From 3525c799134ed6c18066887678bf8370abb32ee5 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 13 Nov 2024 15:58:02 +0200 Subject: [PATCH 001/214] Move smartcontract folder content to abi --- src/{smartcontracts => abi}/argSerializer.spec.ts | 0 src/{smartcontracts => abi}/argSerializer.ts | 0 src/{smartcontracts => abi}/argumentErrorContext.ts | 0 src/{smartcontracts => abi}/code.spec.ts | 0 src/{smartcontracts => abi}/code.ts | 0 src/{smartcontracts => abi}/codeMetadata.spec.ts | 0 src/{smartcontracts => abi}/codeMetadata.ts | 0 src/{smartcontracts => abi}/codec/address.ts | 0 src/{smartcontracts => abi}/codec/arrayVec.ts | 0 src/{smartcontracts => abi}/codec/binary.spec.ts | 0 src/{smartcontracts => abi}/codec/binary.ts | 0 src/{smartcontracts => abi}/codec/binaryCodecUtils.ts | 0 src/{smartcontracts => abi}/codec/boolean.ts | 0 src/{smartcontracts => abi}/codec/bytes.ts | 0 src/{smartcontracts => abi}/codec/codemetadata.ts | 0 src/{smartcontracts => abi}/codec/constants.ts | 0 src/{smartcontracts => abi}/codec/enum.ts | 0 src/{smartcontracts => abi}/codec/explicit-enum.ts | 0 src/{smartcontracts => abi}/codec/fields.ts | 0 src/{smartcontracts => abi}/codec/h256.ts | 0 src/{smartcontracts => abi}/codec/index.ts | 0 src/{smartcontracts => abi}/codec/list.ts | 0 src/{smartcontracts => abi}/codec/managedDecimal.ts | 0 .../codec/managedDecimalSigned.ts | 0 src/{smartcontracts => abi}/codec/nothing.ts | 0 src/{smartcontracts => abi}/codec/numerical.ts | 0 src/{smartcontracts => abi}/codec/option.ts | 0 src/{smartcontracts => abi}/codec/primitive.ts | 0 src/{smartcontracts => abi}/codec/string.ts | 0 src/{smartcontracts => abi}/codec/struct.ts | 0 src/{smartcontracts => abi}/codec/tokenIdentifier.ts | 0 src/{smartcontracts => abi}/codec/tuple.ts | 0 src/{smartcontracts => abi}/codec/utils.ts | 0 src/{smartcontracts => abi}/function.ts | 0 src/{smartcontracts => abi}/index.ts | 0 .../interaction.local.net.spec.ts | 0 src/{smartcontracts => abi}/interaction.spec.ts | 0 src/{smartcontracts => abi}/interaction.ts | 0 src/{smartcontracts => abi}/interactionChecker.spec.ts | 0 src/{smartcontracts => abi}/interactionChecker.ts | 0 src/{smartcontracts => abi}/interface.ts | 0 src/{smartcontracts => abi}/nativeSerializer.spec.ts | 0 src/{smartcontracts => abi}/nativeSerializer.ts | 0 src/{smartcontracts => abi}/query.spec.ts | 0 src/{smartcontracts => abi}/query.ts | 0 src/{smartcontracts => abi}/resultsParser.spec.ts | 0 src/{smartcontracts => abi}/resultsParser.ts | 0 src/{smartcontracts => abi}/returnCode.ts | 0 .../smartContract.local.net.spec.ts | 0 src/{smartcontracts => abi}/smartContract.spec.ts | 0 src/{smartcontracts => abi}/smartContract.ts | 0 .../smartContractResults.local.net.spec.ts | 0 .../transactionPayloadBuilders.spec.ts | 0 .../transactionPayloadBuilders.ts | 0 .../typesystem/abiRegistry.spec.ts | 0 src/{smartcontracts => abi}/typesystem/abiRegistry.ts | 0 src/{smartcontracts => abi}/typesystem/address.ts | 0 src/{smartcontracts => abi}/typesystem/algebraic.ts | 0 src/{smartcontracts => abi}/typesystem/boolean.ts | 0 src/{smartcontracts => abi}/typesystem/bytes.ts | 0 src/{smartcontracts => abi}/typesystem/codeMetadata.ts | 0 src/{smartcontracts => abi}/typesystem/collections.ts | 0 .../typesystem/composite.spec.ts | 0 src/{smartcontracts => abi}/typesystem/composite.ts | 0 .../typesystem/endpoint.spec.ts | 0 src/{smartcontracts => abi}/typesystem/endpoint.ts | 0 src/{smartcontracts => abi}/typesystem/enum.spec.ts | 0 src/{smartcontracts => abi}/typesystem/enum.ts | 0 src/{smartcontracts => abi}/typesystem/event.ts | 0 .../typesystem/explicit-enum.spec.ts | 0 .../typesystem/explicit-enum.ts | 0 src/{smartcontracts => abi}/typesystem/factory.spec.ts | 0 src/{smartcontracts => abi}/typesystem/factory.ts | 0 src/{smartcontracts => abi}/typesystem/fields.ts | 0 src/{smartcontracts => abi}/typesystem/generic.ts | 0 src/{smartcontracts => abi}/typesystem/genericArray.ts | 0 src/{smartcontracts => abi}/typesystem/h256.ts | 0 src/{smartcontracts => abi}/typesystem/index.ts | 1 + .../typesystem/managedDecimal.spec.ts | 0 .../typesystem/managedDecimal.ts | 0 .../typesystem/managedDecimalSigned.ts | 0 src/{smartcontracts => abi}/typesystem/matchers.ts | 0 src/{smartcontracts => abi}/typesystem/nothing.ts | 0 src/{smartcontracts => abi}/typesystem/numerical.ts | 0 src/{smartcontracts => abi}/typesystem/string.ts | 0 src/{smartcontracts => abi}/typesystem/struct.spec.ts | 0 src/{smartcontracts => abi}/typesystem/struct.ts | 0 .../typesystem/tokenIdentifier.ts | 0 src/{smartcontracts => abi}/typesystem/tuple.ts | 0 .../typesystem/typeExpressionParser.spec.ts | 0 .../typesystem/typeExpressionParser.ts | 0 .../typesystem/typeMapper.spec.ts | 0 src/{smartcontracts => abi}/typesystem/typeMapper.ts | 0 src/{smartcontracts => abi}/typesystem/types.spec.ts | 0 src/{smartcontracts => abi}/typesystem/types.ts | 0 src/{smartcontracts => abi}/typesystem/variadic.ts | 0 src/converters/transactionsConverter.ts | 2 +- src/index.ts | 6 +++--- src/proto/serializer.ts | 2 +- src/relayedTransactionV2Builder.ts | 2 +- src/smartContractQueriesController.ts | 3 +-- src/tokenOperations/codec.ts | 4 ++-- src/tokenTransferBuilders.ts | 3 +-- .../delegationTransactionsFactory.ts | 2 +- .../relayedTransactionsFactory.ts | 2 +- .../smartContractTransactionsFactory.ts | 4 +--- .../tokenManagementTransactionsFactory.ts | 2 +- src/transactionsFactories/tokenTransfersDataBuilder.ts | 3 +-- .../transferTransactionsFactory.ts | 10 +--------- .../smartContractTransactionsOutcomeParser.ts | 9 +-------- .../tokenManagementTransactionsOutcomeParser.ts | 2 +- .../transactionEventsParser.ts | 3 +-- src/utils.codec.ts | 2 +- 113 files changed, 21 insertions(+), 41 deletions(-) rename src/{smartcontracts => abi}/argSerializer.spec.ts (100%) rename src/{smartcontracts => abi}/argSerializer.ts (100%) rename src/{smartcontracts => abi}/argumentErrorContext.ts (100%) rename src/{smartcontracts => abi}/code.spec.ts (100%) rename src/{smartcontracts => abi}/code.ts (100%) rename src/{smartcontracts => abi}/codeMetadata.spec.ts (100%) rename src/{smartcontracts => abi}/codeMetadata.ts (100%) rename src/{smartcontracts => abi}/codec/address.ts (100%) rename src/{smartcontracts => abi}/codec/arrayVec.ts (100%) rename src/{smartcontracts => abi}/codec/binary.spec.ts (100%) rename src/{smartcontracts => abi}/codec/binary.ts (100%) rename src/{smartcontracts => abi}/codec/binaryCodecUtils.ts (100%) rename src/{smartcontracts => abi}/codec/boolean.ts (100%) rename src/{smartcontracts => abi}/codec/bytes.ts (100%) rename src/{smartcontracts => abi}/codec/codemetadata.ts (100%) rename src/{smartcontracts => abi}/codec/constants.ts (100%) rename src/{smartcontracts => abi}/codec/enum.ts (100%) rename src/{smartcontracts => abi}/codec/explicit-enum.ts (100%) rename src/{smartcontracts => abi}/codec/fields.ts (100%) rename src/{smartcontracts => abi}/codec/h256.ts (100%) rename src/{smartcontracts => abi}/codec/index.ts (100%) rename src/{smartcontracts => abi}/codec/list.ts (100%) rename src/{smartcontracts => abi}/codec/managedDecimal.ts (100%) rename src/{smartcontracts => abi}/codec/managedDecimalSigned.ts (100%) rename src/{smartcontracts => abi}/codec/nothing.ts (100%) rename src/{smartcontracts => abi}/codec/numerical.ts (100%) rename src/{smartcontracts => abi}/codec/option.ts (100%) rename src/{smartcontracts => abi}/codec/primitive.ts (100%) rename src/{smartcontracts => abi}/codec/string.ts (100%) rename src/{smartcontracts => abi}/codec/struct.ts (100%) rename src/{smartcontracts => abi}/codec/tokenIdentifier.ts (100%) rename src/{smartcontracts => abi}/codec/tuple.ts (100%) rename src/{smartcontracts => abi}/codec/utils.ts (100%) rename src/{smartcontracts => abi}/function.ts (100%) rename src/{smartcontracts => abi}/index.ts (100%) rename src/{smartcontracts => abi}/interaction.local.net.spec.ts (100%) rename src/{smartcontracts => abi}/interaction.spec.ts (100%) rename src/{smartcontracts => abi}/interaction.ts (100%) rename src/{smartcontracts => abi}/interactionChecker.spec.ts (100%) rename src/{smartcontracts => abi}/interactionChecker.ts (100%) rename src/{smartcontracts => abi}/interface.ts (100%) rename src/{smartcontracts => abi}/nativeSerializer.spec.ts (100%) rename src/{smartcontracts => abi}/nativeSerializer.ts (100%) rename src/{smartcontracts => abi}/query.spec.ts (100%) rename src/{smartcontracts => abi}/query.ts (100%) rename src/{smartcontracts => abi}/resultsParser.spec.ts (100%) rename src/{smartcontracts => abi}/resultsParser.ts (100%) rename src/{smartcontracts => abi}/returnCode.ts (100%) rename src/{smartcontracts => abi}/smartContract.local.net.spec.ts (100%) rename src/{smartcontracts => abi}/smartContract.spec.ts (100%) rename src/{smartcontracts => abi}/smartContract.ts (100%) rename src/{smartcontracts => abi}/smartContractResults.local.net.spec.ts (100%) rename src/{smartcontracts => abi}/transactionPayloadBuilders.spec.ts (100%) rename src/{smartcontracts => abi}/transactionPayloadBuilders.ts (100%) rename src/{smartcontracts => abi}/typesystem/abiRegistry.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/abiRegistry.ts (100%) rename src/{smartcontracts => abi}/typesystem/address.ts (100%) rename src/{smartcontracts => abi}/typesystem/algebraic.ts (100%) rename src/{smartcontracts => abi}/typesystem/boolean.ts (100%) rename src/{smartcontracts => abi}/typesystem/bytes.ts (100%) rename src/{smartcontracts => abi}/typesystem/codeMetadata.ts (100%) rename src/{smartcontracts => abi}/typesystem/collections.ts (100%) rename src/{smartcontracts => abi}/typesystem/composite.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/composite.ts (100%) rename src/{smartcontracts => abi}/typesystem/endpoint.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/endpoint.ts (100%) rename src/{smartcontracts => abi}/typesystem/enum.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/enum.ts (100%) rename src/{smartcontracts => abi}/typesystem/event.ts (100%) rename src/{smartcontracts => abi}/typesystem/explicit-enum.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/explicit-enum.ts (100%) rename src/{smartcontracts => abi}/typesystem/factory.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/factory.ts (100%) rename src/{smartcontracts => abi}/typesystem/fields.ts (100%) rename src/{smartcontracts => abi}/typesystem/generic.ts (100%) rename src/{smartcontracts => abi}/typesystem/genericArray.ts (100%) rename src/{smartcontracts => abi}/typesystem/h256.ts (100%) rename src/{smartcontracts => abi}/typesystem/index.ts (97%) rename src/{smartcontracts => abi}/typesystem/managedDecimal.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/managedDecimal.ts (100%) rename src/{smartcontracts => abi}/typesystem/managedDecimalSigned.ts (100%) rename src/{smartcontracts => abi}/typesystem/matchers.ts (100%) rename src/{smartcontracts => abi}/typesystem/nothing.ts (100%) rename src/{smartcontracts => abi}/typesystem/numerical.ts (100%) rename src/{smartcontracts => abi}/typesystem/string.ts (100%) rename src/{smartcontracts => abi}/typesystem/struct.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/struct.ts (100%) rename src/{smartcontracts => abi}/typesystem/tokenIdentifier.ts (100%) rename src/{smartcontracts => abi}/typesystem/tuple.ts (100%) rename src/{smartcontracts => abi}/typesystem/typeExpressionParser.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/typeExpressionParser.ts (100%) rename src/{smartcontracts => abi}/typesystem/typeMapper.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/typeMapper.ts (100%) rename src/{smartcontracts => abi}/typesystem/types.spec.ts (100%) rename src/{smartcontracts => abi}/typesystem/types.ts (100%) rename src/{smartcontracts => abi}/typesystem/variadic.ts (100%) diff --git a/src/smartcontracts/argSerializer.spec.ts b/src/abi/argSerializer.spec.ts similarity index 100% rename from src/smartcontracts/argSerializer.spec.ts rename to src/abi/argSerializer.spec.ts diff --git a/src/smartcontracts/argSerializer.ts b/src/abi/argSerializer.ts similarity index 100% rename from src/smartcontracts/argSerializer.ts rename to src/abi/argSerializer.ts diff --git a/src/smartcontracts/argumentErrorContext.ts b/src/abi/argumentErrorContext.ts similarity index 100% rename from src/smartcontracts/argumentErrorContext.ts rename to src/abi/argumentErrorContext.ts diff --git a/src/smartcontracts/code.spec.ts b/src/abi/code.spec.ts similarity index 100% rename from src/smartcontracts/code.spec.ts rename to src/abi/code.spec.ts diff --git a/src/smartcontracts/code.ts b/src/abi/code.ts similarity index 100% rename from src/smartcontracts/code.ts rename to src/abi/code.ts diff --git a/src/smartcontracts/codeMetadata.spec.ts b/src/abi/codeMetadata.spec.ts similarity index 100% rename from src/smartcontracts/codeMetadata.spec.ts rename to src/abi/codeMetadata.spec.ts diff --git a/src/smartcontracts/codeMetadata.ts b/src/abi/codeMetadata.ts similarity index 100% rename from src/smartcontracts/codeMetadata.ts rename to src/abi/codeMetadata.ts diff --git a/src/smartcontracts/codec/address.ts b/src/abi/codec/address.ts similarity index 100% rename from src/smartcontracts/codec/address.ts rename to src/abi/codec/address.ts diff --git a/src/smartcontracts/codec/arrayVec.ts b/src/abi/codec/arrayVec.ts similarity index 100% rename from src/smartcontracts/codec/arrayVec.ts rename to src/abi/codec/arrayVec.ts diff --git a/src/smartcontracts/codec/binary.spec.ts b/src/abi/codec/binary.spec.ts similarity index 100% rename from src/smartcontracts/codec/binary.spec.ts rename to src/abi/codec/binary.spec.ts diff --git a/src/smartcontracts/codec/binary.ts b/src/abi/codec/binary.ts similarity index 100% rename from src/smartcontracts/codec/binary.ts rename to src/abi/codec/binary.ts diff --git a/src/smartcontracts/codec/binaryCodecUtils.ts b/src/abi/codec/binaryCodecUtils.ts similarity index 100% rename from src/smartcontracts/codec/binaryCodecUtils.ts rename to src/abi/codec/binaryCodecUtils.ts diff --git a/src/smartcontracts/codec/boolean.ts b/src/abi/codec/boolean.ts similarity index 100% rename from src/smartcontracts/codec/boolean.ts rename to src/abi/codec/boolean.ts diff --git a/src/smartcontracts/codec/bytes.ts b/src/abi/codec/bytes.ts similarity index 100% rename from src/smartcontracts/codec/bytes.ts rename to src/abi/codec/bytes.ts diff --git a/src/smartcontracts/codec/codemetadata.ts b/src/abi/codec/codemetadata.ts similarity index 100% rename from src/smartcontracts/codec/codemetadata.ts rename to src/abi/codec/codemetadata.ts diff --git a/src/smartcontracts/codec/constants.ts b/src/abi/codec/constants.ts similarity index 100% rename from src/smartcontracts/codec/constants.ts rename to src/abi/codec/constants.ts diff --git a/src/smartcontracts/codec/enum.ts b/src/abi/codec/enum.ts similarity index 100% rename from src/smartcontracts/codec/enum.ts rename to src/abi/codec/enum.ts diff --git a/src/smartcontracts/codec/explicit-enum.ts b/src/abi/codec/explicit-enum.ts similarity index 100% rename from src/smartcontracts/codec/explicit-enum.ts rename to src/abi/codec/explicit-enum.ts diff --git a/src/smartcontracts/codec/fields.ts b/src/abi/codec/fields.ts similarity index 100% rename from src/smartcontracts/codec/fields.ts rename to src/abi/codec/fields.ts diff --git a/src/smartcontracts/codec/h256.ts b/src/abi/codec/h256.ts similarity index 100% rename from src/smartcontracts/codec/h256.ts rename to src/abi/codec/h256.ts diff --git a/src/smartcontracts/codec/index.ts b/src/abi/codec/index.ts similarity index 100% rename from src/smartcontracts/codec/index.ts rename to src/abi/codec/index.ts diff --git a/src/smartcontracts/codec/list.ts b/src/abi/codec/list.ts similarity index 100% rename from src/smartcontracts/codec/list.ts rename to src/abi/codec/list.ts diff --git a/src/smartcontracts/codec/managedDecimal.ts b/src/abi/codec/managedDecimal.ts similarity index 100% rename from src/smartcontracts/codec/managedDecimal.ts rename to src/abi/codec/managedDecimal.ts diff --git a/src/smartcontracts/codec/managedDecimalSigned.ts b/src/abi/codec/managedDecimalSigned.ts similarity index 100% rename from src/smartcontracts/codec/managedDecimalSigned.ts rename to src/abi/codec/managedDecimalSigned.ts diff --git a/src/smartcontracts/codec/nothing.ts b/src/abi/codec/nothing.ts similarity index 100% rename from src/smartcontracts/codec/nothing.ts rename to src/abi/codec/nothing.ts diff --git a/src/smartcontracts/codec/numerical.ts b/src/abi/codec/numerical.ts similarity index 100% rename from src/smartcontracts/codec/numerical.ts rename to src/abi/codec/numerical.ts diff --git a/src/smartcontracts/codec/option.ts b/src/abi/codec/option.ts similarity index 100% rename from src/smartcontracts/codec/option.ts rename to src/abi/codec/option.ts diff --git a/src/smartcontracts/codec/primitive.ts b/src/abi/codec/primitive.ts similarity index 100% rename from src/smartcontracts/codec/primitive.ts rename to src/abi/codec/primitive.ts diff --git a/src/smartcontracts/codec/string.ts b/src/abi/codec/string.ts similarity index 100% rename from src/smartcontracts/codec/string.ts rename to src/abi/codec/string.ts diff --git a/src/smartcontracts/codec/struct.ts b/src/abi/codec/struct.ts similarity index 100% rename from src/smartcontracts/codec/struct.ts rename to src/abi/codec/struct.ts diff --git a/src/smartcontracts/codec/tokenIdentifier.ts b/src/abi/codec/tokenIdentifier.ts similarity index 100% rename from src/smartcontracts/codec/tokenIdentifier.ts rename to src/abi/codec/tokenIdentifier.ts diff --git a/src/smartcontracts/codec/tuple.ts b/src/abi/codec/tuple.ts similarity index 100% rename from src/smartcontracts/codec/tuple.ts rename to src/abi/codec/tuple.ts diff --git a/src/smartcontracts/codec/utils.ts b/src/abi/codec/utils.ts similarity index 100% rename from src/smartcontracts/codec/utils.ts rename to src/abi/codec/utils.ts diff --git a/src/smartcontracts/function.ts b/src/abi/function.ts similarity index 100% rename from src/smartcontracts/function.ts rename to src/abi/function.ts diff --git a/src/smartcontracts/index.ts b/src/abi/index.ts similarity index 100% rename from src/smartcontracts/index.ts rename to src/abi/index.ts diff --git a/src/smartcontracts/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts similarity index 100% rename from src/smartcontracts/interaction.local.net.spec.ts rename to src/abi/interaction.local.net.spec.ts diff --git a/src/smartcontracts/interaction.spec.ts b/src/abi/interaction.spec.ts similarity index 100% rename from src/smartcontracts/interaction.spec.ts rename to src/abi/interaction.spec.ts diff --git a/src/smartcontracts/interaction.ts b/src/abi/interaction.ts similarity index 100% rename from src/smartcontracts/interaction.ts rename to src/abi/interaction.ts diff --git a/src/smartcontracts/interactionChecker.spec.ts b/src/abi/interactionChecker.spec.ts similarity index 100% rename from src/smartcontracts/interactionChecker.spec.ts rename to src/abi/interactionChecker.spec.ts diff --git a/src/smartcontracts/interactionChecker.ts b/src/abi/interactionChecker.ts similarity index 100% rename from src/smartcontracts/interactionChecker.ts rename to src/abi/interactionChecker.ts diff --git a/src/smartcontracts/interface.ts b/src/abi/interface.ts similarity index 100% rename from src/smartcontracts/interface.ts rename to src/abi/interface.ts diff --git a/src/smartcontracts/nativeSerializer.spec.ts b/src/abi/nativeSerializer.spec.ts similarity index 100% rename from src/smartcontracts/nativeSerializer.spec.ts rename to src/abi/nativeSerializer.spec.ts diff --git a/src/smartcontracts/nativeSerializer.ts b/src/abi/nativeSerializer.ts similarity index 100% rename from src/smartcontracts/nativeSerializer.ts rename to src/abi/nativeSerializer.ts diff --git a/src/smartcontracts/query.spec.ts b/src/abi/query.spec.ts similarity index 100% rename from src/smartcontracts/query.spec.ts rename to src/abi/query.spec.ts diff --git a/src/smartcontracts/query.ts b/src/abi/query.ts similarity index 100% rename from src/smartcontracts/query.ts rename to src/abi/query.ts diff --git a/src/smartcontracts/resultsParser.spec.ts b/src/abi/resultsParser.spec.ts similarity index 100% rename from src/smartcontracts/resultsParser.spec.ts rename to src/abi/resultsParser.spec.ts diff --git a/src/smartcontracts/resultsParser.ts b/src/abi/resultsParser.ts similarity index 100% rename from src/smartcontracts/resultsParser.ts rename to src/abi/resultsParser.ts diff --git a/src/smartcontracts/returnCode.ts b/src/abi/returnCode.ts similarity index 100% rename from src/smartcontracts/returnCode.ts rename to src/abi/returnCode.ts diff --git a/src/smartcontracts/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts similarity index 100% rename from src/smartcontracts/smartContract.local.net.spec.ts rename to src/abi/smartContract.local.net.spec.ts diff --git a/src/smartcontracts/smartContract.spec.ts b/src/abi/smartContract.spec.ts similarity index 100% rename from src/smartcontracts/smartContract.spec.ts rename to src/abi/smartContract.spec.ts diff --git a/src/smartcontracts/smartContract.ts b/src/abi/smartContract.ts similarity index 100% rename from src/smartcontracts/smartContract.ts rename to src/abi/smartContract.ts diff --git a/src/smartcontracts/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts similarity index 100% rename from src/smartcontracts/smartContractResults.local.net.spec.ts rename to src/abi/smartContractResults.local.net.spec.ts diff --git a/src/smartcontracts/transactionPayloadBuilders.spec.ts b/src/abi/transactionPayloadBuilders.spec.ts similarity index 100% rename from src/smartcontracts/transactionPayloadBuilders.spec.ts rename to src/abi/transactionPayloadBuilders.spec.ts diff --git a/src/smartcontracts/transactionPayloadBuilders.ts b/src/abi/transactionPayloadBuilders.ts similarity index 100% rename from src/smartcontracts/transactionPayloadBuilders.ts rename to src/abi/transactionPayloadBuilders.ts diff --git a/src/smartcontracts/typesystem/abiRegistry.spec.ts b/src/abi/typesystem/abiRegistry.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/abiRegistry.spec.ts rename to src/abi/typesystem/abiRegistry.spec.ts diff --git a/src/smartcontracts/typesystem/abiRegistry.ts b/src/abi/typesystem/abiRegistry.ts similarity index 100% rename from src/smartcontracts/typesystem/abiRegistry.ts rename to src/abi/typesystem/abiRegistry.ts diff --git a/src/smartcontracts/typesystem/address.ts b/src/abi/typesystem/address.ts similarity index 100% rename from src/smartcontracts/typesystem/address.ts rename to src/abi/typesystem/address.ts diff --git a/src/smartcontracts/typesystem/algebraic.ts b/src/abi/typesystem/algebraic.ts similarity index 100% rename from src/smartcontracts/typesystem/algebraic.ts rename to src/abi/typesystem/algebraic.ts diff --git a/src/smartcontracts/typesystem/boolean.ts b/src/abi/typesystem/boolean.ts similarity index 100% rename from src/smartcontracts/typesystem/boolean.ts rename to src/abi/typesystem/boolean.ts diff --git a/src/smartcontracts/typesystem/bytes.ts b/src/abi/typesystem/bytes.ts similarity index 100% rename from src/smartcontracts/typesystem/bytes.ts rename to src/abi/typesystem/bytes.ts diff --git a/src/smartcontracts/typesystem/codeMetadata.ts b/src/abi/typesystem/codeMetadata.ts similarity index 100% rename from src/smartcontracts/typesystem/codeMetadata.ts rename to src/abi/typesystem/codeMetadata.ts diff --git a/src/smartcontracts/typesystem/collections.ts b/src/abi/typesystem/collections.ts similarity index 100% rename from src/smartcontracts/typesystem/collections.ts rename to src/abi/typesystem/collections.ts diff --git a/src/smartcontracts/typesystem/composite.spec.ts b/src/abi/typesystem/composite.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/composite.spec.ts rename to src/abi/typesystem/composite.spec.ts diff --git a/src/smartcontracts/typesystem/composite.ts b/src/abi/typesystem/composite.ts similarity index 100% rename from src/smartcontracts/typesystem/composite.ts rename to src/abi/typesystem/composite.ts diff --git a/src/smartcontracts/typesystem/endpoint.spec.ts b/src/abi/typesystem/endpoint.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/endpoint.spec.ts rename to src/abi/typesystem/endpoint.spec.ts diff --git a/src/smartcontracts/typesystem/endpoint.ts b/src/abi/typesystem/endpoint.ts similarity index 100% rename from src/smartcontracts/typesystem/endpoint.ts rename to src/abi/typesystem/endpoint.ts diff --git a/src/smartcontracts/typesystem/enum.spec.ts b/src/abi/typesystem/enum.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/enum.spec.ts rename to src/abi/typesystem/enum.spec.ts diff --git a/src/smartcontracts/typesystem/enum.ts b/src/abi/typesystem/enum.ts similarity index 100% rename from src/smartcontracts/typesystem/enum.ts rename to src/abi/typesystem/enum.ts diff --git a/src/smartcontracts/typesystem/event.ts b/src/abi/typesystem/event.ts similarity index 100% rename from src/smartcontracts/typesystem/event.ts rename to src/abi/typesystem/event.ts diff --git a/src/smartcontracts/typesystem/explicit-enum.spec.ts b/src/abi/typesystem/explicit-enum.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/explicit-enum.spec.ts rename to src/abi/typesystem/explicit-enum.spec.ts diff --git a/src/smartcontracts/typesystem/explicit-enum.ts b/src/abi/typesystem/explicit-enum.ts similarity index 100% rename from src/smartcontracts/typesystem/explicit-enum.ts rename to src/abi/typesystem/explicit-enum.ts diff --git a/src/smartcontracts/typesystem/factory.spec.ts b/src/abi/typesystem/factory.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/factory.spec.ts rename to src/abi/typesystem/factory.spec.ts diff --git a/src/smartcontracts/typesystem/factory.ts b/src/abi/typesystem/factory.ts similarity index 100% rename from src/smartcontracts/typesystem/factory.ts rename to src/abi/typesystem/factory.ts diff --git a/src/smartcontracts/typesystem/fields.ts b/src/abi/typesystem/fields.ts similarity index 100% rename from src/smartcontracts/typesystem/fields.ts rename to src/abi/typesystem/fields.ts diff --git a/src/smartcontracts/typesystem/generic.ts b/src/abi/typesystem/generic.ts similarity index 100% rename from src/smartcontracts/typesystem/generic.ts rename to src/abi/typesystem/generic.ts diff --git a/src/smartcontracts/typesystem/genericArray.ts b/src/abi/typesystem/genericArray.ts similarity index 100% rename from src/smartcontracts/typesystem/genericArray.ts rename to src/abi/typesystem/genericArray.ts diff --git a/src/smartcontracts/typesystem/h256.ts b/src/abi/typesystem/h256.ts similarity index 100% rename from src/smartcontracts/typesystem/h256.ts rename to src/abi/typesystem/h256.ts diff --git a/src/smartcontracts/typesystem/index.ts b/src/abi/typesystem/index.ts similarity index 97% rename from src/smartcontracts/typesystem/index.ts rename to src/abi/typesystem/index.ts index 936c40328..f05527ba3 100644 --- a/src/smartcontracts/typesystem/index.ts +++ b/src/abi/typesystem/index.ts @@ -12,6 +12,7 @@ export * from "./codeMetadata"; export * from "./composite"; export * from "./endpoint"; export * from "./enum"; +export * from "./event"; export * from "./explicit-enum"; export * from "./factory"; export * from "./fields"; diff --git a/src/smartcontracts/typesystem/managedDecimal.spec.ts b/src/abi/typesystem/managedDecimal.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/managedDecimal.spec.ts rename to src/abi/typesystem/managedDecimal.spec.ts diff --git a/src/smartcontracts/typesystem/managedDecimal.ts b/src/abi/typesystem/managedDecimal.ts similarity index 100% rename from src/smartcontracts/typesystem/managedDecimal.ts rename to src/abi/typesystem/managedDecimal.ts diff --git a/src/smartcontracts/typesystem/managedDecimalSigned.ts b/src/abi/typesystem/managedDecimalSigned.ts similarity index 100% rename from src/smartcontracts/typesystem/managedDecimalSigned.ts rename to src/abi/typesystem/managedDecimalSigned.ts diff --git a/src/smartcontracts/typesystem/matchers.ts b/src/abi/typesystem/matchers.ts similarity index 100% rename from src/smartcontracts/typesystem/matchers.ts rename to src/abi/typesystem/matchers.ts diff --git a/src/smartcontracts/typesystem/nothing.ts b/src/abi/typesystem/nothing.ts similarity index 100% rename from src/smartcontracts/typesystem/nothing.ts rename to src/abi/typesystem/nothing.ts diff --git a/src/smartcontracts/typesystem/numerical.ts b/src/abi/typesystem/numerical.ts similarity index 100% rename from src/smartcontracts/typesystem/numerical.ts rename to src/abi/typesystem/numerical.ts diff --git a/src/smartcontracts/typesystem/string.ts b/src/abi/typesystem/string.ts similarity index 100% rename from src/smartcontracts/typesystem/string.ts rename to src/abi/typesystem/string.ts diff --git a/src/smartcontracts/typesystem/struct.spec.ts b/src/abi/typesystem/struct.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/struct.spec.ts rename to src/abi/typesystem/struct.spec.ts diff --git a/src/smartcontracts/typesystem/struct.ts b/src/abi/typesystem/struct.ts similarity index 100% rename from src/smartcontracts/typesystem/struct.ts rename to src/abi/typesystem/struct.ts diff --git a/src/smartcontracts/typesystem/tokenIdentifier.ts b/src/abi/typesystem/tokenIdentifier.ts similarity index 100% rename from src/smartcontracts/typesystem/tokenIdentifier.ts rename to src/abi/typesystem/tokenIdentifier.ts diff --git a/src/smartcontracts/typesystem/tuple.ts b/src/abi/typesystem/tuple.ts similarity index 100% rename from src/smartcontracts/typesystem/tuple.ts rename to src/abi/typesystem/tuple.ts diff --git a/src/smartcontracts/typesystem/typeExpressionParser.spec.ts b/src/abi/typesystem/typeExpressionParser.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/typeExpressionParser.spec.ts rename to src/abi/typesystem/typeExpressionParser.spec.ts diff --git a/src/smartcontracts/typesystem/typeExpressionParser.ts b/src/abi/typesystem/typeExpressionParser.ts similarity index 100% rename from src/smartcontracts/typesystem/typeExpressionParser.ts rename to src/abi/typesystem/typeExpressionParser.ts diff --git a/src/smartcontracts/typesystem/typeMapper.spec.ts b/src/abi/typesystem/typeMapper.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/typeMapper.spec.ts rename to src/abi/typesystem/typeMapper.spec.ts diff --git a/src/smartcontracts/typesystem/typeMapper.ts b/src/abi/typesystem/typeMapper.ts similarity index 100% rename from src/smartcontracts/typesystem/typeMapper.ts rename to src/abi/typesystem/typeMapper.ts diff --git a/src/smartcontracts/typesystem/types.spec.ts b/src/abi/typesystem/types.spec.ts similarity index 100% rename from src/smartcontracts/typesystem/types.spec.ts rename to src/abi/typesystem/types.spec.ts diff --git a/src/smartcontracts/typesystem/types.ts b/src/abi/typesystem/types.ts similarity index 100% rename from src/smartcontracts/typesystem/types.ts rename to src/abi/typesystem/types.ts diff --git a/src/smartcontracts/typesystem/variadic.ts b/src/abi/typesystem/variadic.ts similarity index 100% rename from src/smartcontracts/typesystem/variadic.ts rename to src/abi/typesystem/variadic.ts diff --git a/src/converters/transactionsConverter.ts b/src/converters/transactionsConverter.ts index 966ec86e4..5d47886e3 100644 --- a/src/converters/transactionsConverter.ts +++ b/src/converters/transactionsConverter.ts @@ -1,6 +1,6 @@ +import { ResultsParser } from "../abi"; import { IPlainTransactionObject, ITransaction } from "../interface"; import { IContractResultItem, ITransactionEvent, ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { ResultsParser } from "../smartcontracts"; import { Transaction } from "../transaction"; import { SmartContractCallOutcome, diff --git a/src/index.ts b/src/index.ts index 08c8affee..08a84ad38 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,7 @@ require("./globals"); +export * from "./abi"; export * from "./account"; export * from "./adapters"; export * from "./address"; @@ -19,19 +20,18 @@ export * from "./interfaceOfNetwork"; export * from "./logger"; export * from "./message"; export * from "./networkParams"; +export * from "./networkProviders"; export * from "./relayedTransactionV1Builder"; export * from "./relayedTransactionV2Builder"; export * from "./signableMessage"; export * from "./smartContractQueriesController"; -export * from "./smartcontracts"; export * from "./tokenOperations"; export * from "./tokens"; export * from "./transaction"; export * from "./transactionComputer"; export * from "./transactionPayload"; -export * from "./transactionWatcher"; export * from "./transactionsFactories"; export * from "./transactionsOutcomeParsers"; +export * from "./transactionWatcher"; export * from "./utils"; -export * from "./networkProviders"; export * from "./wallet"; diff --git a/src/proto/serializer.ts b/src/proto/serializer.ts index 2f46ee425..c690b5e4d 100644 --- a/src/proto/serializer.ts +++ b/src/proto/serializer.ts @@ -1,9 +1,9 @@ import BigNumber from "bignumber.js"; +import { bigIntToBuffer } from "../abi/codec/utils"; import { Address } from "../address"; import { TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_OPTIONS_TX_GUARDED } from "../constants"; import * as errors from "../errors"; import { ITransaction, ITransactionValue } from "../interface"; -import { bigIntToBuffer } from "../smartcontracts/codec/utils"; import { Transaction } from "../transaction"; /** diff --git a/src/relayedTransactionV2Builder.ts b/src/relayedTransactionV2Builder.ts index b5b01b1a6..54d1595b7 100644 --- a/src/relayedTransactionV2Builder.ts +++ b/src/relayedTransactionV2Builder.ts @@ -1,7 +1,7 @@ +import { AddressValue, ArgSerializer, BytesValue, U64Value } from "./abi"; import { ErrGasLimitShouldBe0ForInnerTransaction, ErrInvalidRelayedV2BuilderArguments } from "./errors"; import { IAddress, IGasLimit, INonce } from "./interface"; import { INetworkConfig } from "./interfaceOfNetwork"; -import { AddressValue, ArgSerializer, BytesValue, U64Value } from "./smartcontracts"; import { Transaction } from "./transaction"; import { TransactionPayload } from "./transactionPayload"; diff --git a/src/smartContractQueriesController.ts b/src/smartContractQueriesController.ts index d156742fc..aee47a980 100644 --- a/src/smartContractQueriesController.ts +++ b/src/smartContractQueriesController.ts @@ -1,8 +1,7 @@ +import { ArgSerializer, ContractFunction, EndpointDefinition, isTyped, NativeSerializer, ResultsParser } from "./abi"; import { Err, ErrSmartContractQuery } from "./errors"; import { IContractQueryResponse } from "./interfaceOfNetwork"; import { SmartContractQuery, SmartContractQueryResponse } from "./smartContractQuery"; -import { ArgSerializer, ContractFunction, EndpointDefinition, NativeSerializer, ResultsParser } from "./smartcontracts"; -import { isTyped } from "./smartcontracts/typesystem"; interface IAbi { getEndpoint(name: string | ContractFunction): EndpointDefinition; diff --git a/src/tokenOperations/codec.ts b/src/tokenOperations/codec.ts index 64b4c4844..3fc5cad65 100644 --- a/src/tokenOperations/codec.ts +++ b/src/tokenOperations/codec.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import * as contractsCodecUtils from "../smartcontracts/codec/utils"; +import * as contractsCodecUtils from "../abi/codec/utils"; import * as codecUtils from "../utils.codec"; export function stringToBuffer(value: string): Buffer { @@ -22,7 +22,7 @@ export function bigIntToBuffer(value: BigNumber.Value): Buffer { return contractsCodecUtils.bigIntToBuffer(value); } -export { utf8ToHex, bigIntToHex, addressToHex } from "../utils.codec"; +export { addressToHex, bigIntToHex, utf8ToHex } from "../utils.codec"; export function bufferToHex(value: Buffer) { const hex = value.toString("hex"); diff --git a/src/tokenTransferBuilders.ts b/src/tokenTransferBuilders.ts index a557ca363..d4b6d37ad 100644 --- a/src/tokenTransferBuilders.ts +++ b/src/tokenTransferBuilders.ts @@ -1,7 +1,6 @@ +import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, TypedValue, U16Value, U64Value } from "./abi"; import { Address } from "./address"; import { IAddress, ITokenTransfer } from "./interface"; -import { ArgSerializer } from "./smartcontracts/argSerializer"; -import { AddressValue, BigUIntValue, BytesValue, TypedValue, U16Value, U64Value } from "./smartcontracts/typesystem"; import { TokenTransfer } from "./tokens"; import { TransactionPayload } from "./transactionPayload"; diff --git a/src/transactionsFactories/delegationTransactionsFactory.ts b/src/transactionsFactories/delegationTransactionsFactory.ts index 0b8062ec2..8e0b2c662 100644 --- a/src/transactionsFactories/delegationTransactionsFactory.ts +++ b/src/transactionsFactories/delegationTransactionsFactory.ts @@ -1,8 +1,8 @@ +import { ArgSerializer, BigUIntValue, BytesValue, StringValue } from "../abi"; import { Address } from "../address"; import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../constants"; import { Err } from "../errors"; import { IAddress } from "../interface"; -import { ArgSerializer, BigUIntValue, BytesValue, StringValue } from "../smartcontracts"; import { Transaction } from "../transaction"; import { TransactionBuilder } from "./transactionBuilder"; diff --git a/src/transactionsFactories/relayedTransactionsFactory.ts b/src/transactionsFactories/relayedTransactionsFactory.ts index b69741025..13c2a8e6c 100644 --- a/src/transactionsFactories/relayedTransactionsFactory.ts +++ b/src/transactionsFactories/relayedTransactionsFactory.ts @@ -1,8 +1,8 @@ import BigNumber from "bignumber.js"; +import { AddressValue, ArgSerializer, BytesValue, U64Value } from "../abi"; import { Address } from "../address"; import { ErrInvalidInnerTransaction } from "../errors"; import { IAddress, ITransaction } from "../interface"; -import { AddressValue, ArgSerializer, BytesValue, U64Value } from "../smartcontracts"; import { Transaction } from "../transaction"; const JSONbig = require("json-bigint"); diff --git a/src/transactionsFactories/smartContractTransactionsFactory.ts b/src/transactionsFactories/smartContractTransactionsFactory.ts index 6102ebac5..dc55129b1 100644 --- a/src/transactionsFactories/smartContractTransactionsFactory.ts +++ b/src/transactionsFactories/smartContractTransactionsFactory.ts @@ -1,11 +1,9 @@ +import { ArgSerializer, CodeMetadata, ContractFunction, EndpointDefinition, isTyped, NativeSerializer } from "../abi"; import { Address } from "../address"; import { CONTRACT_DEPLOY_ADDRESS_HEX, VM_TYPE_WASM_VM } from "../constants"; import { Err } from "../errors"; import { IAddress } from "../interface"; import { Logger } from "../logger"; -import { ArgSerializer, CodeMetadata, ContractFunction, EndpointDefinition } from "../smartcontracts"; -import { NativeSerializer } from "../smartcontracts/nativeSerializer"; -import { isTyped } from "../smartcontracts/typesystem"; import { TokenComputer, TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; import { byteArrayToHex, utf8ToHex } from "../utils.codec"; diff --git a/src/transactionsFactories/tokenManagementTransactionsFactory.ts b/src/transactionsFactories/tokenManagementTransactionsFactory.ts index b674313a5..eff2cdf69 100644 --- a/src/transactionsFactories/tokenManagementTransactionsFactory.ts +++ b/src/transactionsFactories/tokenManagementTransactionsFactory.ts @@ -1,9 +1,9 @@ +import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, StringValue } from "../abi"; import { Address } from "../address"; import { ESDT_CONTRACT_ADDRESS_HEX } from "../constants"; import { ErrBadUsage } from "../errors"; import { IAddress } from "../interface"; import { Logger } from "../logger"; -import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, StringValue } from "../smartcontracts"; import { Transaction } from "../transaction"; import { TransactionBuilder } from "./transactionBuilder"; diff --git a/src/transactionsFactories/tokenTransfersDataBuilder.ts b/src/transactionsFactories/tokenTransfersDataBuilder.ts index 45cd92162..75e8b2409 100644 --- a/src/transactionsFactories/tokenTransfersDataBuilder.ts +++ b/src/transactionsFactories/tokenTransfersDataBuilder.ts @@ -1,6 +1,5 @@ +import { AddressValue, ArgSerializer, BigUIntValue, TokenIdentifierValue, TypedValue, U32Value } from "../abi"; import { IAddress } from "../interface"; -import { ArgSerializer } from "../smartcontracts/argSerializer"; -import { AddressValue, BigUIntValue, TokenIdentifierValue, TypedValue, U32Value } from "../smartcontracts/typesystem"; import { TokenComputer, TokenTransfer } from "../tokens"; export class TokenTransfersDataBuilder { diff --git a/src/transactionsFactories/transferTransactionsFactory.ts b/src/transactionsFactories/transferTransactionsFactory.ts index 84dcf2a63..b4e43c079 100644 --- a/src/transactionsFactories/transferTransactionsFactory.ts +++ b/src/transactionsFactories/transferTransactionsFactory.ts @@ -1,3 +1,4 @@ +import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, TypedValue, U16Value, U64Value } from "../abi"; import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../constants"; import { Err, ErrBadUsage } from "../errors"; import { @@ -10,15 +11,6 @@ import { ITransactionPayload, ITransactionValue, } from "../interface"; -import { - AddressValue, - ArgSerializer, - BigUIntValue, - BytesValue, - TypedValue, - U16Value, - U64Value, -} from "../smartcontracts"; import { TokenComputer, TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; import { TransactionPayload } from "../transactionPayload"; diff --git a/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.ts b/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.ts index 9f57b4782..f575622bb 100644 --- a/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.ts +++ b/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.ts @@ -1,15 +1,8 @@ +import { ArgSerializer, EndpointDefinition, ResultsParser, ReturnCode, Type, UntypedOutcomeBundle } from "../abi"; import { Address } from "../address"; import { ARGUMENTS_SEPARATOR } from "../constants"; import { Err } from "../errors"; import { IContractResultItem, ITransactionEvent, ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { - ArgSerializer, - EndpointDefinition, - ResultsParser, - ReturnCode, - Type, - UntypedOutcomeBundle, -} from "../smartcontracts"; import { SmartContractCallOutcome, TransactionOutcome, findEventsByIdentifier } from "./resources"; enum Events { diff --git a/src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.ts b/src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.ts index fcf78d585..43345ddc2 100644 --- a/src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.ts +++ b/src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.ts @@ -1,8 +1,8 @@ +import { bufferToBigInt } from "../abi/codec/utils"; import { Address } from "../address"; import { TransactionsConverter } from "../converters/transactionsConverter"; import { ErrParseTransactionOutcome } from "../errors"; import { ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { bufferToBigInt } from "../smartcontracts/codec/utils"; import { TransactionEvent, TransactionOutcome, findEventsByIdentifier } from "./resources"; export class TokenManagementTransactionsOutcomeParser { diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.ts b/src/transactionsOutcomeParsers/transactionEventsParser.ts index 4d568e077..da4c0d316 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.ts @@ -1,5 +1,4 @@ -import { ResultsParser } from "../smartcontracts"; -import { EventDefinition } from "../smartcontracts/typesystem/event"; +import { EventDefinition, ResultsParser } from "../abi"; import { TransactionEvent } from "./resources"; interface IAbi { diff --git a/src/utils.codec.ts b/src/utils.codec.ts index 0e03b658b..4f70e93c8 100644 --- a/src/utils.codec.ts +++ b/src/utils.codec.ts @@ -1,7 +1,7 @@ import BigNumber from "bignumber.js"; +import * as contractsCodecUtils from "./abi/codec/utils"; import { Address } from "./address"; import { IAddress } from "./interface"; -import * as contractsCodecUtils from "./smartcontracts/codec/utils"; export function numberToPaddedHex(value: bigint | number | BigNumber.Value) { let hexableNumber: { toString(radix?: number): string }; From 681ae55e43913a6d004b38824ddfebe7e7f29a73 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 13 Nov 2024 16:05:23 +0200 Subject: [PATCH 002/214] Fix imports --- src/abi/interaction.local.net.spec.ts | 14 +++++++------- src/abi/interaction.spec.ts | 5 ++--- src/abi/interactionChecker.spec.ts | 2 +- src/abi/smartContract.local.net.spec.ts | 13 ++++++++++--- src/smartContractQueriesController.spec.ts | 6 +++--- src/testutils/contractController.ts | 4 +--- src/testutils/mockNetworkProvider.ts | 4 ++-- src/testutils/utils.ts | 4 +--- .../smartContractTransactionsFactory.spec.ts | 4 +--- .../transactionEventsParser.spec.ts | 10 +++++----- 10 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 05b8a8106..2f1c286af 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -1,20 +1,20 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; +import { promises } from "fs"; +import { QueryRunnerAdapter } from "../adapters/queryRunnerAdapter"; +import { SmartContractQueriesController } from "../smartContractQueriesController"; import { loadAbiRegistry, loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; import { ContractController } from "../testutils/contractController"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { SmartContractTransactionsFactory } from "../transactionsFactories/smartContractTransactionsFactory"; +import { TransactionWatcher } from "../transactionWatcher"; import { Interaction } from "./interaction"; +import { ResultsParser } from "./resultsParser"; import { ReturnCode } from "./returnCode"; import { SmartContract } from "./smartContract"; -import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; -import { SmartContractTransactionsFactory } from "../transactionsFactories/smartContractTransactionsFactory"; -import { promises } from "fs"; -import { ResultsParser } from "./resultsParser"; -import { TransactionWatcher } from "../transactionWatcher"; -import { SmartContractQueriesController } from "../smartContractQueriesController"; -import { QueryRunnerAdapter } from "../adapters/queryRunnerAdapter"; import { ManagedDecimalSignedValue, ManagedDecimalValue } from "./typesystem"; describe("test smart contract interactor", function () { diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index e88789a90..3e1f5b808 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -1,7 +1,7 @@ -import { ContractQueryResponse } from "../networkProviders"; import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Address } from "../address"; +import { ContractQueryResponse } from "../networkProviders"; import { loadAbiRegistry, loadTestWallets, @@ -16,8 +16,7 @@ import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; import { ReturnCode } from "./returnCode"; import { SmartContract } from "./smartContract"; -import { BigUIntValue, OptionalValue, OptionValue, TokenIdentifierValue, U32Value } from "./typesystem"; -import { BytesValue } from "./typesystem/bytes"; +import { BigUIntValue, BytesValue, OptionalValue, OptionValue, TokenIdentifierValue, U32Value } from "./typesystem"; describe("test smart contract interactor", function () { let dummyAddress = new Address("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"); diff --git a/src/abi/interactionChecker.spec.ts b/src/abi/interactionChecker.spec.ts index 84da7dab0..caabab429 100644 --- a/src/abi/interactionChecker.spec.ts +++ b/src/abi/interactionChecker.spec.ts @@ -9,13 +9,13 @@ import { SmartContract } from "./smartContract"; import { BigUIntType, BigUIntValue, + BytesValue, OptionalType, OptionalValue, OptionValue, TokenIdentifierValue, U32Value, } from "./typesystem"; -import { BytesValue } from "./typesystem/bytes"; describe("integration tests: test checker within interactor", function () { let dummyAddress = new Address("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"); diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 99219622b..57c5646f8 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -7,15 +7,22 @@ import { prepareDeployment } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { loadTestWallets, TestWallet } from "../testutils/wallets"; import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; import { SmartContractTransactionsFactory } from "../transactionsFactories/smartContractTransactionsFactory"; -import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { decodeUnsignedNumber } from "./codec"; import { ContractFunction } from "./function"; import { ResultsParser } from "./resultsParser"; import { SmartContract } from "./smartContract"; -import { AddressValue, BigUIntValue, OptionalValue, OptionValue, TokenIdentifierValue, U32Value } from "./typesystem"; -import { BytesValue } from "./typesystem/bytes"; +import { + AddressValue, + BigUIntValue, + BytesValue, + OptionalValue, + OptionValue, + TokenIdentifierValue, + U32Value, +} from "./typesystem"; describe("test on local testnet", function () { let alice: TestWallet, bob: TestWallet, carol: TestWallet; diff --git a/src/smartContractQueriesController.spec.ts b/src/smartContractQueriesController.spec.ts index 07bc570d8..63c7887a1 100644 --- a/src/smartContractQueriesController.spec.ts +++ b/src/smartContractQueriesController.spec.ts @@ -1,12 +1,12 @@ -import { ContractQueryResponse } from "./networkProviders"; import BigNumber from "bignumber.js"; import { assert } from "chai"; +import { AbiRegistry, BigUIntValue, BooleanValue, BytesValue, Tuple, U16Value, U64Value } from "./abi"; import { QueryRunnerAdapter } from "./adapters/queryRunnerAdapter"; +import { ContractQueryResponse } from "./networkProviders"; import { SmartContractQueriesController } from "./smartContractQueriesController"; import { SmartContractQueryResponse } from "./smartContractQuery"; -import { AbiRegistry, BigUIntValue, BooleanValue, BytesValue, Tuple, U16Value, U64Value } from "./smartcontracts"; -import { bigIntToBuffer } from "./smartcontracts/codec/utils"; import { MockNetworkProvider, loadAbiRegistry } from "./testutils"; +import { bigIntToBuffer } from "./tokenOperations/codec"; describe("test smart contract queries controller", () => { describe("createQuery", () => { diff --git a/src/testutils/contractController.ts b/src/testutils/contractController.ts index f72d30794..a053e4431 100644 --- a/src/testutils/contractController.ts +++ b/src/testutils/contractController.ts @@ -1,8 +1,6 @@ +import { Interaction, ResultsParser, TypedOutcomeBundle, UntypedOutcomeBundle } from "../abi"; import { ITransactionOnNetwork } from "../interfaceOfNetwork"; import { Logger } from "../logger"; -import { Interaction } from "../smartcontracts/interaction"; -import { TypedOutcomeBundle, UntypedOutcomeBundle } from "../smartcontracts/interface"; -import { ResultsParser } from "../smartcontracts/resultsParser"; import { Transaction } from "../transaction"; import { TransactionWatcher } from "../transactionWatcher"; import { INetworkProvider } from "./networkProviders"; diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 988d693f5..53276a27b 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -1,4 +1,4 @@ -import { ContractResultItem, ContractResults, TransactionOnNetwork, TransactionStatus } from "../networkProviders"; +import { Query } from "../abi/query"; import { Address } from "../address"; import { AsyncTimer } from "../asyncTimer"; import * as errors from "../errors"; @@ -11,7 +11,7 @@ import { ITransactionOnNetwork, ITransactionStatus, } from "../interfaceOfNetwork"; -import { Query } from "../smartcontracts/query"; +import { ContractResultItem, ContractResults, TransactionOnNetwork, TransactionStatus } from "../networkProviders"; import { Transaction, TransactionHash } from "../transaction"; import { createAccountBalance } from "./utils"; diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index 349e82f3b..0b19c55a7 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -1,10 +1,8 @@ import BigNumber from "bignumber.js"; import * as fs from "fs"; import { PathLike } from "fs"; +import { AbiRegistry, Code, SmartContract, TypedValue } from "../abi"; import { IChainID, IGasLimit } from "../interface"; -import { Code } from "../smartcontracts/code"; -import { SmartContract } from "../smartcontracts/smartContract"; -import { AbiRegistry, TypedValue } from "../smartcontracts/typesystem"; import { Transaction } from "../transaction"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; diff --git a/src/transactionsFactories/smartContractTransactionsFactory.spec.ts b/src/transactionsFactories/smartContractTransactionsFactory.spec.ts index 096c37ea7..62633f757 100644 --- a/src/transactionsFactories/smartContractTransactionsFactory.spec.ts +++ b/src/transactionsFactories/smartContractTransactionsFactory.spec.ts @@ -1,9 +1,7 @@ import { assert } from "chai"; +import { AbiRegistry, Code, U32Value } from "../abi"; import { Address } from "../address"; import { Err } from "../errors"; -import { U32Value } from "../smartcontracts"; -import { Code } from "../smartcontracts/code"; -import { AbiRegistry } from "../smartcontracts/typesystem/abiRegistry"; import { loadAbiRegistry, loadContractCode } from "../testutils/utils"; import { Token, TokenTransfer } from "../tokens"; import { SmartContractTransactionsFactory } from "./smartContractTransactionsFactory"; diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts index cddc8ea3d..6b1a3fa7d 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts @@ -1,3 +1,8 @@ +import BigNumber from "bignumber.js"; +import { assert } from "chai"; +import { AbiRegistry } from "../abi"; +import { Address } from "../address"; +import { TransactionsConverter } from "../converters/transactionsConverter"; import { ContractResultItem, ContractResults, @@ -7,11 +12,6 @@ import { TransactionLogsOnNetwork, TransactionOnNetwork, } from "../networkProviders"; -import BigNumber from "bignumber.js"; -import { assert } from "chai"; -import { Address } from "../address"; -import { TransactionsConverter } from "../converters/transactionsConverter"; -import { AbiRegistry } from "../smartcontracts"; import { loadAbiRegistry } from "../testutils"; import { TransactionEvent, findEventsByFirstTopic } from "./resources"; import { TransactionEventsParser } from "./transactionEventsParser"; From 3092ab26cac0e3fe8e3e6f5fa30d87439804b4b4 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 11:13:17 +0200 Subject: [PATCH 003/214] Add accounts folder --- src/accounts/account.ts | 113 +++++++++++++++++++++++++++++++++++++ src/accounts/index.ts | 2 + src/accounts/interfaces.ts | 7 +++ src/wallet/userVerifier.ts | 39 ++++++------- src/wallet/userWallet.ts | 28 +++++++++ 5 files changed, 168 insertions(+), 21 deletions(-) create mode 100644 src/accounts/account.ts create mode 100644 src/accounts/index.ts create mode 100644 src/accounts/interfaces.ts diff --git a/src/accounts/account.ts b/src/accounts/account.ts new file mode 100644 index 000000000..e164a34b2 --- /dev/null +++ b/src/accounts/account.ts @@ -0,0 +1,113 @@ +import { Address } from "../address"; +import { LibraryConfig } from "../config"; +import { IAccountBalance, INonce } from "../interface"; +import { Mnemonic, UserSigner, UserWallet } from "../wallet"; +import { IAccount } from "./interfaces"; + +/** + * An abstraction representing an account (user or Smart Contract) on the Network. + */ +export class Account implements IAccount { + /** + * The address of the account. + */ + readonly address: Address = Address.empty(); + + /** + * The nonce of the account (the account sequence number). + */ + nonce: INonce = 0; + + /** + * @deprecated This will be remove with the next release as not needed anymore. + */ + /** + * The balance of the account. + */ + balance: IAccountBalance = "0"; + + /** + * The signer of the account. + */ + private signer?: UserSigner; + + /** + * Creates an account object from an address + */ + constructor(address: Address, signer?: UserSigner) { + this.address = address; + this.signer = signer; + } + + /** + * @deprecated This will be remove with the next release as not needed anymore. + */ + /** + * Updates account properties (such as nonce, balance). + */ + update(obj: { nonce: INonce; balance: IAccountBalance }) { + this.nonce = obj.nonce; + this.balance = obj.balance; + } + + /** + * Increments (locally) the nonce (the account sequence number). + */ + incrementNonce() { + this.nonce = this.nonce.valueOf() + 1; + } + + /** + * Gets then increments (locally) the nonce (the account sequence number). + */ + getNonceThenIncrement(): INonce { + let nonce = this.nonce; + this.nonce = this.nonce.valueOf() + 1; + return nonce; + } + + /** + * Converts the account to a pretty, plain JavaScript object. + */ + toJSON(): any { + return { + address: this.address.bech32(), + nonce: this.nonce.valueOf(), + balance: this.balance.toString(), + }; + } + + sign(data: Uint8Array): Promise { + if (!this.signer) { + throw new Error("Signer not initialiezed, please provide the signer when account is instantiated"); + } + return this.signer.sign(data); + } + + static newFromPem(path: string, index: number = 0, hrp: string = LibraryConfig.DefaultAddressHrp): Account { + const userSigner = UserSigner.fromPem(path, index); + return new Account(userSigner.getAddress(hrp), userSigner); + } + + static newFromMnemonic( + mnemonic: string, + addressIndex: number = 0, + hrp: string = LibraryConfig.DefaultAddressHrp, + ): Account { + const mnemonicHandler = Mnemonic.fromString(mnemonic); + const secretKey = mnemonicHandler.deriveKey(addressIndex); + const userSigner = new UserSigner(secretKey); + return new Account(userSigner.getAddress(hrp), userSigner); + } + + static newFromKeystore( + filePath: string, + password: string, + addressIndex?: number, + hrp: string = LibraryConfig.DefaultAddressHrp, + ): Account { + const secretKey = UserWallet.loadSecretKey(filePath, password, addressIndex); + const userSigner = new UserSigner(secretKey); + return new Account(userSigner.getAddress(hrp), userSigner); + } +} diff --git a/src/accounts/index.ts b/src/accounts/index.ts new file mode 100644 index 000000000..5b58bd041 --- /dev/null +++ b/src/accounts/index.ts @@ -0,0 +1,2 @@ +export * from "./account"; +export * from "./interfaces"; diff --git a/src/accounts/interfaces.ts b/src/accounts/interfaces.ts new file mode 100644 index 000000000..482b99900 --- /dev/null +++ b/src/accounts/interfaces.ts @@ -0,0 +1,7 @@ +import { Address } from "../address"; + +export interface IAccount { + readonly address: Address; + + sign(data: Uint8Array): Promise; +} diff --git a/src/wallet/userVerifier.ts b/src/wallet/userVerifier.ts index ca56585a0..b143c760e 100644 --- a/src/wallet/userVerifier.ts +++ b/src/wallet/userVerifier.ts @@ -1,31 +1,28 @@ +import { Address } from "../address"; import { UserPublicKey } from "./userKeys"; -interface IAddress { - pubkey(): Buffer; -} - /** * ed25519 signature verification */ export class UserVerifier { - publicKey: UserPublicKey; + publicKey: UserPublicKey; - constructor(publicKey: UserPublicKey) { - this.publicKey = publicKey; - } + constructor(publicKey: UserPublicKey) { + this.publicKey = publicKey; + } - static fromAddress(address: IAddress): UserVerifier { - let publicKey = new UserPublicKey(address.pubkey()); - return new UserVerifier(publicKey); - } + static fromAddress(address: Address): UserVerifier { + let publicKey = new UserPublicKey(address.getPublicKey()); + return new UserVerifier(publicKey); + } - /** - * - * @param data the raw data to be verified (e.g. an already-serialized enveloped message) - * @param signature the signature to be verified - * @returns true if the signature is valid, false otherwise - */ - verify(data: Buffer | Uint8Array, signature: Buffer | Uint8Array): boolean { - return this.publicKey.verify(data, signature); - } + /** + * + * @param data the raw data to be verified (e.g. an already-serialized enveloped message) + * @param signature the signature to be verified + * @returns true if the signature is valid, false otherwise + */ + verify(data: Buffer | Uint8Array, signature: Buffer | Uint8Array): boolean { + return this.publicKey.verify(data, signature); + } } diff --git a/src/wallet/userWallet.ts b/src/wallet/userWallet.ts index 743f4ac69..3d505ff60 100644 --- a/src/wallet/userWallet.ts +++ b/src/wallet/userWallet.ts @@ -1,4 +1,7 @@ +import { readFileSync } from "fs"; +import path from "path"; import { Err } from "../errors"; +import { Logger } from "../logger"; import { CipherAlgorithm, Decryptor, EncryptedData, Encryptor, KeyDerivationFunction, Randomness } from "./crypto"; import { ScryptKeyDerivationParams } from "./crypto/derivationParams"; import { Mnemonic } from "./mnemonic"; @@ -77,6 +80,31 @@ export class UserWallet { }); } + static loadSecretKey(filePath: string, password: string, addressIndex?: number): UserSecretKey { + // Load and parse the keystore file + const keyFileJson = readFileSync(path.resolve(filePath), "utf8"); + const keyFileObject = JSON.parse(keyFileJson); + const kind = keyFileObject.kind || UserWalletKind.SecretKey.valueOf(); + + Logger.debug(`UserWallet.loadSecretKey(), kind = ${kind}`); + + let secretKey: UserSecretKey; + + if (kind === UserWalletKind.SecretKey.valueOf()) { + if (addressIndex !== undefined) { + throw new Error("address_index must not be provided when kind == 'secretKey'"); + } + secretKey = UserWallet.decryptSecretKey(keyFileObject, password); + } else if (kind === UserWalletKind.Mnemonic.valueOf()) { + const mnemonic = UserWallet.decryptMnemonic(keyFileObject, password); + secretKey = mnemonic.deriveKey(addressIndex || 0); + } else { + throw new Error(`Unknown kind: ${kind}`); + } + + return secretKey; + } + static decrypt(keyFileObject: any, password: string, addressIndex?: number): UserSecretKey { const kind = keyFileObject.kind || UserWalletKind.SecretKey; From be40e3ad79d0a03a4a130e9a5b612ad49f077a59 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 11:21:26 +0200 Subject: [PATCH 004/214] Add account management --- src/account.ts | 64 ------------------- src/accountManagement/accountController.ts | 62 ++++++++++++++++++ .../accountTransactionsFactory.spec.ts | 16 ++--- .../accountTransactionsFactory.ts | 36 +++++------ src/accountManagement/index.ts | 2 + src/accountManagement/resources.ts | 4 ++ src/index.ts | 3 +- src/transactionsFactories/index.ts | 2 +- 8 files changed, 91 insertions(+), 98 deletions(-) delete mode 100644 src/account.ts create mode 100644 src/accountManagement/accountController.ts rename src/{transactionsFactories => accountManagement}/accountTransactionsFactory.spec.ts (93%) rename src/{transactionsFactories => accountManagement}/accountTransactionsFactory.ts (76%) create mode 100644 src/accountManagement/index.ts create mode 100644 src/accountManagement/resources.ts diff --git a/src/account.ts b/src/account.ts deleted file mode 100644 index d371afdc6..000000000 --- a/src/account.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { Address } from "./address"; -import { IAccountBalance, IAddress, INonce } from "./interface"; - -/** - * An abstraction representing an account (user or Smart Contract) on the Network. - */ -export class Account { - /** - * The address of the account. - */ - readonly address: IAddress = Address.empty(); - - /** - * The nonce of the account (the account sequence number). - */ - nonce: INonce = 0; - - /** - * The balance of the account. - */ - balance: IAccountBalance = "0"; - - /** - * Creates an account object from an address - */ - constructor(address: IAddress) { - this.address = address; - } - - /** - * Updates account properties (such as nonce, balance). - */ - update(obj: { nonce: INonce; balance: IAccountBalance }) { - this.nonce = obj.nonce; - this.balance = obj.balance; - } - - /** - * Increments (locally) the nonce (the account sequence number). - */ - incrementNonce() { - this.nonce = this.nonce.valueOf() + 1; - } - - /** - * Gets then increments (locally) the nonce (the account sequence number). - */ - getNonceThenIncrement(): INonce { - let nonce = this.nonce; - this.nonce = this.nonce.valueOf() + 1; - return nonce; - } - - /** - * Converts the account to a pretty, plain JavaScript object. - */ - toJSON(): any { - return { - address: this.address.bech32(), - nonce: this.nonce.valueOf(), - balance: this.balance.toString(), - }; - } -} diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts new file mode 100644 index 000000000..91ca55150 --- /dev/null +++ b/src/accountManagement/accountController.ts @@ -0,0 +1,62 @@ +import { IAccount } from "../accounts/interfaces"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { AccountTransactionsFactory } from "./accountTransactionsFactory"; +import { SaveKeyValueInput, SetGuardianInput } from "./resources"; + +export class AccountController { + private factory: AccountTransactionsFactory; + private txComputer: TransactionComputer; + + constructor(options: { chainID: string }) { + this.factory = new AccountTransactionsFactory({ + config: new TransactionsFactoryConfig(options), + }); + this.txComputer = new TransactionComputer(); + } + + async createTransactionForSavingKeyValue( + sender: IAccount, + nonce: bigint, + options: SaveKeyValueInput, + ): Promise { + const transaction = this.factory.createTransactionForSavingKeyValue(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForSettingGuardian( + sender: IAccount, + nonce: bigint, + options: SetGuardianInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingGuardian(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForGuardingAccount(sender: IAccount, nonce: bigint): Promise { + const transaction = this.factory.createTransactionForGuardingAccount(sender.address); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForUnguardingAccount(sender: IAccount, nonce: bigint): Promise { + const transaction = this.factory.createTransactionForUnguardingAccount(sender.address); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } +} diff --git a/src/transactionsFactories/accountTransactionsFactory.spec.ts b/src/accountManagement/accountTransactionsFactory.spec.ts similarity index 93% rename from src/transactionsFactories/accountTransactionsFactory.spec.ts rename to src/accountManagement/accountTransactionsFactory.spec.ts index 6dc4ec8ee..78660dd6f 100644 --- a/src/transactionsFactories/accountTransactionsFactory.spec.ts +++ b/src/accountManagement/accountTransactionsFactory.spec.ts @@ -1,6 +1,6 @@ import { assert } from "chai"; import { Address } from "../address"; -import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; describe("test account transactions factory", function () { @@ -11,8 +11,7 @@ describe("test account transactions factory", function () { const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const keyValuePairs = new Map([[Buffer.from("key0"), Buffer.from("value0")]]); - const transaction = factory.createTransactionForSavingKeyValue({ - sender: sender, + const transaction = factory.createTransactionForSavingKeyValue(sender, { keyValuePairs: keyValuePairs, }); @@ -29,8 +28,7 @@ describe("test account transactions factory", function () { const guardian = Address.fromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); const serviceID = "MultiversXTCSService"; - const transaction = factory.createTransactionForSettingGuardian({ - sender: sender, + const transaction = factory.createTransactionForSettingGuardian(sender, { guardianAddress: guardian, serviceID: serviceID, }); @@ -49,9 +47,7 @@ describe("test account transactions factory", function () { it("should create 'Transaction' for guarding account", async function () { const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const transaction = factory.createTransactionForGuardingAccount({ - sender: sender, - }); + const transaction = factory.createTransactionForGuardingAccount(sender); assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); @@ -64,9 +60,7 @@ describe("test account transactions factory", function () { it("should create 'Transaction' for unguarding account", async function () { const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const transaction = factory.createTransactionForUnguardingAccount({ - sender: sender, - }); + const transaction = factory.createTransactionForUnguardingAccount(sender); assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); diff --git a/src/transactionsFactories/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts similarity index 76% rename from src/transactionsFactories/accountTransactionsFactory.ts rename to src/accountManagement/accountTransactionsFactory.ts index 01784bd21..dcb89169a 100644 --- a/src/transactionsFactories/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -1,9 +1,10 @@ import { Address } from "../address"; import { IAddress } from "../interface"; import { Transaction } from "../transaction"; -import { TransactionBuilder } from "./transactionBuilder"; +import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; +import { SaveKeyValueInput, SetGuardianInput } from "./resources"; -interface IConfig { +export interface IConfig { chainID: string; minGasLimit: bigint; gasLimitPerByte: bigint; @@ -22,10 +23,7 @@ export class AccountTransactionsFactory { this.config = options.config; } - createTransactionForSavingKeyValue(options: { - sender: IAddress; - keyValuePairs: Map; - }): Transaction { + createTransactionForSavingKeyValue(sender: IAddress, options: SaveKeyValueInput): Transaction { const functionName = "SaveKeyValue"; const keyValueParts = this.computeDataPartsForSavingKeyValue(options.keyValuePairs); const dataParts = [functionName, ...keyValueParts]; @@ -33,8 +31,8 @@ export class AccountTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: extraGas, addDataMovementGas: true, @@ -63,11 +61,7 @@ export class AccountTransactionsFactory { return dataParts; } - createTransactionForSettingGuardian(options: { - sender: IAddress; - guardianAddress: IAddress; - serviceID: string; - }): Transaction { + createTransactionForSettingGuardian(sender: IAddress, options: SetGuardianInput): Transaction { const dataParts = [ "SetGuardian", Address.fromBech32(options.guardianAddress.bech32()).toHex(), @@ -76,34 +70,34 @@ export class AccountTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitSetGuardian, addDataMovementGas: true, }).build(); } - createTransactionForGuardingAccount(options: { sender: IAddress }): Transaction { + createTransactionForGuardingAccount(sender: IAddress): Transaction { const dataParts = ["GuardAccount"]; return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitGuardAccount, addDataMovementGas: true, }).build(); } - createTransactionForUnguardingAccount(options: { sender: IAddress }): Transaction { + createTransactionForUnguardingAccount(sender: IAddress): Transaction { const dataParts = ["UnGuardAccount"]; return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitUnguardAccount, addDataMovementGas: true, diff --git a/src/accountManagement/index.ts b/src/accountManagement/index.ts new file mode 100644 index 000000000..87098af89 --- /dev/null +++ b/src/accountManagement/index.ts @@ -0,0 +1,2 @@ +export * from "./accountController"; +export * from "./accountTransactionsFactory"; diff --git a/src/accountManagement/resources.ts b/src/accountManagement/resources.ts new file mode 100644 index 000000000..aae540e73 --- /dev/null +++ b/src/accountManagement/resources.ts @@ -0,0 +1,4 @@ +import { IAddress } from "../interface"; + +export type SetGuardianInput = { guardianAddress: IAddress; serviceID: string }; +export type SaveKeyValueInput = { keyValuePairs: Map }; diff --git a/src/index.ts b/src/index.ts index 08a84ad38..83fb068d9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,8 @@ require("./globals"); export * from "./abi"; -export * from "./account"; +export * from "./accountManagement"; +export * from "./accounts"; export * from "./adapters"; export * from "./address"; export * from "./asyncTimer"; diff --git a/src/transactionsFactories/index.ts b/src/transactionsFactories/index.ts index fd9df3521..075c6b33a 100644 --- a/src/transactionsFactories/index.ts +++ b/src/transactionsFactories/index.ts @@ -1,7 +1,7 @@ +export * from "../accountManagement/accountTransactionsFactory"; export * from "./delegationTransactionsFactory"; export * from "./relayedTransactionsFactory"; export * from "./smartContractTransactionsFactory"; export * from "./tokenManagementTransactionsFactory"; export * from "./transactionsFactoryConfig"; export * from "./transferTransactionsFactory"; -export * from "./accountTransactionsFactory"; From 83ce45a8385b85d1f0b815b9bae83e56a9ff14f0 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 11:32:53 +0200 Subject: [PATCH 005/214] Fix tests --- src/abi/interaction.ts | 2 +- src/testutils/wallets.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index 2568dc7dc..e1bedc5f4 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -1,4 +1,4 @@ -import { Account } from "../account"; +import { Account } from "../accounts"; import { Address } from "../address"; import { Compatibility } from "../compatibility"; import { TRANSACTION_VERSION_DEFAULT } from "../constants"; diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index e332cec0c..c5e77ccb8 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -1,6 +1,6 @@ import * as fs from "fs"; import * as path from "path"; -import { Account } from "../account"; +import { Account } from "../accounts"; import { Address } from "../address"; import { IAddress } from "../interface"; import { IAccountOnNetwork } from "../interfaceOfNetwork"; From c618338b8c6449dc8b9a6000bf2bbcae7c93ba0f Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 11:48:40 +0200 Subject: [PATCH 006/214] Add test for load secret key --- src/wallet/users.spec.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index 976f4ef85..d29a1559f 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -1,4 +1,5 @@ import { assert } from "chai"; +import path from "path"; import { ErrBadMnemonicEntropy, ErrInvariantFailed } from "../errors"; import { TestMessage } from "./../testutils/message"; import { TestTransaction } from "./../testutils/transaction"; @@ -241,7 +242,7 @@ describe("test user wallets", async () => { assert.deepEqual(dummyWallet.toJSON(), expectedDummyWallet); }); - it("should loadSecretKey, but without 'kind' field", async function () { + it("should create user wallet from secret key, but without 'kind' field", async function () { const keyFileObject = await loadTestKeystore("withoutKind.json"); const secretKey = UserWallet.decrypt(keyFileObject, password); @@ -251,6 +252,17 @@ describe("test user wallets", async () => { ); }); + it("should loadSecretKey, but without 'kind' field", async function () { + const testdataPath = path.resolve(__dirname, "..", "testdata/testwallets"); + const keystorePath = path.resolve(testdataPath, "withoutKind.json"); + const secretKey = UserWallet.loadSecretKey(keystorePath, password); + + assert.equal( + secretKey.generatePublicKey().toAddress().bech32(), + "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", + ); + }); + it("should throw when calling loadSecretKey with unecessary address index", async function () { const keyFileObject = await loadTestKeystore("alice.json"); From bb25bf139263d36abed20aa1aa39fa2ceefee592 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 11:49:00 +0200 Subject: [PATCH 007/214] Remove uneded export --- src/accountManagement/accountTransactionsFactory.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/accountManagement/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts index dcb89169a..f9bbc5a16 100644 --- a/src/accountManagement/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -4,7 +4,7 @@ import { Transaction } from "../transaction"; import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; import { SaveKeyValueInput, SetGuardianInput } from "./resources"; -export interface IConfig { +interface IConfig { chainID: string; minGasLimit: bigint; gasLimitPerByte: bigint; From 224fc07f077af5a62484c6358e8562f29a2384eb Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 12:57:04 +0200 Subject: [PATCH 008/214] Fix run tests for users --- src/wallet/users.spec.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index d29a1559f..7b3ce1444 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -18,15 +18,17 @@ import { UserSigner } from "./userSigner"; import { UserVerifier } from "./userVerifier"; import { UserWallet } from "./userWallet"; -describe("test user wallets", async () => { +describe("test user wallets", () => { let alice: TestWallet, bob: TestWallet, carol: TestWallet; - let password: string = await loadPassword(); - const dummyMnemonic = await loadMnemonic(); + let password: string; + let dummyMnemonic: string; before(async function () { alice = await loadTestWallet("alice"); bob = await loadTestWallet("bob"); carol = await loadTestWallet("carol"); + password = await loadPassword(); + dummyMnemonic = await loadMnemonic(); }); it("should generate mnemonic", () => { @@ -139,7 +141,7 @@ describe("test user wallets", async () => { assert.equal(UserSecretKey.fromPem(carol.pemFileText).hex(), carol.secretKeyHex); }); - it("should create and load keystore files (with secret keys)", function () { + it.only("should create and load keystore files (with secret keys)", function () { this.timeout(10000); let aliceSecretKey = UserSecretKey.fromString(alice.secretKeyHex); @@ -157,7 +159,7 @@ describe("test user wallets", async () => { assert.equal(carolKeyFile.toJSON().bech32, carol.address.bech32()); console.time("decrypt"); - assert.deepEqual(UserWallet.decryptSecretKey(aliceKeyFile.toJSON(), password), aliceSecretKey); + // assert.deepEqual(UserWallet.decryptSecretKey(aliceKeyFile.toJSON(), password), aliceSecretKey); assert.deepEqual(UserWallet.decryptSecretKey(bobKeyFile.toJSON(), password), bobSecretKey); assert.deepEqual(UserWallet.decryptSecretKey(carolKeyFile.toJSON(), password), carolSecretKey); console.timeEnd("decrypt"); @@ -194,6 +196,7 @@ describe("test user wallets", async () => { }), }); + console.log(alice.keyFileObject, aliceKeyFile.toJSON()); assert.deepEqual(aliceKeyFile.toJSON(), alice.keyFileObject); assert.deepEqual(bobKeyFile.toJSON(), bob.keyFileObject); assert.deepEqual(carolKeyFile.toJSON(), carol.keyFileObject); From bf6f31958c8ec6491a564e5915ddb6e0f87ccc67 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 13:02:50 +0200 Subject: [PATCH 009/214] Fix tests --- src/testdata/testwallets/alice.json | 1 + src/testdata/testwallets/bob.json | 1 + src/testdata/testwallets/carol.json | 1 + src/wallet/users.spec.ts | 2 +- 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/testdata/testwallets/alice.json b/src/testdata/testwallets/alice.json index 9e83170cf..18c4ea1e9 100644 --- a/src/testdata/testwallets/alice.json +++ b/src/testdata/testwallets/alice.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "0dc10c02-b59b-4bac-9710-6b2cfa4284ba", "address": "0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1", "bech32": "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", diff --git a/src/testdata/testwallets/bob.json b/src/testdata/testwallets/bob.json index 439b394a5..9efb41109 100644 --- a/src/testdata/testwallets/bob.json +++ b/src/testdata/testwallets/bob.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "85fdc8a7-7119-479d-b7fb-ab4413ed038d", "address": "8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8", "bech32": "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", diff --git a/src/testdata/testwallets/carol.json b/src/testdata/testwallets/carol.json index 3614a5ba2..e02e8044e 100644 --- a/src/testdata/testwallets/carol.json +++ b/src/testdata/testwallets/carol.json @@ -1,6 +1,7 @@ { "version": 4, "id": "65894f35-d142-41d2-9335-6ad02e0ed0be", + "kind": "secretKey", "address": "b2a11555ce521e4944e09ab17549d85b487dcd26c84b5017a39e31a3670889ba", "bech32": "erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8", "crypto": { diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index 7b3ce1444..ff5cb6322 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -141,7 +141,7 @@ describe("test user wallets", () => { assert.equal(UserSecretKey.fromPem(carol.pemFileText).hex(), carol.secretKeyHex); }); - it.only("should create and load keystore files (with secret keys)", function () { + it("should create and load keystore files (with secret keys)", function () { this.timeout(10000); let aliceSecretKey = UserSecretKey.fromString(alice.secretKeyHex); From e5e695d03b9f15c1ccf40385a47462936af85a9d Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 13:18:45 +0200 Subject: [PATCH 010/214] Fix tests, add default kind secret key --- src/testdata/testwallets/alice.json | 1 - src/testdata/testwallets/bob.json | 1 - src/testdata/testwallets/carol.json | 1 - src/testutils/wallets.ts | 1 + src/wallet/users.spec.ts | 59 ++++++++++++++--------------- 5 files changed, 30 insertions(+), 33 deletions(-) diff --git a/src/testdata/testwallets/alice.json b/src/testdata/testwallets/alice.json index 18c4ea1e9..9e83170cf 100644 --- a/src/testdata/testwallets/alice.json +++ b/src/testdata/testwallets/alice.json @@ -1,6 +1,5 @@ { "version": 4, - "kind": "secretKey", "id": "0dc10c02-b59b-4bac-9710-6b2cfa4284ba", "address": "0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1", "bech32": "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", diff --git a/src/testdata/testwallets/bob.json b/src/testdata/testwallets/bob.json index 9efb41109..439b394a5 100644 --- a/src/testdata/testwallets/bob.json +++ b/src/testdata/testwallets/bob.json @@ -1,6 +1,5 @@ { "version": 4, - "kind": "secretKey", "id": "85fdc8a7-7119-479d-b7fb-ab4413ed038d", "address": "8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8", "bech32": "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", diff --git a/src/testdata/testwallets/carol.json b/src/testdata/testwallets/carol.json index e02e8044e..3614a5ba2 100644 --- a/src/testdata/testwallets/carol.json +++ b/src/testdata/testwallets/carol.json @@ -1,7 +1,6 @@ { "version": 4, "id": "65894f35-d142-41d2-9335-6ad02e0ed0be", - "kind": "secretKey", "address": "b2a11555ce521e4944e09ab17549d85b487dcd26c84b5017a39e31a3670889ba", "bech32": "erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8", "crypto": { diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index c5e77ccb8..191ee3de0 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -65,6 +65,7 @@ export async function loadPassword(): Promise { export async function loadTestWallet(name: string): Promise { const jsonContents = JSON.parse(await readTestWalletFileContents(name + ".json")); + jsonContents.kind = jsonContents.kind ?? "secretKey"; const pemContents = await readTestWalletFileContents(name + ".pem"); const secretKey = UserSecretKey.fromPem(pemContents); const publicKey = secretKey.generatePublicKey().valueOf(); diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index ff5cb6322..35f0b7632 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -77,28 +77,28 @@ describe("test user wallets", () => { const mnemonic = Mnemonic.fromString(DummyMnemonicOf12Words); assert.equal( - mnemonic.deriveKey(0).generatePublicKey().toAddress().bech32(), + mnemonic.deriveKey(0).generatePublicKey().toAddress().toBech32(), "erd1l8g9dk3gz035gkjhwegsjkqzdu3augrwhcfxrnucnyyrpc2220pqg4g7na", ); assert.equal( - mnemonic.deriveKey(1).generatePublicKey().toAddress().bech32(), + mnemonic.deriveKey(1).generatePublicKey().toAddress().toBech32(), "erd1fmhwg84rldg0xzngf53m0y607wvefvamh07n2mkypedx27lcqnts4zs09p", ); assert.equal( - mnemonic.deriveKey(2).generatePublicKey().toAddress().bech32(), + mnemonic.deriveKey(2).generatePublicKey().toAddress().toBech32(), "erd1tyuyemt4xz2yjvc7rxxp8kyfmk2n3h8gv3aavzd9ru4v2vhrkcksptewtj", ); assert.equal( - mnemonic.deriveKey(0).generatePublicKey().toAddress("test").bech32(), + mnemonic.deriveKey(0).generatePublicKey().toAddress("test").toBech32(), "test1l8g9dk3gz035gkjhwegsjkqzdu3augrwhcfxrnucnyyrpc2220pqc6tnnf", ); assert.equal( - mnemonic.deriveKey(1).generatePublicKey().toAddress("xerd").bech32(), + mnemonic.deriveKey(1).generatePublicKey().toAddress("xerd").toBech32(), "xerd1fmhwg84rldg0xzngf53m0y607wvefvamh07n2mkypedx27lcqntsj4adj4", ); assert.equal( - mnemonic.deriveKey(2).generatePublicKey().toAddress("yerd").bech32(), + mnemonic.deriveKey(2).generatePublicKey().toAddress("yerd").toBech32(), "yerd1tyuyemt4xz2yjvc7rxxp8kyfmk2n3h8gv3aavzd9ru4v2vhrkcksn8p0n5", ); }); @@ -154,12 +154,12 @@ describe("test user wallets", () => { let carolKeyFile = UserWallet.fromSecretKey({ secretKey: carolSecretKey, password: password }); console.timeEnd("encrypt"); - assert.equal(aliceKeyFile.toJSON().bech32, alice.address.bech32()); - assert.equal(bobKeyFile.toJSON().bech32, bob.address.bech32()); - assert.equal(carolKeyFile.toJSON().bech32, carol.address.bech32()); + assert.equal(aliceKeyFile.toJSON().bech32, alice.address.toBech32()); + assert.equal(bobKeyFile.toJSON().bech32, bob.address.toBech32()); + assert.equal(carolKeyFile.toJSON().bech32, carol.address.toBech32()); console.time("decrypt"); - // assert.deepEqual(UserWallet.decryptSecretKey(aliceKeyFile.toJSON(), password), aliceSecretKey); + assert.deepEqual(UserWallet.decryptSecretKey(aliceKeyFile.toJSON(), password), aliceSecretKey); assert.deepEqual(UserWallet.decryptSecretKey(bobKeyFile.toJSON(), password), bobSecretKey); assert.deepEqual(UserWallet.decryptSecretKey(carolKeyFile.toJSON(), password), carolSecretKey); console.timeEnd("decrypt"); @@ -196,7 +196,6 @@ describe("test user wallets", () => { }), }); - console.log(alice.keyFileObject, aliceKeyFile.toJSON()); assert.deepEqual(aliceKeyFile.toJSON(), alice.keyFileObject); assert.deepEqual(bobKeyFile.toJSON(), bob.keyFileObject); assert.deepEqual(carolKeyFile.toJSON(), carol.keyFileObject); @@ -207,7 +206,7 @@ describe("test user wallets", () => { const secretKey = UserWallet.decryptSecretKey(keyFileObject, password); assert.equal( - secretKey.generatePublicKey().toAddress().bech32(), + secretKey.generatePublicKey().toAddress().toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", ); }); @@ -220,15 +219,15 @@ describe("test user wallets", () => { assert.equal(json.version, 4); assert.equal(json.kind, "mnemonic"); - assert.isUndefined(json.bech32); + assert.isUndefined(json.toBech32); const mnemonic = UserWallet.decryptMnemonic(json, password); const mnemonicText = mnemonic.toString(); assert.equal(mnemonicText, dummyMnemonic); - assert.equal(mnemonic.deriveKey(0).generatePublicKey().toAddress().bech32(), alice.address.bech32()); - assert.equal(mnemonic.deriveKey(1).generatePublicKey().toAddress().bech32(), bob.address.bech32()); - assert.equal(mnemonic.deriveKey(2).generatePublicKey().toAddress().bech32(), carol.address.bech32()); + assert.equal(mnemonic.deriveKey(0).generatePublicKey().toAddress().toBech32(), alice.address.toBech32()); + assert.equal(mnemonic.deriveKey(1).generatePublicKey().toAddress().toBech32(), bob.address.toBech32()); + assert.equal(mnemonic.deriveKey(2).generatePublicKey().toAddress().toBech32(), carol.address.toBech32()); // With provided randomness, in order to reproduce our test wallets const expectedDummyWallet = await loadTestKeystore("withDummyMnemonic.json"); @@ -250,7 +249,7 @@ describe("test user wallets", () => { const secretKey = UserWallet.decrypt(keyFileObject, password); assert.equal( - secretKey.generatePublicKey().toAddress().bech32(), + secretKey.generatePublicKey().toAddress().toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", ); }); @@ -261,7 +260,7 @@ describe("test user wallets", () => { const secretKey = UserWallet.loadSecretKey(keystorePath, password); assert.equal( - secretKey.generatePublicKey().toAddress().bech32(), + secretKey.generatePublicKey().toAddress().toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", ); }); @@ -279,15 +278,15 @@ describe("test user wallets", () => { const keyFileObject = await loadTestKeystore("withDummyMnemonic.json"); assert.equal( - UserWallet.decrypt(keyFileObject, password, 0).generatePublicKey().toAddress().bech32(), + UserWallet.decrypt(keyFileObject, password, 0).generatePublicKey().toAddress().toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", ); assert.equal( - UserWallet.decrypt(keyFileObject, password, 1).generatePublicKey().toAddress().bech32(), + UserWallet.decrypt(keyFileObject, password, 1).generatePublicKey().toAddress().toBech32(), "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", ); assert.equal( - UserWallet.decrypt(keyFileObject, password, 2).generatePublicKey().toAddress().bech32(), + UserWallet.decrypt(keyFileObject, password, 2).generatePublicKey().toAddress().toBech32(), "erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8", ); }); @@ -483,40 +482,40 @@ describe("test user wallets", () => { const keyFileObjectWithSecretKey = await loadTestKeystore("withDummySecretKey.json"); assert.equal( - UserSigner.fromWallet(keyFileObjectWithoutKind, password).getAddress().bech32(), + UserSigner.fromWallet(keyFileObjectWithoutKind, password).getAddress().toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", ); assert.equal( - UserSigner.fromWallet(keyFileObjectWithMnemonic, password).getAddress().bech32(), + UserSigner.fromWallet(keyFileObjectWithMnemonic, password).getAddress().toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", ); assert.equal( - UserSigner.fromWallet(keyFileObjectWithSecretKey, password).getAddress().bech32(), + UserSigner.fromWallet(keyFileObjectWithSecretKey, password).getAddress().toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", ); assert.equal( - UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 0).getAddress().bech32(), + UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 0).getAddress().toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", ); assert.equal( - UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 1).getAddress().bech32(), + UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 1).getAddress().toBech32(), "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", ); assert.equal( - UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 2).getAddress().bech32(), + UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 2).getAddress().toBech32(), "erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8", ); assert.equal( - UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 0).getAddress("test").bech32(), + UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 0).getAddress("test").toBech32(), "test1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ss5hqhtr", ); assert.equal( - UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 1).getAddress("xerd").bech32(), + UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 1).getAddress("xerd").toBech32(), "xerd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruq9thc9j", ); assert.equal( - UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 2).getAddress("yerd").bech32(), + UserSigner.fromWallet(keyFileObjectWithMnemonic, password, 2).getAddress("yerd").toBech32(), "yerd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaqgh23pp", ); }); From ecc03b666959e792bdd36fab5ddbfb8d2ecdd9e6 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 13:21:34 +0200 Subject: [PATCH 011/214] Fix imports --- src/testutils/networkProviders.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 67ed2a4d1..18c8f1b25 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,3 +1,4 @@ +import { Query } from "../abi"; import { IAddress } from "../interface"; import { IAccountOnNetwork, @@ -7,7 +8,7 @@ import { ITransactionStatus, } from "../interfaceOfNetwork"; import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; -import { Query } from "../smartcontracts/query"; + import { Transaction } from "../transaction"; export function createLocalnetProvider(): INetworkProvider { From 50345376cecfa9359a5f730a28a7fb87f2b39628 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 13:42:50 +0200 Subject: [PATCH 012/214] Fix test --- src/testdata/testwallets/alice.json | 1 + src/testdata/testwallets/bob.json | 1 + src/testdata/testwallets/carol.json | 1 + src/testdata/testwallets/dan.json | 1 + src/testdata/testwallets/eve.json | 1 + src/testdata/testwallets/frank.json | 1 + src/testdata/testwallets/grace.json | 1 + src/testdata/testwallets/heidi.json | 1 + src/testdata/testwallets/ivan.json | 1 + src/testdata/testwallets/judy.json | 1 + src/testdata/testwallets/mallory.json | 1 + src/testdata/testwallets/mike.json | 1 + src/testutils/wallets.ts | 1 - 13 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/testdata/testwallets/alice.json b/src/testdata/testwallets/alice.json index 9e83170cf..18c4ea1e9 100644 --- a/src/testdata/testwallets/alice.json +++ b/src/testdata/testwallets/alice.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "0dc10c02-b59b-4bac-9710-6b2cfa4284ba", "address": "0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1", "bech32": "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", diff --git a/src/testdata/testwallets/bob.json b/src/testdata/testwallets/bob.json index 439b394a5..9efb41109 100644 --- a/src/testdata/testwallets/bob.json +++ b/src/testdata/testwallets/bob.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "85fdc8a7-7119-479d-b7fb-ab4413ed038d", "address": "8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8", "bech32": "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", diff --git a/src/testdata/testwallets/carol.json b/src/testdata/testwallets/carol.json index 3614a5ba2..1014a8230 100644 --- a/src/testdata/testwallets/carol.json +++ b/src/testdata/testwallets/carol.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "65894f35-d142-41d2-9335-6ad02e0ed0be", "address": "b2a11555ce521e4944e09ab17549d85b487dcd26c84b5017a39e31a3670889ba", "bech32": "erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8", diff --git a/src/testdata/testwallets/dan.json b/src/testdata/testwallets/dan.json index 15eb9f793..9b6cf26b6 100644 --- a/src/testdata/testwallets/dan.json +++ b/src/testdata/testwallets/dan.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "fc8b9b89-2227-41ec-afd1-5e6853feb7b2", "address": "b13a017423c366caff8cecfb77a12610a130f4888134122c7937feae0d6d7d17", "bech32": "erd1kyaqzaprcdnv4luvanah0gfxzzsnpaygsy6pytrexll2urtd05ts9vegu7", diff --git a/src/testdata/testwallets/eve.json b/src/testdata/testwallets/eve.json index b95f2582a..507778be8 100644 --- a/src/testdata/testwallets/eve.json +++ b/src/testdata/testwallets/eve.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "e770c455-a23b-4dcd-a7a5-0e22375dc233", "address": "3af8d9c9423b2577c6252722c1d90212a4111f7203f9744f76fcfa1d0a310033", "bech32": "erd18tudnj2z8vjh0339yu3vrkgzz2jpz8mjq0uhgnmklnap6z33qqeszq2yn4", diff --git a/src/testdata/testwallets/frank.json b/src/testdata/testwallets/frank.json index afb4a0f6b..74f69eadd 100644 --- a/src/testdata/testwallets/frank.json +++ b/src/testdata/testwallets/frank.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "df70f3ef-bb40-4afd-8751-77b26b29356d", "address": "b37f5d130beb8885b90ab574a8bfcdd894ca531a7d3d1f3431158d77d6185fbb", "bech32": "erd1kdl46yctawygtwg2k462307dmz2v55c605737dp3zkxh04sct7asqylhyv", diff --git a/src/testdata/testwallets/grace.json b/src/testdata/testwallets/grace.json index 81d640dcf..a438757b7 100644 --- a/src/testdata/testwallets/grace.json +++ b/src/testdata/testwallets/grace.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "9aff338f-f504-403c-86cd-5e623bc81c42", "address": "1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13", "bech32": "erd1r69gk66fmedhhcg24g2c5kn2f2a5k4kvpr6jfw67dn2lyydd8cfswy6ede", diff --git a/src/testdata/testwallets/heidi.json b/src/testdata/testwallets/heidi.json index 7608b981f..d9799fdd1 100644 --- a/src/testdata/testwallets/heidi.json +++ b/src/testdata/testwallets/heidi.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "1b55836f-946f-4dc3-946d-3c27e5096873", "address": "6e224118d9068ae626878a1cfbebcb6a95a4715db86d1b51e06a04226cf30fd6", "bech32": "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha", diff --git a/src/testdata/testwallets/ivan.json b/src/testdata/testwallets/ivan.json index ba0f7f34b..5d2b1eec4 100644 --- a/src/testdata/testwallets/ivan.json +++ b/src/testdata/testwallets/ivan.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "0b80d732-d4e6-4145-b5bb-698bdd323b3c", "address": "899451b361a83e89d73b4096d3c90c209b27874c9c7cb01bb08b0bb4dc15693d", "bech32": "erd13x29rvmp4qlgn4emgztd8jgvyzdj0p6vn37tqxas3v9mfhq4dy7shalqrx", diff --git a/src/testdata/testwallets/judy.json b/src/testdata/testwallets/judy.json index 286c9ffd7..6d64175bb 100644 --- a/src/testdata/testwallets/judy.json +++ b/src/testdata/testwallets/judy.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "a3108434-5d2c-4dca-9f94-29e822697e20", "address": "4a101a0f8f95f1218683900801cd971c6028b1597a771b2ed367d1ede09d9d2a", "bech32": "erd1fggp5ru0jhcjrp5rjqyqrnvhr3sz3v2e0fm3ktknvlg7mcyan54qzccnan", diff --git a/src/testdata/testwallets/mallory.json b/src/testdata/testwallets/mallory.json index 1416c2f14..bf9c1490e 100644 --- a/src/testdata/testwallets/mallory.json +++ b/src/testdata/testwallets/mallory.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "6756aa76-5934-4dc6-90c7-c261db98fe44", "address": "1454931ffa758ab35654a5206b28e9dbf1fb8df8f9ced093bb2887eb39f7e7af", "bech32": "erd1z32fx8l6wk9tx4j555sxk28fm0clhr0cl88dpyam9zr7kw0hu7hsx2j524", diff --git a/src/testdata/testwallets/mike.json b/src/testdata/testwallets/mike.json index d46a9e7bf..6a1bbc3a3 100644 --- a/src/testdata/testwallets/mike.json +++ b/src/testdata/testwallets/mike.json @@ -1,5 +1,6 @@ { "version": 4, + "kind": "secretKey", "id": "3f6adbc3-1215-4c31-9a61-a049b430e6f7", "address": "e32afedc904fe1939746ad973beb383563cf63642ba669b3040f9b9428a5ed60", "bech32": "erd1uv40ahysflse896x4ktnh6ecx43u7cmy9wnxnvcyp7deg299a4sq6vaywa", diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index 191ee3de0..c5e77ccb8 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -65,7 +65,6 @@ export async function loadPassword(): Promise { export async function loadTestWallet(name: string): Promise { const jsonContents = JSON.parse(await readTestWalletFileContents(name + ".json")); - jsonContents.kind = jsonContents.kind ?? "secretKey"; const pemContents = await readTestWalletFileContents(name + ".pem"); const secretKey = UserSecretKey.fromPem(pemContents); const publicKey = secretKey.generatePublicKey().valueOf(); From b7e3f3d47909ff9b828ff6f2105972237158c7f2 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 14:11:34 +0200 Subject: [PATCH 013/214] Add delegation controller --- src/delegation/delegationController.ts | 288 ++++++++++++++++++ .../delegationTransactionsFactory.spec.ts | 53 ++-- .../delegationTransactionsFactory.ts | 158 +++++----- ...elegationTransactionsOutcomeParser.spec.ts | 7 +- .../delegationTransactionsOutcomeParser.ts | 2 +- src/delegation/index.ts | 3 + src/delegation/resources.ts | 17 ++ src/index.ts | 1 + src/transactionsFactories/index.ts | 1 - src/transactionsOutcomeParsers/index.ts | 1 - 10 files changed, 408 insertions(+), 123 deletions(-) create mode 100644 src/delegation/delegationController.ts rename src/{transactionsFactories => delegation}/delegationTransactionsFactory.spec.ts (93%) rename src/{transactionsFactories => delegation}/delegationTransactionsFactory.ts (75%) rename src/{transactionsOutcomeParsers => delegation}/delegationTransactionsOutcomeParser.spec.ts (94%) rename src/{transactionsOutcomeParsers => delegation}/delegationTransactionsOutcomeParser.ts (97%) create mode 100644 src/delegation/index.ts create mode 100644 src/delegation/resources.ts diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts new file mode 100644 index 000000000..413968e5f --- /dev/null +++ b/src/delegation/delegationController.ts @@ -0,0 +1,288 @@ +import { IAccount } from "../accounts/interfaces"; +import { ITransactionOnNetwork } from "../interfaceOfNetwork"; +import { INetworkProvider } from "../networkProviders/interface"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionWatcher } from "../transactionWatcher"; +import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; +import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; +import * as inputs from "./resources"; + +export class DelegationController { + private transactionAwaiter: TransactionWatcher; + private factory: DelegationTransactionsFactory; + private parser: DelegationTransactionsOutcomeParser; + private txComputer: TransactionComputer; + + constructor(options: { chainID: string; networkProvider: INetworkProvider }) { + this.transactionAwaiter = new TransactionWatcher(options.networkProvider); + this.factory = new DelegationTransactionsFactory({ + config: new TransactionsFactoryConfig({ chainID: options.chainID }), + }); + this.parser = new DelegationTransactionsOutcomeParser(); + this.txComputer = new TransactionComputer(); + } + + async createTransactionForNewDelegationContract( + sender: IAccount, + nonce: bigint, + options: inputs.NewDelegationContractInput, + ): Promise { + const transaction = this.factory.createTransactionForNewDelegationContract(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedCreateNewDelegationContract(txHash: string): Promise<{ contractAddress: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseCreateNewDelegationContract(transaction); + } + + parseCreateNewDelegationContract(transactionOnNetwork: ITransactionOnNetwork): { contractAddress: string }[] { + return this.parser.parseCreateNewDelegationContract(transactionOnNetwork); + } + + async createTransactionForAddingNodes( + sender: IAccount, + nonce: bigint, + options: inputs.AddNodesInput, + ): Promise { + const transaction = this.factory.createTransactionForAddingNodes(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForRemovingNodes( + sender: IAccount, + nonce: bigint, + options: inputs.ManageNodesInput, + ): Promise { + const transaction = this.factory.createTransactionForRemovingNodes(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForStakingNodes( + sender: IAccount, + nonce: bigint, + options: inputs.ManageNodesInput, + ): Promise { + const transaction = this.factory.createTransactionForStakingNodes(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForUnbondingNodes( + sender: IAccount, + nonce: bigint, + options: inputs.ManageNodesInput, + ): Promise { + const transaction = this.factory.createTransactionForUnbondingNodes(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForUnstakingNodes( + sender: IAccount, + nonce: bigint, + options: inputs.ManageNodesInput, + ): Promise { + const transaction = this.factory.createTransactionForUnstakingNodes(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForUnjailingNodes( + sender: IAccount, + nonce: bigint, + options: inputs.UnjailingNodesInput, + ): Promise { + const transaction = this.factory.createTransactionForUnjailingNodes(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForChangingServiceFee( + sender: IAccount, + nonce: bigint, + options: inputs.ChangeServiceFee, + ): Promise { + const transaction = this.factory.createTransactionForChangingServiceFee(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForModifyingDelegationCap( + sender: IAccount, + nonce: bigint, + options: inputs.ModifyDelegationCapInput, + ): Promise { + const transaction = this.factory.createTransactionForModifyingDelegationCap(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForSettingAutomaticActivation( + sender: IAccount, + nonce: bigint, + options: inputs.ManageDelegationContractInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingAutomaticActivation(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForUnsettingAutomaticActivation( + sender: IAccount, + nonce: bigint, + options: inputs.ManageDelegationContractInput, + ): Promise { + const transaction = this.factory.createTransactionForUnsettingAutomaticActivation(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForSettingCapCheckOnRedelegateRewards( + sender: IAccount, + nonce: bigint, + options: inputs.ManageDelegationContractInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingCapCheckOnRedelegateRewards( + sender.address, + options, + ); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForUnsettingCapCheckOnRedelegateRewards( + sender: IAccount, + nonce: bigint, + options: inputs.ManageDelegationContractInput, + ): Promise { + const transaction = this.factory.createTransactionForUnsettingCapCheckOnRedelegateRewards( + sender.address, + options, + ); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForSettingMetadata( + sender: IAccount, + nonce: bigint, + options: inputs.SetContractMetadataInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingMetadata(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForDelegating( + sender: IAccount, + nonce: bigint, + options: inputs.DelegateActionsInput, + ): Promise { + const transaction = this.factory.createTransactionForDelegating(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForClaimingRewards( + sender: IAccount, + nonce: bigint, + options: inputs.ManageDelegationContractInput, + ): Promise { + const transaction = this.factory.createTransactionForClaimingRewards(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForRedelegatingRewards( + sender: IAccount, + nonce: bigint, + options: inputs.ManageDelegationContractInput, + ): Promise { + const transaction = this.factory.createTransactionForRedelegatingRewards(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForUndelegating( + sender: IAccount, + nonce: bigint, + options: inputs.DelegateActionsInput, + ): Promise { + const transaction = this.factory.createTransactionForUndelegating(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForWithdrawing( + sender: IAccount, + nonce: bigint, + options: inputs.ManageDelegationContractInput, + ): Promise { + const transaction = this.factory.createTransactionForWithdrawing(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } +} diff --git a/src/transactionsFactories/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts similarity index 93% rename from src/transactionsFactories/delegationTransactionsFactory.spec.ts rename to src/delegation/delegationTransactionsFactory.spec.ts index c7d72902f..46c788db2 100644 --- a/src/transactionsFactories/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -1,9 +1,9 @@ -import { ValidatorPublicKey } from "./../wallet"; import { assert } from "chai"; import { Address } from "../address"; -import { DELEGATION_MANAGER_SC_ADDRESS } from "../constants"; +import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../constants"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { ValidatorPublicKey } from "../wallet"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; -import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; describe("test delegation transactions factory", function () { const config = new TransactionsFactoryConfig({ chainID: "D" }); @@ -15,15 +15,17 @@ describe("test delegation transactions factory", function () { const serviceFee = 10n; const value = 1250000000000000000000n; - const transaction = delegationFactory.createTransactionForNewDelegationContract({ - sender: sender, + const transaction = delegationFactory.createTransactionForNewDelegationContract(sender, { totalDelegationCap: delagationCap, serviceFee: serviceFee, amount: value, }); assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, DELEGATION_MANAGER_SC_ADDRESS); + assert.equal( + transaction.receiver, + Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, this.config.addressHrp).bech32(), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("createNewDelegationContract@010f0cf064dd59200000@0a")); assert.equal(transaction.gasLimit, 60126500n); @@ -49,8 +51,7 @@ describe("test delegation transactions factory", function () { ), }; - const transaction = delegationFactory.createTransactionForAddingNodes({ - sender: sender, + const transaction = delegationFactory.createTransactionForAddingNodes(sender, { delegationContract: delegationContract, publicKeys: [publicKey], signedMessages: [mockMessage.getSignature()], @@ -78,8 +79,7 @@ describe("test delegation transactions factory", function () { }, }; - const transaction = delegationFactory.createTransactionForRemovingNodes({ - sender: sender, + const transaction = delegationFactory.createTransactionForRemovingNodes(sender, { delegationContract: delegationContract, publicKeys: [publicKey], }); @@ -101,8 +101,7 @@ describe("test delegation transactions factory", function () { }, }; - const transaction = delegationFactory.createTransactionForStakingNodes({ - sender: sender, + const transaction = delegationFactory.createTransactionForStakingNodes(sender, { delegationContract: delegationContract, publicKeys: [publicKey], }); @@ -124,8 +123,7 @@ describe("test delegation transactions factory", function () { }, }; - const transaction = delegationFactory.createTransactionForUnbondingNodes({ - sender: sender, + const transaction = delegationFactory.createTransactionForUnbondingNodes(sender, { delegationContract: delegationContract, publicKeys: [publicKey], }); @@ -148,8 +146,7 @@ describe("test delegation transactions factory", function () { }, }; - const transaction = delegationFactory.createTransactionForUnstakingNodes({ - sender: sender, + const transaction = delegationFactory.createTransactionForUnstakingNodes(sender, { delegationContract: delegationContract, publicKeys: [publicKey], }); @@ -172,8 +169,7 @@ describe("test delegation transactions factory", function () { }, }; - const transaction = delegationFactory.createTransactionForUnjailingNodes({ - sender: sender, + const transaction = delegationFactory.createTransactionForUnjailingNodes(sender, { delegationContract: delegationContract, publicKeys: [publicKey], amount: 25000000000000000000n, @@ -191,8 +187,7 @@ describe("test delegation transactions factory", function () { const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); const serviceFee = 10n; - const transaction = delegationFactory.createTransactionForChangingServiceFee({ - sender: sender, + const transaction = delegationFactory.createTransactionForChangingServiceFee(sender, { delegationContract: delegationContract, serviceFee: serviceFee, }); @@ -209,8 +204,7 @@ describe("test delegation transactions factory", function () { const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); const delegationCap = 5000000000000000000000n; - const transaction = delegationFactory.createTransactionForModifyingDelegationCap({ - sender: sender, + const transaction = delegationFactory.createTransactionForModifyingDelegationCap(sender, { delegationContract: delegationContract, delegationCap: delegationCap, }); @@ -226,8 +220,7 @@ describe("test delegation transactions factory", function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - const transaction = delegationFactory.createTransactionForSettingAutomaticActivation({ - sender: sender, + const transaction = delegationFactory.createTransactionForSettingAutomaticActivation(sender, { delegationContract: delegationContract, }); @@ -242,8 +235,7 @@ describe("test delegation transactions factory", function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - const transaction = delegationFactory.createTransactionForUnsettingAutomaticActivation({ - sender: sender, + const transaction = delegationFactory.createTransactionForUnsettingAutomaticActivation(sender, { delegationContract: delegationContract, }); @@ -258,8 +250,7 @@ describe("test delegation transactions factory", function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - const transaction = delegationFactory.createTransactionForSettingCapCheckOnRedelegateRewards({ - sender: sender, + const transaction = delegationFactory.createTransactionForSettingCapCheckOnRedelegateRewards(sender, { delegationContract: delegationContract, }); @@ -274,8 +265,7 @@ describe("test delegation transactions factory", function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - const transaction = delegationFactory.createTransactionForUnsettingCapCheckOnRedelegateRewards({ - sender: sender, + const transaction = delegationFactory.createTransactionForUnsettingCapCheckOnRedelegateRewards(sender, { delegationContract: delegationContract, }); @@ -290,8 +280,7 @@ describe("test delegation transactions factory", function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - const transaction = delegationFactory.createTransactionForSettingMetadata({ - sender: sender, + const transaction = delegationFactory.createTransactionForSettingMetadata(sender, { delegationContract: delegationContract, name: "name", website: "website", diff --git a/src/transactionsFactories/delegationTransactionsFactory.ts b/src/delegation/delegationTransactionsFactory.ts similarity index 75% rename from src/transactionsFactories/delegationTransactionsFactory.ts rename to src/delegation/delegationTransactionsFactory.ts index 8e0b2c662..22879cd3e 100644 --- a/src/transactionsFactories/delegationTransactionsFactory.ts +++ b/src/delegation/delegationTransactionsFactory.ts @@ -4,7 +4,8 @@ import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../constants"; import { Err } from "../errors"; import { IAddress } from "../interface"; import { Transaction } from "../transaction"; -import { TransactionBuilder } from "./transactionBuilder"; +import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; +import * as inputs from "./resources"; interface IConfig { chainID: string; @@ -20,7 +21,7 @@ interface IConfig { additionalGasLimitForDelegationOperations: bigint; } -interface IValidatorPublicKey { +export interface IValidatorPublicKey { hex(): string; } @@ -38,12 +39,10 @@ export class DelegationTransactionsFactory { this.delegationManagerAddress = Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, this.config.addressHrp); } - createTransactionForNewDelegationContract(options: { - sender: IAddress; - totalDelegationCap: bigint; - serviceFee: bigint; - amount: bigint; - }): Transaction { + createTransactionForNewDelegationContract( + sender: IAddress, + options: inputs.NewDelegationContractInput, + ): Transaction { const dataParts = [ "createNewDelegationContract", ...this.argSerializer.valuesToStrings([ @@ -57,7 +56,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.delegationManagerAddress, dataParts: dataParts, gasLimit: executionGasLimit, @@ -66,12 +65,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForAddingNodes(options: { - sender: IAddress; - delegationContract: IAddress; - publicKeys: IValidatorPublicKey[]; - signedMessages: Uint8Array[]; - }): Transaction { + createTransactionForAddingNodes(sender: IAddress, options: inputs.AddNodesInput): Transaction { if (options.publicKeys.length !== options.signedMessages.length) { throw new Err("The number of public keys should match the number of signed messages"); } @@ -90,7 +84,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), @@ -98,11 +92,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForRemovingNodes(options: { - sender: IAddress; - delegationContract: IAddress; - publicKeys: IValidatorPublicKey[]; - }): Transaction { + createTransactionForRemovingNodes(sender: IAddress, options: inputs.ManageNodesInput): Transaction { const dataParts = ["removeNodes"]; for (const key of options.publicKeys) { @@ -112,7 +102,7 @@ export class DelegationTransactionsFactory { const numNodes = options.publicKeys.length; return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), @@ -120,11 +110,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForStakingNodes(options: { - sender: IAddress; - delegationContract: IAddress; - publicKeys: IValidatorPublicKey[]; - }): Transaction { + createTransactionForStakingNodes(sender: IAddress, options: inputs.ManageNodesInput): Transaction { let dataParts = ["stakeNodes"]; for (const key of options.publicKeys) { @@ -139,7 +125,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: executionGasLimit, @@ -147,11 +133,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnbondingNodes(options: { - sender: IAddress; - delegationContract: IAddress; - publicKeys: IValidatorPublicKey[]; - }): Transaction { + createTransactionForUnbondingNodes(sender: IAddress, options: inputs.ManageNodesInput): Transaction { let dataParts = ["unBondNodes"]; for (const key of options.publicKeys) { @@ -166,7 +148,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: executionGasLimit, @@ -174,11 +156,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnstakingNodes(options: { - sender: IAddress; - delegationContract: IAddress; - publicKeys: IValidatorPublicKey[]; - }): Transaction { + createTransactionForUnstakingNodes(sender: IAddress, options: inputs.ManageNodesInput): Transaction { let dataParts = ["unStakeNodes"]; for (const key of options.publicKeys) { @@ -193,7 +171,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: executionGasLimit, @@ -201,12 +179,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnjailingNodes(options: { - sender: IAddress; - delegationContract: IAddress; - publicKeys: IValidatorPublicKey[]; - amount: bigint; - }): Transaction { + createTransactionForUnjailingNodes(sender: IAddress, options: inputs.UnjailingNodesInput): Transaction { const dataParts = ["unJailNodes"]; for (const key of options.publicKeys) { @@ -216,7 +189,7 @@ export class DelegationTransactionsFactory { const numNodes = options.publicKeys.length; return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), @@ -225,11 +198,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForChangingServiceFee(options: { - sender: IAddress; - delegationContract: IAddress; - serviceFee: bigint; - }): Transaction { + createTransactionForChangingServiceFee(sender: IAddress, options: inputs.ChangeServiceFee): Transaction { const dataParts = [ "changeServiceFee", this.argSerializer.valuesToStrings([new BigUIntValue(options.serviceFee)])[0], @@ -239,7 +208,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: gasLimit, @@ -247,11 +216,10 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForModifyingDelegationCap(options: { - sender: IAddress; - delegationContract: IAddress; - delegationCap: bigint; - }): Transaction { + createTransactionForModifyingDelegationCap( + sender: IAddress, + options: inputs.ModifyDelegationCapInput, + ): Transaction { const dataParts = [ "modifyTotalDelegationCap", this.argSerializer.valuesToStrings([new BigUIntValue(options.delegationCap)])[0], @@ -261,7 +229,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: gasLimit, @@ -269,17 +237,17 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForSettingAutomaticActivation(options: { - sender: IAddress; - delegationContract: IAddress; - }): Transaction { + createTransactionForSettingAutomaticActivation( + sender: IAddress, + options: inputs.ManageDelegationContractInput, + ): Transaction { const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new StringValue("true")])[0]]; const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: gasLimit, @@ -287,17 +255,17 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnsettingAutomaticActivation(options: { - sender: IAddress; - delegationContract: IAddress; - }): Transaction { + createTransactionForUnsettingAutomaticActivation( + sender: IAddress, + options: inputs.ManageDelegationContractInput, + ): Transaction { const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new StringValue("false")])[0]]; const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: gasLimit, @@ -305,10 +273,10 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForSettingCapCheckOnRedelegateRewards(options: { - sender: IAddress; - delegationContract: IAddress; - }): Transaction { + createTransactionForSettingCapCheckOnRedelegateRewards( + sender: IAddress, + options: inputs.ManageDelegationContractInput, + ): Transaction { const dataParts = [ "setCheckCapOnReDelegateRewards", this.argSerializer.valuesToStrings([new StringValue("true")])[0], @@ -318,7 +286,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: gasLimit, @@ -326,10 +294,10 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnsettingCapCheckOnRedelegateRewards(options: { - sender: IAddress; - delegationContract: IAddress; - }): Transaction { + createTransactionForUnsettingCapCheckOnRedelegateRewards( + sender: IAddress, + options: inputs.ManageDelegationContractInput, + ): Transaction { const dataParts = [ "setCheckCapOnReDelegateRewards", this.argSerializer.valuesToStrings([new StringValue("false")])[0], @@ -339,7 +307,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: gasLimit, @@ -347,13 +315,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForSettingMetadata(options: { - sender: IAddress; - delegationContract: IAddress; - name: string; - website: string; - identifier: string; - }): Transaction { + createTransactionForSettingMetadata(sender: IAddress, options: inputs.SetContractMetadataInput): Transaction { const dataParts = [ "setMetaData", ...this.argSerializer.valuesToStrings([ @@ -368,7 +330,7 @@ export class DelegationTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.delegationContract, dataParts: dataParts, gasLimit: gasLimit, @@ -376,6 +338,28 @@ export class DelegationTransactionsFactory { }).build(); } + createTransactionForWithdrawing(_sender: IAddress, _options: inputs.ManageDelegationContractInput): Transaction { + throw new Error("Method not implemented."); + } + createTransactionForUndelegating(_sender: IAddress, _options: inputs.DelegateActionsInput): Transaction { + throw new Error("Method not implemented."); + } + createTransactionForRedelegatingRewards( + _sender: IAddress, + _options: inputs.ManageDelegationContractInput, + ): Transaction { + throw new Error("Method not implemented."); + } + createTransactionForClaimingRewards( + _sender: IAddress, + _options: inputs.ManageDelegationContractInput, + ): Transaction { + throw new Error("Method not implemented."); + } + createTransactionForDelegating(_sender: IAddress, _options: inputs.DelegateActionsInput): Transaction { + throw new Error("Method not implemented."); + } + private computeExecutionGasLimitForNodesManagement(numNodes: number): bigint { const additionalGasForAllNodes = this.config.additionalGasLimitPerValidatorNode * BigInt(numNodes); diff --git a/src/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.spec.ts b/src/delegation/delegationTransactionsOutcomeParser.spec.ts similarity index 94% rename from src/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.spec.ts rename to src/delegation/delegationTransactionsOutcomeParser.spec.ts index c57ac28c4..aa043b548 100644 --- a/src/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.spec.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.spec.ts @@ -1,8 +1,13 @@ import { assert } from "chai"; import { Address } from "../address"; import { b64TopicsToBytes } from "../testutils"; +import { + SmartContractResult, + TransactionEvent, + TransactionLogs, + TransactionOutcome, +} from "../transactionsOutcomeParsers/resources"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; -import { SmartContractResult, TransactionEvent, TransactionLogs, TransactionOutcome } from "./resources"; describe("test delegation transactions outcome parser", () => { const parser = new DelegationTransactionsOutcomeParser(); diff --git a/src/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.ts b/src/delegation/delegationTransactionsOutcomeParser.ts similarity index 97% rename from src/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.ts rename to src/delegation/delegationTransactionsOutcomeParser.ts index b7e9a0a03..a267f8e8b 100644 --- a/src/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.ts @@ -2,7 +2,7 @@ import { Address } from "../address"; import { TransactionsConverter } from "../converters/transactionsConverter"; import { ErrParseTransactionOutcome } from "../errors"; import { ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { TransactionEvent, TransactionOutcome, findEventsByIdentifier } from "./resources"; +import { TransactionEvent, TransactionOutcome, findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; export class DelegationTransactionsOutcomeParser { constructor() {} diff --git a/src/delegation/index.ts b/src/delegation/index.ts new file mode 100644 index 000000000..955224312 --- /dev/null +++ b/src/delegation/index.ts @@ -0,0 +1,3 @@ +export * from "./delegationController"; +export * from "./delegationTransactionsFactory"; +export * from "./delegationTransactionsOutcomeParser"; diff --git a/src/delegation/resources.ts b/src/delegation/resources.ts new file mode 100644 index 000000000..63607e475 --- /dev/null +++ b/src/delegation/resources.ts @@ -0,0 +1,17 @@ +import { Address } from "../address"; +import { IValidatorPublicKey } from "./delegationTransactionsFactory"; + +export type NewDelegationContractInput = { totalDelegationCap: bigint; serviceFee: bigint; amount: bigint }; +export type AddNodesInput = ManageNodesInput & { signedMessages: Uint8Array[] }; +export type UnjailingNodesInput = ManageNodesInput & { amount: bigint }; +export type ManageNodesInput = { delegationContract: Address; publicKeys: IValidatorPublicKey[] }; +export type ChangeServiceFee = { delegationContract: Address; serviceFee: bigint }; +export type ModifyDelegationCapInput = { delegationContract: Address; delegationCap: bigint }; +export type ManageDelegationContractInput = { delegationContract: Address }; +export type DelegateActionsInput = { delegationContract: Address; amount: bigint }; +export type SetContractMetadataInput = { + delegationContract: Address; + name: string; + website: string; + identifier: string; +}; diff --git a/src/index.ts b/src/index.ts index 83fb068d9..f45b90477 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ export * from "./address"; export * from "./asyncTimer"; export * from "./config"; export * from "./converters"; +export * from "./delegation"; export * from "./errors"; export * from "./gasEstimator"; export * from "./interface"; diff --git a/src/transactionsFactories/index.ts b/src/transactionsFactories/index.ts index 075c6b33a..e3edd8fcc 100644 --- a/src/transactionsFactories/index.ts +++ b/src/transactionsFactories/index.ts @@ -1,5 +1,4 @@ export * from "../accountManagement/accountTransactionsFactory"; -export * from "./delegationTransactionsFactory"; export * from "./relayedTransactionsFactory"; export * from "./smartContractTransactionsFactory"; export * from "./tokenManagementTransactionsFactory"; diff --git a/src/transactionsOutcomeParsers/index.ts b/src/transactionsOutcomeParsers/index.ts index b50f8ba9c..8c5a55439 100644 --- a/src/transactionsOutcomeParsers/index.ts +++ b/src/transactionsOutcomeParsers/index.ts @@ -1,4 +1,3 @@ -export * from "./delegationTransactionsOutcomeParser"; export * from "./resources"; export * from "./smartContractTransactionsOutcomeParser"; export * from "./tokenManagementTransactionsOutcomeParser"; From d6ebcc53947544bb7874c46065618ca9a6749522 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 14:31:49 +0200 Subject: [PATCH 014/214] Fix test --- src/delegation/delegationTransactionsFactory.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index 46c788db2..91a999feb 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -24,7 +24,7 @@ describe("test delegation transactions factory", function () { assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); assert.equal( transaction.receiver, - Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, this.config.addressHrp).bech32(), + Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, config.addressHrp).bech32(), ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("createNewDelegationContract@010f0cf064dd59200000@0a")); From ad13a18746d8bf4910b8609d9bbe1008573d3041 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 14:56:03 +0200 Subject: [PATCH 015/214] Fix tests --- .../delegationTransactionsFactory.spec.ts | 94 +++++++++++-------- .../delegationTransactionsFactory.ts | 49 +++++----- src/delegation/resources.ts | 4 +- 3 files changed, 84 insertions(+), 63 deletions(-) diff --git a/src/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index 91a999feb..67f21a49e 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -73,11 +73,11 @@ describe("test delegation transactions factory", function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - const publicKey = { - hex(): string { - return Buffer.from("abba").toString("hex"); - }, - }; + const publicKey = new ValidatorPublicKey( + Buffer.from( + "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", + ), + ); const transaction = delegationFactory.createTransactionForRemovingNodes(sender, { delegationContract: delegationContract, @@ -87,19 +87,23 @@ describe("test delegation transactions factory", function () { assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); assert.isDefined(transaction.data); - assert.deepEqual(transaction.data, Buffer.from("removeNodes@61626261")); + assert.deepEqual( + transaction.data, + Buffer.from( + "removeNodes@626532653539336666313038393961326565386531643563383039346533366339663438653034623837653132393939316666303934373538303837343365303762623431626636653762633134363366613535346334623436353934623938", + ), + ); assert.equal(transaction.value, 0n); }); it("should create 'Transaction' for staking nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - - const publicKey = { - hex(): string { - return Buffer.from("abba").toString("hex"); - }, - }; + const publicKey = new ValidatorPublicKey( + Buffer.from( + "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", + ), + ); const transaction = delegationFactory.createTransactionForStakingNodes(sender, { delegationContract: delegationContract, @@ -109,19 +113,23 @@ describe("test delegation transactions factory", function () { assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); assert.isDefined(transaction.data); - assert.deepEqual(transaction.data, Buffer.from("stakeNodes@61626261")); + assert.deepEqual( + transaction.data, + Buffer.from( + "stakeNodes@626532653539336666313038393961326565386531643563383039346533366339663438653034623837653132393939316666303934373538303837343365303762623431626636653762633134363366613535346334623436353934623938", + ), + ); assert.equal(transaction.value, 0n); }); it("should create 'Transaction' for unbonding nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - - const publicKey = { - hex(): string { - return Buffer.from("abba").toString("hex"); - }, - }; + const publicKey = new ValidatorPublicKey( + Buffer.from( + "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", + ), + ); const transaction = delegationFactory.createTransactionForUnbondingNodes(sender, { delegationContract: delegationContract, @@ -131,20 +139,24 @@ describe("test delegation transactions factory", function () { assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); assert.isDefined(transaction.data); - assert.deepEqual(transaction.data, Buffer.from("unBondNodes@61626261")); + assert.deepEqual( + transaction.data, + Buffer.from( + "unBondNodes@626532653539336666313038393961326565386531643563383039346533366339663438653034623837653132393939316666303934373538303837343365303762623431626636653762633134363366613535346334623436353934623938", + ), + ); assert.equal(transaction.value, 0n); - assert.equal(transaction.gasLimit, 12080000n); + assert.equal(transaction.gasLimit, 12356000n); }); it("should create 'Transaction' for unstaking nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - - const publicKey = { - hex(): string { - return Buffer.from("abba").toString("hex"); - }, - }; + const publicKey = new ValidatorPublicKey( + Buffer.from( + "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", + ), + ); const transaction = delegationFactory.createTransactionForUnstakingNodes(sender, { delegationContract: delegationContract, @@ -154,31 +166,39 @@ describe("test delegation transactions factory", function () { assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); assert.isDefined(transaction.data); - assert.deepEqual(transaction.data, Buffer.from("unStakeNodes@61626261")); + assert.deepEqual( + transaction.data, + Buffer.from( + "unStakeNodes@626532653539336666313038393961326565386531643563383039346533366339663438653034623837653132393939316666303934373538303837343365303762623431626636653762633134363366613535346334623436353934623938", + ), + ); assert.equal(transaction.value, 0n); - assert.equal(transaction.gasLimit, 12081500n); + assert.equal(transaction.gasLimit, 12357500n); }); it("should create 'Transaction' for unjailing nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); - - const publicKey = { - hex(): string { - return Buffer.from("abba").toString("hex"); - }, - }; + const publicKey = new ValidatorPublicKey( + Buffer.from( + "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", + ), + ); const transaction = delegationFactory.createTransactionForUnjailingNodes(sender, { delegationContract: delegationContract, publicKeys: [publicKey], amount: 25000000000000000000n, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); assert.isDefined(transaction.data); - assert.deepEqual(transaction.data, Buffer.from("unJailNodes@61626261")); + assert.deepEqual( + transaction.data, + Buffer.from( + "unJailNodes@626532653539336666313038393961326565386531643563383039346533366339663438653034623837653132393939316666303934373538303837343365303762623431626636653762633134363366613535346334623436353934623938", + ), + ); assert.equal(transaction.value, 25000000000000000000n); }); diff --git a/src/delegation/delegationTransactionsFactory.ts b/src/delegation/delegationTransactionsFactory.ts index 22879cd3e..193521827 100644 --- a/src/delegation/delegationTransactionsFactory.ts +++ b/src/delegation/delegationTransactionsFactory.ts @@ -5,7 +5,7 @@ import { Err } from "../errors"; import { IAddress } from "../interface"; import { Transaction } from "../transaction"; import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; -import * as inputs from "./resources"; +import * as resources from "./resources"; interface IConfig { chainID: string; @@ -21,10 +21,6 @@ interface IConfig { additionalGasLimitForDelegationOperations: bigint; } -export interface IValidatorPublicKey { - hex(): string; -} - /** * Use this class to create delegation related transactions like creating a new delegation contract or adding nodes. */ @@ -41,7 +37,7 @@ export class DelegationTransactionsFactory { createTransactionForNewDelegationContract( sender: IAddress, - options: inputs.NewDelegationContractInput, + options: resources.NewDelegationContractInput, ): Transaction { const dataParts = [ "createNewDelegationContract", @@ -65,7 +61,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForAddingNodes(sender: IAddress, options: inputs.AddNodesInput): Transaction { + createTransactionForAddingNodes(sender: IAddress, options: resources.AddNodesInput): Transaction { if (options.publicKeys.length !== options.signedMessages.length) { throw new Err("The number of public keys should match the number of signed messages"); } @@ -92,7 +88,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForRemovingNodes(sender: IAddress, options: inputs.ManageNodesInput): Transaction { + createTransactionForRemovingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { const dataParts = ["removeNodes"]; for (const key of options.publicKeys) { @@ -110,8 +106,9 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForStakingNodes(sender: IAddress, options: inputs.ManageNodesInput): Transaction { + createTransactionForStakingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { let dataParts = ["stakeNodes"]; + console.log(options.publicKeys); for (const key of options.publicKeys) { dataParts = dataParts.concat(key.hex()); @@ -133,7 +130,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnbondingNodes(sender: IAddress, options: inputs.ManageNodesInput): Transaction { + createTransactionForUnbondingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { let dataParts = ["unBondNodes"]; for (const key of options.publicKeys) { @@ -156,7 +153,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnstakingNodes(sender: IAddress, options: inputs.ManageNodesInput): Transaction { + createTransactionForUnstakingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { let dataParts = ["unStakeNodes"]; for (const key of options.publicKeys) { @@ -179,7 +176,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnjailingNodes(sender: IAddress, options: inputs.UnjailingNodesInput): Transaction { + createTransactionForUnjailingNodes(sender: IAddress, options: resources.UnjailingNodesInput): Transaction { const dataParts = ["unJailNodes"]; for (const key of options.publicKeys) { @@ -198,7 +195,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForChangingServiceFee(sender: IAddress, options: inputs.ChangeServiceFee): Transaction { + createTransactionForChangingServiceFee(sender: IAddress, options: resources.ChangeServiceFee): Transaction { const dataParts = [ "changeServiceFee", this.argSerializer.valuesToStrings([new BigUIntValue(options.serviceFee)])[0], @@ -218,7 +215,7 @@ export class DelegationTransactionsFactory { createTransactionForModifyingDelegationCap( sender: IAddress, - options: inputs.ModifyDelegationCapInput, + options: resources.ModifyDelegationCapInput, ): Transaction { const dataParts = [ "modifyTotalDelegationCap", @@ -239,7 +236,7 @@ export class DelegationTransactionsFactory { createTransactionForSettingAutomaticActivation( sender: IAddress, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Transaction { const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new StringValue("true")])[0]]; const gasLimit = @@ -257,7 +254,7 @@ export class DelegationTransactionsFactory { createTransactionForUnsettingAutomaticActivation( sender: IAddress, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Transaction { const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new StringValue("false")])[0]]; const gasLimit = @@ -275,7 +272,7 @@ export class DelegationTransactionsFactory { createTransactionForSettingCapCheckOnRedelegateRewards( sender: IAddress, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Transaction { const dataParts = [ "setCheckCapOnReDelegateRewards", @@ -296,7 +293,7 @@ export class DelegationTransactionsFactory { createTransactionForUnsettingCapCheckOnRedelegateRewards( sender: IAddress, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Transaction { const dataParts = [ "setCheckCapOnReDelegateRewards", @@ -315,7 +312,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForSettingMetadata(sender: IAddress, options: inputs.SetContractMetadataInput): Transaction { + createTransactionForSettingMetadata(sender: IAddress, options: resources.SetContractMetadataInput): Transaction { const dataParts = [ "setMetaData", ...this.argSerializer.valuesToStrings([ @@ -338,25 +335,29 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForWithdrawing(_sender: IAddress, _options: inputs.ManageDelegationContractInput): Transaction { + createTransactionForWithdrawing(_sender: IAddress, _options: resources.ManageDelegationContractInput): Transaction { throw new Error("Method not implemented."); } - createTransactionForUndelegating(_sender: IAddress, _options: inputs.DelegateActionsInput): Transaction { + + createTransactionForUndelegating(_sender: IAddress, _options: resources.DelegateActionsInput): Transaction { throw new Error("Method not implemented."); } + createTransactionForRedelegatingRewards( _sender: IAddress, - _options: inputs.ManageDelegationContractInput, + _options: resources.ManageDelegationContractInput, ): Transaction { throw new Error("Method not implemented."); } + createTransactionForClaimingRewards( _sender: IAddress, - _options: inputs.ManageDelegationContractInput, + _options: resources.ManageDelegationContractInput, ): Transaction { throw new Error("Method not implemented."); } - createTransactionForDelegating(_sender: IAddress, _options: inputs.DelegateActionsInput): Transaction { + + createTransactionForDelegating(_sender: IAddress, _options: resources.DelegateActionsInput): Transaction { throw new Error("Method not implemented."); } diff --git a/src/delegation/resources.ts b/src/delegation/resources.ts index 63607e475..fd566cf16 100644 --- a/src/delegation/resources.ts +++ b/src/delegation/resources.ts @@ -1,10 +1,10 @@ import { Address } from "../address"; -import { IValidatorPublicKey } from "./delegationTransactionsFactory"; +import { ValidatorPublicKey } from "../wallet"; export type NewDelegationContractInput = { totalDelegationCap: bigint; serviceFee: bigint; amount: bigint }; export type AddNodesInput = ManageNodesInput & { signedMessages: Uint8Array[] }; export type UnjailingNodesInput = ManageNodesInput & { amount: bigint }; -export type ManageNodesInput = { delegationContract: Address; publicKeys: IValidatorPublicKey[] }; +export type ManageNodesInput = { delegationContract: Address; publicKeys: ValidatorPublicKey[] }; export type ChangeServiceFee = { delegationContract: Address; serviceFee: bigint }; export type ModifyDelegationCapInput = { delegationContract: Address; delegationCap: bigint }; export type ManageDelegationContractInput = { delegationContract: Address }; From 3becf91cfdfdf9810f5df26ec8f78888a853f578 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 15:08:40 +0200 Subject: [PATCH 016/214] Add relayed folder --- src/index.ts | 1 + src/relayed/index.ts | 2 + src/relayed/relayedController.ts | 41 +++++++++++++++++++ .../relayedTransactionsFactory.spec.ts | 2 +- .../relayedTransactionsFactory.ts | 0 src/relayed/resources.ts | 8 ++++ src/transactionsFactories/index.ts | 2 - 7 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 src/relayed/index.ts create mode 100644 src/relayed/relayedController.ts rename src/{transactionsFactories => relayed}/relayedTransactionsFactory.spec.ts (99%) rename src/{transactionsFactories => relayed}/relayedTransactionsFactory.ts (100%) create mode 100644 src/relayed/resources.ts diff --git a/src/index.ts b/src/index.ts index f45b90477..87ed40c94 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,6 +23,7 @@ export * from "./logger"; export * from "./message"; export * from "./networkParams"; export * from "./networkProviders"; +export * from "./relayed"; export * from "./relayedTransactionV1Builder"; export * from "./relayedTransactionV2Builder"; export * from "./signableMessage"; diff --git a/src/relayed/index.ts b/src/relayed/index.ts new file mode 100644 index 000000000..fbf0c51f0 --- /dev/null +++ b/src/relayed/index.ts @@ -0,0 +1,2 @@ +export * from "./relayedController"; +export * from "./relayedTransactionsFactory"; diff --git a/src/relayed/relayedController.ts b/src/relayed/relayedController.ts new file mode 100644 index 000000000..f1b35f8c1 --- /dev/null +++ b/src/relayed/relayedController.ts @@ -0,0 +1,41 @@ +import { IAccount } from "../accounts/interfaces"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; +import { CreateV1RelayTransactionInput, CreateV2RelayTransactionInput } from "./resources"; + +export class RelayedController { + private factory: RelayedTransactionsFactory; + private txComputer: TransactionComputer; + + /** + * The transactions are created from the perspective of the relayer. + * The 'sender' represents the relayer. + */ + constructor(options: { chainID: string }) { + this.factory = new RelayedTransactionsFactory({ + config: new TransactionsFactoryConfig(options), + }); + this.txComputer = new TransactionComputer(); + } + + async createRelayedV1Transaction(sender: IAccount, options: CreateV1RelayTransactionInput): Promise { + const transaction = this.factory.createRelayedV1Transaction({ ...options, relayerAddress: sender.address }); + + transaction.nonce = options.nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createRelayedV2Transaction(sender: IAccount, options: CreateV2RelayTransactionInput): Promise { + const transaction = this.factory.createRelayedV2Transaction({ ...options, relayerAddress: sender.address }); + + transaction.nonce = options.nonce; + transaction.gasLimit = BigInt(0); + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } +} diff --git a/src/transactionsFactories/relayedTransactionsFactory.spec.ts b/src/relayed/relayedTransactionsFactory.spec.ts similarity index 99% rename from src/transactionsFactories/relayedTransactionsFactory.spec.ts rename to src/relayed/relayedTransactionsFactory.spec.ts index 6c61d331a..8adca1afb 100644 --- a/src/transactionsFactories/relayedTransactionsFactory.spec.ts +++ b/src/relayed/relayedTransactionsFactory.spec.ts @@ -2,8 +2,8 @@ import { assert } from "chai"; import { TestWallet, loadTestWallets } from "../testutils"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; -import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; describe("test relayed transactions factory", function () { const config = new TransactionsFactoryConfig({ chainID: "T" }); diff --git a/src/transactionsFactories/relayedTransactionsFactory.ts b/src/relayed/relayedTransactionsFactory.ts similarity index 100% rename from src/transactionsFactories/relayedTransactionsFactory.ts rename to src/relayed/relayedTransactionsFactory.ts diff --git a/src/relayed/resources.ts b/src/relayed/resources.ts new file mode 100644 index 000000000..6c33853ed --- /dev/null +++ b/src/relayed/resources.ts @@ -0,0 +1,8 @@ +import { ITransaction } from "../interface"; + +export type CreateV1RelayTransactionInput = { nonce: bigint; innerTransaction: ITransaction }; +export type CreateV2RelayTransactionInput = { + nonce: bigint; + innerTransaction: ITransaction; + innerTransactionGasLimit: bigint; +}; diff --git a/src/transactionsFactories/index.ts b/src/transactionsFactories/index.ts index e3edd8fcc..39ea35baf 100644 --- a/src/transactionsFactories/index.ts +++ b/src/transactionsFactories/index.ts @@ -1,5 +1,3 @@ -export * from "../accountManagement/accountTransactionsFactory"; -export * from "./relayedTransactionsFactory"; export * from "./smartContractTransactionsFactory"; export * from "./tokenManagementTransactionsFactory"; export * from "./transactionsFactoryConfig"; From 537e2676dd5bc9b308755917809864741d1568c1 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 15:27:13 +0200 Subject: [PATCH 017/214] Update input names --- src/delegation/delegationController.ts | 40 +++++++++++++------------- src/relayed/relayedController.ts | 6 ++-- src/relayed/resources.ts | 4 +-- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index 413968e5f..e8ad9c787 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -7,7 +7,7 @@ import { TransactionsFactoryConfig } from "../transactionsFactories"; import { TransactionWatcher } from "../transactionWatcher"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; -import * as inputs from "./resources"; +import * as resources from "./resources"; export class DelegationController { private transactionAwaiter: TransactionWatcher; @@ -27,7 +27,7 @@ export class DelegationController { async createTransactionForNewDelegationContract( sender: IAccount, nonce: bigint, - options: inputs.NewDelegationContractInput, + options: resources.NewDelegationContractInput, ): Promise { const transaction = this.factory.createTransactionForNewDelegationContract(sender.address, options); @@ -49,7 +49,7 @@ export class DelegationController { async createTransactionForAddingNodes( sender: IAccount, nonce: bigint, - options: inputs.AddNodesInput, + options: resources.AddNodesInput, ): Promise { const transaction = this.factory.createTransactionForAddingNodes(sender.address, options); @@ -62,7 +62,7 @@ export class DelegationController { async createTransactionForRemovingNodes( sender: IAccount, nonce: bigint, - options: inputs.ManageNodesInput, + options: resources.ManageNodesInput, ): Promise { const transaction = this.factory.createTransactionForRemovingNodes(sender.address, options); @@ -75,7 +75,7 @@ export class DelegationController { async createTransactionForStakingNodes( sender: IAccount, nonce: bigint, - options: inputs.ManageNodesInput, + options: resources.ManageNodesInput, ): Promise { const transaction = this.factory.createTransactionForStakingNodes(sender.address, options); @@ -88,7 +88,7 @@ export class DelegationController { async createTransactionForUnbondingNodes( sender: IAccount, nonce: bigint, - options: inputs.ManageNodesInput, + options: resources.ManageNodesInput, ): Promise { const transaction = this.factory.createTransactionForUnbondingNodes(sender.address, options); @@ -101,7 +101,7 @@ export class DelegationController { async createTransactionForUnstakingNodes( sender: IAccount, nonce: bigint, - options: inputs.ManageNodesInput, + options: resources.ManageNodesInput, ): Promise { const transaction = this.factory.createTransactionForUnstakingNodes(sender.address, options); @@ -114,7 +114,7 @@ export class DelegationController { async createTransactionForUnjailingNodes( sender: IAccount, nonce: bigint, - options: inputs.UnjailingNodesInput, + options: resources.UnjailingNodesInput, ): Promise { const transaction = this.factory.createTransactionForUnjailingNodes(sender.address, options); @@ -127,7 +127,7 @@ export class DelegationController { async createTransactionForChangingServiceFee( sender: IAccount, nonce: bigint, - options: inputs.ChangeServiceFee, + options: resources.ChangeServiceFee, ): Promise { const transaction = this.factory.createTransactionForChangingServiceFee(sender.address, options); @@ -140,7 +140,7 @@ export class DelegationController { async createTransactionForModifyingDelegationCap( sender: IAccount, nonce: bigint, - options: inputs.ModifyDelegationCapInput, + options: resources.ModifyDelegationCapInput, ): Promise { const transaction = this.factory.createTransactionForModifyingDelegationCap(sender.address, options); @@ -153,7 +153,7 @@ export class DelegationController { async createTransactionForSettingAutomaticActivation( sender: IAccount, nonce: bigint, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Promise { const transaction = this.factory.createTransactionForSettingAutomaticActivation(sender.address, options); @@ -166,7 +166,7 @@ export class DelegationController { async createTransactionForUnsettingAutomaticActivation( sender: IAccount, nonce: bigint, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingAutomaticActivation(sender.address, options); @@ -179,7 +179,7 @@ export class DelegationController { async createTransactionForSettingCapCheckOnRedelegateRewards( sender: IAccount, nonce: bigint, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Promise { const transaction = this.factory.createTransactionForSettingCapCheckOnRedelegateRewards( sender.address, @@ -195,7 +195,7 @@ export class DelegationController { async createTransactionForUnsettingCapCheckOnRedelegateRewards( sender: IAccount, nonce: bigint, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingCapCheckOnRedelegateRewards( sender.address, @@ -211,7 +211,7 @@ export class DelegationController { async createTransactionForSettingMetadata( sender: IAccount, nonce: bigint, - options: inputs.SetContractMetadataInput, + options: resources.SetContractMetadataInput, ): Promise { const transaction = this.factory.createTransactionForSettingMetadata(sender.address, options); @@ -224,7 +224,7 @@ export class DelegationController { async createTransactionForDelegating( sender: IAccount, nonce: bigint, - options: inputs.DelegateActionsInput, + options: resources.DelegateActionsInput, ): Promise { const transaction = this.factory.createTransactionForDelegating(sender.address, options); @@ -237,7 +237,7 @@ export class DelegationController { async createTransactionForClaimingRewards( sender: IAccount, nonce: bigint, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Promise { const transaction = this.factory.createTransactionForClaimingRewards(sender.address, options); @@ -250,7 +250,7 @@ export class DelegationController { async createTransactionForRedelegatingRewards( sender: IAccount, nonce: bigint, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Promise { const transaction = this.factory.createTransactionForRedelegatingRewards(sender.address, options); @@ -263,7 +263,7 @@ export class DelegationController { async createTransactionForUndelegating( sender: IAccount, nonce: bigint, - options: inputs.DelegateActionsInput, + options: resources.DelegateActionsInput, ): Promise { const transaction = this.factory.createTransactionForUndelegating(sender.address, options); @@ -276,7 +276,7 @@ export class DelegationController { async createTransactionForWithdrawing( sender: IAccount, nonce: bigint, - options: inputs.ManageDelegationContractInput, + options: resources.ManageDelegationContractInput, ): Promise { const transaction = this.factory.createTransactionForWithdrawing(sender.address, options); diff --git a/src/relayed/relayedController.ts b/src/relayed/relayedController.ts index f1b35f8c1..f9a5fb8ce 100644 --- a/src/relayed/relayedController.ts +++ b/src/relayed/relayedController.ts @@ -3,7 +3,7 @@ import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; import { TransactionsFactoryConfig } from "../transactionsFactories"; import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; -import { CreateV1RelayTransactionInput, CreateV2RelayTransactionInput } from "./resources"; +import { CreateV1RelayedTransactionInput, CreateV2RelayedTransactionInput } from "./resources"; export class RelayedController { private factory: RelayedTransactionsFactory; @@ -20,7 +20,7 @@ export class RelayedController { this.txComputer = new TransactionComputer(); } - async createRelayedV1Transaction(sender: IAccount, options: CreateV1RelayTransactionInput): Promise { + async createRelayedV1Transaction(sender: IAccount, options: CreateV1RelayedTransactionInput): Promise { const transaction = this.factory.createRelayedV1Transaction({ ...options, relayerAddress: sender.address }); transaction.nonce = options.nonce; @@ -29,7 +29,7 @@ export class RelayedController { return transaction; } - async createRelayedV2Transaction(sender: IAccount, options: CreateV2RelayTransactionInput): Promise { + async createRelayedV2Transaction(sender: IAccount, options: CreateV2RelayedTransactionInput): Promise { const transaction = this.factory.createRelayedV2Transaction({ ...options, relayerAddress: sender.address }); transaction.nonce = options.nonce; diff --git a/src/relayed/resources.ts b/src/relayed/resources.ts index 6c33853ed..4ffc5cf83 100644 --- a/src/relayed/resources.ts +++ b/src/relayed/resources.ts @@ -1,7 +1,7 @@ import { ITransaction } from "../interface"; -export type CreateV1RelayTransactionInput = { nonce: bigint; innerTransaction: ITransaction }; -export type CreateV2RelayTransactionInput = { +export type CreateV1RelayedTransactionInput = { nonce: bigint; innerTransaction: ITransaction }; +export type CreateV2RelayedTransactionInput = { nonce: bigint; innerTransaction: ITransaction; innerTransactionGasLimit: bigint; From 515e601681265e30c38ec5a5758e3cd819b7b9be Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 15:40:23 +0200 Subject: [PATCH 018/214] Add smart contract controller --- src/abi/interaction.ts | 12 +-- src/abi/interface.ts | 15 +-- src/abi/smartContract.ts | 27 +++--- src/smartContracts/index.ts | 3 + src/smartContracts/resources.ts | 46 +++++++++ src/smartContracts/smartContractController.ts | 95 +++++++++++++++++++ .../smartContractTransactionsFactory.spec.ts | 71 +++++--------- .../smartContractTransactionsFactory.ts | 64 ++++--------- ...tTransactionsOutcomeParser.dev.net.spec.ts | 0 ...TransactionsOutcomeParser.main.net.spec.ts | 0 ...tContractTransactionsOutcomeParser.spec.ts | 19 ++-- .../smartContractTransactionsOutcomeParser.ts | 6 +- src/transactionsFactories/index.ts | 1 - src/transactionsOutcomeParsers/index.ts | 2 +- 14 files changed, 231 insertions(+), 130 deletions(-) create mode 100644 src/smartContracts/index.ts create mode 100644 src/smartContracts/resources.ts create mode 100644 src/smartContracts/smartContractController.ts rename src/{transactionsFactories => smartContracts}/smartContractTransactionsFactory.spec.ts (94%) rename src/{transactionsFactories => smartContracts}/smartContractTransactionsFactory.ts (82%) rename src/{transactionsOutcomeParsers => smartContracts}/smartContractTransactionsOutcomeParser.dev.net.spec.ts (100%) rename src/{transactionsOutcomeParsers => smartContracts}/smartContractTransactionsOutcomeParser.main.net.spec.ts (100%) rename src/{transactionsOutcomeParsers => smartContracts}/smartContractTransactionsOutcomeParser.spec.ts (98%) rename src/{transactionsOutcomeParsers => smartContracts}/smartContractTransactionsOutcomeParser.ts (98%) diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index e1bedc5f4..8519308d7 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -3,9 +3,10 @@ import { Address } from "../address"; import { Compatibility } from "../compatibility"; import { TRANSACTION_VERSION_DEFAULT } from "../constants"; import { IAddress, IChainID, IGasLimit, IGasPrice, INonce, ITokenTransfer, ITransactionValue } from "../interface"; +import { SmartContractTransactionsFactory } from "../smartContracts"; import { TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; -import { SmartContractTransactionsFactory, TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; import { ContractFunction } from "./function"; import { InteractionChecker } from "./interactionChecker"; import { CallArguments } from "./interface"; @@ -17,7 +18,7 @@ import { EndpointDefinition, TypedValue } from "./typesystem"; */ interface ISmartContractWithinInteraction { call({ func, args, value, gasLimit, receiver }: CallArguments): Transaction; - getAddress(): IAddress; + getAddress(): Address; getEndpoint(name: ContractFunction): EndpointDefinition; } @@ -41,7 +42,7 @@ export class Interaction { private chainID: IChainID = ""; private querent: IAddress = Address.empty(); private explicitReceiver?: IAddress; - private sender: IAddress = Address.empty(); + private sender: Address = Address.empty(); private version: number = TRANSACTION_VERSION_DEFAULT; private tokenTransfers: TokenTransfer[]; @@ -97,8 +98,7 @@ export class Interaction { config: factoryConfig, }); - const transaction = factory.createTransactionForExecute({ - sender: this.sender, + const transaction = factory.createTransactionForExecute(this.sender, { contract: this.contract.getAddress(), function: this.function.valueOf(), gasLimit: BigInt(this.gasLimit.valueOf()), @@ -173,7 +173,7 @@ export class Interaction { return this; } - withSender(sender: IAddress): Interaction { + withSender(sender: Address): Interaction { this.sender = sender; return this; } diff --git a/src/abi/interface.ts b/src/abi/interface.ts index b474ad8ed..e51c5b70b 100644 --- a/src/abi/interface.ts +++ b/src/abi/interface.ts @@ -1,4 +1,5 @@ -import { IAddress, IChainID, IGasLimit, IGasPrice, ITransactionValue } from "../interface"; +import { Address } from "../address"; +import { IChainID, IGasLimit, IGasPrice, ITransactionValue } from "../interface"; import { Transaction } from "../transaction"; import { ReturnCode } from "./returnCode"; import { TypedValue } from "./typesystem"; @@ -10,7 +11,7 @@ export interface ISmartContract { /** * Gets the address of the Smart Contract. */ - getAddress(): IAddress; + getAddress(): Address; /** * Creates a {@link Transaction} for deploying the Smart Contract to the Network. @@ -36,7 +37,7 @@ export interface DeployArguments { gasLimit: IGasLimit; gasPrice?: IGasPrice; chainID: IChainID; - deployer: IAddress; + deployer: Address; } export interface UpgradeArguments { @@ -47,7 +48,7 @@ export interface UpgradeArguments { gasLimit: IGasLimit; gasPrice?: IGasPrice; chainID: IChainID; - caller: IAddress; + caller: Address; } export interface CallArguments { @@ -55,17 +56,17 @@ export interface CallArguments { args?: any[]; value?: ITransactionValue; gasLimit: IGasLimit; - receiver?: IAddress; + receiver?: Address; gasPrice?: IGasPrice; chainID: IChainID; - caller: IAddress; + caller: Address; } export interface QueryArguments { func: IContractFunction; args?: TypedValue[]; value?: ITransactionValue; - caller?: IAddress; + caller?: Address; } export interface TypedOutcomeBundle { diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index b06b7a5a5..ff8122bf4 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -2,11 +2,11 @@ import { Address, AddressComputer } from "../address"; import { Compatibility } from "../compatibility"; import { TRANSACTION_MIN_GAS_PRICE } from "../constants"; import { ErrContractHasNoAddress } from "../errors"; -import { IAddress, INonce } from "../interface"; +import { INonce } from "../interface"; import { Transaction } from "../transaction"; -import { SmartContractTransactionsFactory } from "../transactionsFactories/smartContractTransactionsFactory"; import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; import { guardValueIsSet } from "../utils"; +import { SmartContractTransactionsFactory } from "./../smartContracts/smartContractTransactionsFactory"; import { CodeMetadata } from "./codeMetadata"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; @@ -33,7 +33,7 @@ interface IAbi { * An abstraction for deploying and interacting with Smart Contracts. */ export class SmartContract implements ISmartContract { - private address: IAddress = Address.empty(); + private address: Address = Address.empty(); private abi?: IAbi; /** @@ -54,7 +54,7 @@ export class SmartContract implements ISmartContract { /** * Create a SmartContract object by providing its address on the Network. */ - constructor(options: { address?: IAddress; abi?: IAbi } = {}) { + constructor(options: { address?: Address; abi?: IAbi } = {}) { this.address = options.address || Address.empty(); this.abi = options.abi; @@ -93,14 +93,14 @@ export class SmartContract implements ISmartContract { /** * Sets the address, as on Network. */ - setAddress(address: IAddress) { + setAddress(address: Address) { this.address = address; } /** * Gets the address, as on Network. */ - getAddress(): IAddress { + getAddress(): Address { return this.address; } @@ -141,11 +141,10 @@ export class SmartContract implements ISmartContract { const bytecode = Buffer.from(code.toString(), "hex"); const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); - const transaction = factory.createTransactionForDeploy({ - sender: deployer, + const transaction = factory.createTransactionForDeploy(deployer, { bytecode: bytecode, gasLimit: BigInt(gasLimit.valueOf()), - arguments: initArguments, + arguments: initArguments ?? [], isUpgradeable: metadataAsJson.upgradeable, isReadable: metadataAsJson.readable, isPayable: metadataAsJson.payable, @@ -211,12 +210,11 @@ export class SmartContract implements ISmartContract { const bytecode = Uint8Array.from(Buffer.from(code.toString(), "hex")); const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); - const transaction = factory.createTransactionForUpgrade({ - sender: caller, + const transaction = factory.createTransactionForUpgrade(caller, { contract: this.getAddress(), bytecode: bytecode, gasLimit: BigInt(gasLimit.valueOf()), - arguments: initArguments, + arguments: initArguments ?? [], isUpgradeable: metadataAsJson.upgradeable, isReadable: metadataAsJson.readable, isPayable: metadataAsJson.payable, @@ -251,8 +249,7 @@ export class SmartContract implements ISmartContract { args = args || []; value = value || 0; - const transaction = factory.createTransactionForExecute({ - sender: caller, + const transaction = factory.createTransactionForExecute(caller, { contract: receiver ? receiver : this.getAddress(), function: func.toString(), gasLimit: BigInt(gasLimit.valueOf()), @@ -291,7 +288,7 @@ export class SmartContract implements ISmartContract { * @param owner The owner of the Smart Contract * @param nonce The owner nonce used for the deployment transaction */ - static computeAddress(owner: IAddress, nonce: INonce): IAddress { + static computeAddress(owner: Address, nonce: INonce): Address { const deployer = Address.fromBech32(owner.bech32()); const addressComputer = new AddressComputer(); return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); diff --git a/src/smartContracts/index.ts b/src/smartContracts/index.ts new file mode 100644 index 000000000..29233d303 --- /dev/null +++ b/src/smartContracts/index.ts @@ -0,0 +1,3 @@ +export * from "./smartContractController"; +export * from "./smartContractTransactionsFactory"; +export * from "./smartContractTransactionsOutcomeParser"; diff --git a/src/smartContracts/resources.ts b/src/smartContracts/resources.ts new file mode 100644 index 000000000..2b1bc298e --- /dev/null +++ b/src/smartContracts/resources.ts @@ -0,0 +1,46 @@ +import { Address } from "../address"; +import { TokenTransfer } from "../tokens"; + +export type ContractDepoyInput = { + bytecode: Uint8Array; + gasLimit: bigint; + arguments: any[]; + nativeTransferAmount?: bigint; + isUpgradeable?: boolean; + isReadable?: boolean; + isPayable?: boolean; + isPayableBySmartContract?: boolean; +}; + +export type TransactionInput = { + contract: Address; + gasLimit: bigint; + function: string; + arguments?: any[]; + nativeTransferAmount?: bigint; + tokenTransfers?: TokenTransfer[]; +}; + +export type ContractUpgradeInput = ContractDepoyInput & { contract: Address }; + +export interface SmartContractDeployOutcome { + returnCode: string; + returnMessage: string; + contracts: DeployedSmartContract[]; +} + +export class DeployedSmartContract { + address: string; + ownerAddress: string; + codeHash: Uint8Array; + + constructor(address: string, ownerAddress: string, codeHash: Uint8Array) { + this.address = address; + this.ownerAddress = ownerAddress; + this.codeHash = codeHash; + } + + toString(): string { + return `DeployedSmartContract(address=${this.address}, ownerAddress=${this.ownerAddress}, codeHash=${Buffer.from(this.codeHash).toString("hex")})`; + } +} diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts new file mode 100644 index 000000000..27dacb489 --- /dev/null +++ b/src/smartContracts/smartContractController.ts @@ -0,0 +1,95 @@ +import { AbiRegistry } from "../abi"; +import { IAccount } from "../accounts/interfaces"; +import { QueryRunnerAdapter } from "../adapters"; +import { IAddress } from "../interface"; +import { ITransactionOnNetwork } from "../interfaceOfNetwork"; +import { INetworkProvider } from "../networkProviders/interface"; +import { SmartContractQueriesController } from "../smartContractQueriesController"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { SmartContractTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; +import { TransactionWatcher } from "../transactionWatcher"; +import * as resources from "./resources"; +import { SmartContractTransactionsFactory } from "./smartContractTransactionsFactory"; + +export class SmartContractController { + private factory: SmartContractTransactionsFactory; + private parser: SmartContractTransactionsOutcomeParser; + private queryController: SmartContractQueriesController; + private transactionWatcher: TransactionWatcher; + private txComputer: TransactionComputer; + + constructor(options: { chainID: string; networkProvider: INetworkProvider; abi?: AbiRegistry }) { + this.factory = new SmartContractTransactionsFactory({ + config: new TransactionsFactoryConfig({ chainID: options.chainID }), + abi: options.abi, + }); + this.parser = new SmartContractTransactionsOutcomeParser(options); + + this.queryController = new SmartContractQueriesController({ + queryRunner: new QueryRunnerAdapter(options), + abi: options.abi, + }); + this.transactionWatcher = new TransactionWatcher(options.networkProvider); + this.txComputer = new TransactionComputer(); + } + + async createTransactionForDeploy( + sender: IAccount, + nonce: bigint, + options: resources.ContractDepoyInput, + ): Promise { + const transaction = this.factory.createTransactionForDeploy(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedDeploy(txHash: string): Promise { + const transaction = await this.transactionWatcher.awaitCompleted(txHash); + return this.parseDeploy(transaction); + } + + async createTransactionForUpgrade( + sender: IAccount, + nonce: bigint, + options: resources.ContractUpgradeInput, + ): Promise { + const transaction = this.factory.createTransactionForUpgrade(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForExecute( + sender: IAccount, + nonce: bigint, + options: resources.TransactionInput, + ): Promise { + const transaction = this.factory.createTransactionForExecute(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + queryContract(contract: IAddress, func: string, args: any[], caller?: IAddress, value?: bigint): Promise { + return this.queryController.query({ + contract: contract.bech32(), + function: func, + arguments: args, + caller: caller ? caller.bech32() : undefined, + value: BigInt(value ?? 0), + }); + } + + parseDeploy(transactionOnNetwork: ITransactionOnNetwork): resources.SmartContractDeployOutcome { + return this.parser.parseDeploy({ transactionOnNetwork }); + } +} diff --git a/src/transactionsFactories/smartContractTransactionsFactory.spec.ts b/src/smartContracts/smartContractTransactionsFactory.spec.ts similarity index 94% rename from src/transactionsFactories/smartContractTransactionsFactory.spec.ts rename to src/smartContracts/smartContractTransactionsFactory.spec.ts index 62633f757..b2c88ff97 100644 --- a/src/transactionsFactories/smartContractTransactionsFactory.spec.ts +++ b/src/smartContracts/smartContractTransactionsFactory.spec.ts @@ -4,8 +4,8 @@ import { Address } from "../address"; import { Err } from "../errors"; import { loadAbiRegistry, loadContractCode } from "../testutils/utils"; import { Token, TokenTransfer } from "../tokens"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; import { SmartContractTransactionsFactory } from "./smartContractTransactionsFactory"; -import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; describe("test smart contract transactions factory", function () { const config = new TransactionsFactoryConfig({ chainID: "D" }); @@ -35,8 +35,7 @@ describe("test smart contract transactions factory", function () { assert.throws( () => - factory.createTransactionForDeploy({ - sender: sender, + factory.createTransactionForDeploy(sender, { bytecode: bytecode.valueOf(), gasLimit: gasLimit, arguments: args, @@ -51,15 +50,13 @@ describe("test smart contract transactions factory", function () { const gasLimit = 6000000n; const args = [new U32Value(1)]; - const transaction = factory.createTransactionForDeploy({ - sender: sender, + const transaction = factory.createTransactionForDeploy(sender, { bytecode: bytecode.valueOf(), gasLimit: gasLimit, arguments: args, }); - const transactionAbiAware = abiAwareFactory.createTransactionForDeploy({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForDeploy(sender, { bytecode: bytecode.valueOf(), gasLimit: gasLimit, arguments: args, @@ -81,16 +78,14 @@ describe("test smart contract transactions factory", function () { const gasLimit = 6000000n; const args = [new U32Value(7)]; - const transaction = factory.createTransactionForExecute({ - sender: sender, + const transaction = factory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, arguments: args, }); - const transactionAbiAware = abiAwareFactory.createTransactionForExecute({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -113,8 +108,7 @@ describe("test smart contract transactions factory", function () { const gasLimit = 6000000n; const egldAmount = 1000000000000000000n; - const transaction = factory.createTransactionForExecute({ - sender: sender, + const transaction = factory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -122,8 +116,7 @@ describe("test smart contract transactions factory", function () { nativeTransferAmount: egldAmount, }); - const transactionAbiAware = abiAwareFactory.createTransactionForExecute({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -149,8 +142,7 @@ describe("test smart contract transactions factory", function () { const token = new Token({ identifier: "FOO-6ce17b", nonce: 0n }); const transfer = new TokenTransfer({ token, amount: 10n }); - const transaction = factory.createTransactionForExecute({ - sender: sender, + const transaction = factory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -158,8 +150,7 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [transfer], }); - const transactionAbiAware = abiAwareFactory.createTransactionForExecute({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -188,8 +179,7 @@ describe("test smart contract transactions factory", function () { const barToken = new Token({ identifier: "BAR-5bc08f", nonce: 0n }); const barTransfer = new TokenTransfer({ token: barToken, amount: 3140n }); - const transaction = factory.createTransactionForExecute({ - sender: sender, + const transaction = factory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -197,8 +187,7 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [fooTransfer, barTransfer], }); - const transactionAbiAware = abiAwareFactory.createTransactionForExecute({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -232,8 +221,7 @@ describe("test smart contract transactions factory", function () { const token = new Token({ identifier: "NFT-123456", nonce: 1n }); const transfer = new TokenTransfer({ token, amount: 1n }); - const transaction = factory.createTransactionForExecute({ - sender: sender, + const transaction = factory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -241,8 +229,7 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [transfer], }); - const transactionAbiAware = abiAwareFactory.createTransactionForExecute({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -279,8 +266,7 @@ describe("test smart contract transactions factory", function () { const secondToken = new Token({ identifier: "NFT-123456", nonce: 42n }); const secondTransfer = new TokenTransfer({ token: secondToken, amount: 1n }); - const transaction = factory.createTransactionForExecute({ - sender: sender, + const transaction = factory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -288,8 +274,7 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [firstTransfer, secondTransfer], }); - const transactionAbiAware = abiAwareFactory.createTransactionForExecute({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -326,8 +311,7 @@ describe("test smart contract transactions factory", function () { const secondToken = new Token({ identifier: "NFT-123456", nonce: 42n }); const secondTransfer = new TokenTransfer({ token: secondToken, amount: 1n }); - const transaction = factory.createTransactionForExecute({ - sender: sender, + const transaction = factory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -336,8 +320,7 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [firstTransfer, secondTransfer], }); - const transactionAbiAware = abiAwareFactory.createTransactionForExecute({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForExecute(sender, { contract: contract, function: func, gasLimit: gasLimit, @@ -369,16 +352,14 @@ describe("test smart contract transactions factory", function () { const gasLimit = 6000000n; const args = [new U32Value(7)]; - const transaction = factory.createTransactionForUpgrade({ - sender: sender, + const transaction = factory.createTransactionForUpgrade(sender, { contract: contract, bytecode: bytecode.valueOf(), gasLimit: gasLimit, arguments: args, }); - const transactionAbiAware = abiAwareFactory.createTransactionForUpgrade({ - sender: sender, + const transactionAbiAware = abiAwareFactory.createTransactionForUpgrade(sender, { contract: contract, bytecode: bytecode.valueOf(), gasLimit: gasLimit, @@ -442,8 +423,7 @@ describe("test smart contract transactions factory", function () { const gasLimit = 6000000n; // By default, use the upgrade constructor. - const tx1 = factory.createTransactionForUpgrade({ - sender: sender, + const tx1 = factory.createTransactionForUpgrade(sender, { contract: receiver, bytecode: bytecode, gasLimit: gasLimit, @@ -455,8 +435,7 @@ describe("test smart contract transactions factory", function () { // Fallback to the "upgrade" endpoint. (abi).upgradeConstructorDefinition = undefined; - const tx2 = factory.createTransactionForUpgrade({ - sender: sender, + const tx2 = factory.createTransactionForUpgrade(sender, { contract: receiver, bytecode: bytecode, gasLimit: gasLimit, @@ -468,8 +447,7 @@ describe("test smart contract transactions factory", function () { // Fallback to the constructor. (abi).endpoints.length = 0; - const tx3 = factory.createTransactionForUpgrade({ - sender: sender, + const tx3 = factory.createTransactionForUpgrade(sender, { contract: receiver, bytecode: bytecode, gasLimit: gasLimit, @@ -483,8 +461,7 @@ describe("test smart contract transactions factory", function () { assert.throws( () => - factory.createTransactionForUpgrade({ - sender: sender, + factory.createTransactionForUpgrade(sender, { contract: receiver, bytecode: bytecode, gasLimit: gasLimit, diff --git a/src/transactionsFactories/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts similarity index 82% rename from src/transactionsFactories/smartContractTransactionsFactory.ts rename to src/smartContracts/smartContractTransactionsFactory.ts index dc55129b1..e4caeab19 100644 --- a/src/transactionsFactories/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -1,14 +1,16 @@ -import { ArgSerializer, CodeMetadata, ContractFunction, EndpointDefinition, isTyped, NativeSerializer } from "../abi"; +import { ArgSerializer, CodeMetadata, ContractFunction, EndpointDefinition } from "../abi"; +import { NativeSerializer } from "../abi/nativeSerializer"; +import { isTyped } from "../abi/typesystem"; import { Address } from "../address"; import { CONTRACT_DEPLOY_ADDRESS_HEX, VM_TYPE_WASM_VM } from "../constants"; import { Err } from "../errors"; -import { IAddress } from "../interface"; import { Logger } from "../logger"; import { TokenComputer, TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; +import { TokenTransfersDataBuilder } from "../transactionsFactories/tokenTransfersDataBuilder"; +import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; import { byteArrayToHex, utf8ToHex } from "../utils.codec"; -import { TokenTransfersDataBuilder } from "./tokenTransfersDataBuilder"; -import { TransactionBuilder } from "./transactionBuilder"; +import * as resources from "./resources"; interface IConfig { chainID: string; @@ -44,17 +46,7 @@ export class SmartContractTransactionsFactory { this.contractDeployAddress = Address.fromHex(CONTRACT_DEPLOY_ADDRESS_HEX, this.config.addressHrp); } - createTransactionForDeploy(options: { - sender: IAddress; - bytecode: Uint8Array; - gasLimit: bigint; - arguments?: any[]; - nativeTransferAmount?: bigint; - isUpgradeable?: boolean; - isReadable?: boolean; - isPayable?: boolean; - isPayableBySmartContract?: boolean; - }): Transaction { + createTransactionForDeploy(sender: Address, options: resources.ContractDepoyInput): Transaction { const nativeTransferAmount = options.nativeTransferAmount ?? 0n; const isUpgradeable = options.isUpgradeable ?? true; const isReadable = options.isReadable ?? true; @@ -70,7 +62,7 @@ export class SmartContractTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.contractDeployAddress, dataParts: dataParts, gasLimit: options.gasLimit, @@ -79,15 +71,7 @@ export class SmartContractTransactionsFactory { }).build(); } - createTransactionForExecute(options: { - sender: IAddress; - contract: IAddress; - function: string; - gasLimit: bigint; - arguments?: any[]; - nativeTransferAmount?: bigint; - tokenTransfers?: TokenTransfer[]; - }): Transaction { + createTransactionForExecute(sender: Address, options: resources.TransactionInput): Transaction { const args = options.arguments || []; let tokenTransfers = options.tokenTransfers ? [...options.tokenTransfers] : []; let nativeTransferAmount = options.nativeTransferAmount ?? 0n; @@ -109,22 +93,23 @@ export class SmartContractTransactionsFactory { dataParts = this.dataArgsBuilder.buildDataPartsForESDTTransfer(transfer); } else { dataParts = this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); - receiver = options.sender; + receiver = sender; } } else if (numberOfTokens > 1) { dataParts = this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(receiver, tokenTransfers); - receiver = options.sender; + receiver = sender; } dataParts.push(dataParts.length ? utf8ToHex(options.function) : options.function); const endpoint = this.abi?.getEndpoint(options.function); + const preparedArgs = this.argsToDataParts(args, endpoint); dataParts.push(...preparedArgs); return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: receiver, dataParts: dataParts, gasLimit: options.gasLimit, @@ -133,18 +118,7 @@ export class SmartContractTransactionsFactory { }).build(); } - createTransactionForUpgrade(options: { - sender: IAddress; - contract: IAddress; - bytecode: Uint8Array; - gasLimit: bigint; - arguments?: any[]; - nativeTransferAmount?: bigint; - isUpgradeable?: boolean; - isReadable?: boolean; - isPayable?: boolean; - isPayableBySmartContract?: boolean; - }): Transaction { + createTransactionForUpgrade(sender: Address, options: resources.ContractUpgradeInput): Transaction { const nativeTransferAmount = options.nativeTransferAmount ?? 0n; const isUpgradeable = options.isUpgradeable ?? true; @@ -162,7 +136,7 @@ export class SmartContractTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: options.contract, dataParts: dataParts, gasLimit: options.gasLimit, @@ -193,7 +167,7 @@ export class SmartContractTransactionsFactory { } } - createTransactionForClaimingDeveloperRewards(options: { sender: IAddress; contract: IAddress }): Transaction { + createTransactionForClaimingDeveloperRewards(options: { sender: Address; contract: Address }): Transaction { const dataParts = ["ClaimDeveloperRewards"]; return new TransactionBuilder({ @@ -207,9 +181,9 @@ export class SmartContractTransactionsFactory { } createTransactionForChangingOwnerAddress(options: { - sender: IAddress; - contract: IAddress; - newOwner: IAddress; + sender: Address; + contract: Address; + newOwner: Address; }): Transaction { const dataParts = ["ChangeOwnerAddress", Address.fromBech32(options.newOwner.bech32()).toHex()]; diff --git a/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.dev.net.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts similarity index 100% rename from src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.dev.net.spec.ts rename to src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts diff --git a/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.main.net.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.main.net.spec.ts similarity index 100% rename from src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.main.net.spec.ts rename to src/smartContracts/smartContractTransactionsOutcomeParser.main.net.spec.ts diff --git a/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts similarity index 98% rename from src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.spec.ts rename to src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index e005f1b39..3e8149269 100644 --- a/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -1,17 +1,22 @@ +import BigNumber from "bignumber.js"; +import { assert } from "chai"; +import { Address } from "../address"; +import { TransactionsConverter } from "../converters/transactionsConverter"; import { ContractResultItem, ContractResults, - TransactionEventTopic, - TransactionOnNetwork, TransactionEventOnNetwork, + TransactionEventTopic, TransactionLogsOnNetwork, + TransactionOnNetwork, } from "../networkProviders"; -import BigNumber from "bignumber.js"; -import { assert } from "chai"; -import { Address } from "../address"; -import { TransactionsConverter } from "../converters/transactionsConverter"; import { loadAbiRegistry } from "../testutils"; -import { SmartContractCallOutcome, TransactionEvent, TransactionLogs, TransactionOutcome } from "./resources"; +import { + SmartContractCallOutcome, + TransactionEvent, + TransactionLogs, + TransactionOutcome, +} from "../transactionsOutcomeParsers/resources"; import { SmartContractTransactionsOutcomeParser } from "./smartContractTransactionsOutcomeParser"; describe("test smart contract transactions outcome parser", () => { diff --git a/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts similarity index 98% rename from src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.ts rename to src/smartContracts/smartContractTransactionsOutcomeParser.ts index f575622bb..5db245c85 100644 --- a/src/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -3,7 +3,11 @@ import { Address } from "../address"; import { ARGUMENTS_SEPARATOR } from "../constants"; import { Err } from "../errors"; import { IContractResultItem, ITransactionEvent, ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { SmartContractCallOutcome, TransactionOutcome, findEventsByIdentifier } from "./resources"; +import { + SmartContractCallOutcome, + TransactionOutcome, + findEventsByIdentifier, +} from "../transactionsOutcomeParsers/resources"; enum Events { SCDeploy = "SCDeploy", diff --git a/src/transactionsFactories/index.ts b/src/transactionsFactories/index.ts index 39ea35baf..23d727598 100644 --- a/src/transactionsFactories/index.ts +++ b/src/transactionsFactories/index.ts @@ -1,4 +1,3 @@ -export * from "./smartContractTransactionsFactory"; export * from "./tokenManagementTransactionsFactory"; export * from "./transactionsFactoryConfig"; export * from "./transferTransactionsFactory"; diff --git a/src/transactionsOutcomeParsers/index.ts b/src/transactionsOutcomeParsers/index.ts index 8c5a55439..6511796e7 100644 --- a/src/transactionsOutcomeParsers/index.ts +++ b/src/transactionsOutcomeParsers/index.ts @@ -1,4 +1,4 @@ +export * from "../smartContracts/smartContractTransactionsOutcomeParser"; export * from "./resources"; -export * from "./smartContractTransactionsOutcomeParser"; export * from "./tokenManagementTransactionsOutcomeParser"; export * from "./transactionEventsParser"; From 198e69cafcac8a4b5c8ed959018d3ca02eae364a Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 15:42:01 +0200 Subject: [PATCH 019/214] Update Relayed inputs --- src/relayed/relayedController.ts | 18 +++++++++++++----- src/relayed/resources.ts | 5 ++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/relayed/relayedController.ts b/src/relayed/relayedController.ts index f9a5fb8ce..21cf739b8 100644 --- a/src/relayed/relayedController.ts +++ b/src/relayed/relayedController.ts @@ -3,7 +3,7 @@ import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; import { TransactionsFactoryConfig } from "../transactionsFactories"; import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; -import { CreateV1RelayedTransactionInput, CreateV2RelayedTransactionInput } from "./resources"; +import { RelayedV1TransactionInput, RelayedV2TransactionInput } from "./resources"; export class RelayedController { private factory: RelayedTransactionsFactory; @@ -20,19 +20,27 @@ export class RelayedController { this.txComputer = new TransactionComputer(); } - async createRelayedV1Transaction(sender: IAccount, options: CreateV1RelayedTransactionInput): Promise { + async createRelayedV1Transaction( + sender: IAccount, + nonce: bigint, + options: RelayedV1TransactionInput, + ): Promise { const transaction = this.factory.createRelayedV1Transaction({ ...options, relayerAddress: sender.address }); - transaction.nonce = options.nonce; + transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; } - async createRelayedV2Transaction(sender: IAccount, options: CreateV2RelayedTransactionInput): Promise { + async createRelayedV2Transaction( + sender: IAccount, + nonce: bigint, + options: RelayedV2TransactionInput, + ): Promise { const transaction = this.factory.createRelayedV2Transaction({ ...options, relayerAddress: sender.address }); - transaction.nonce = options.nonce; + transaction.nonce = nonce; transaction.gasLimit = BigInt(0); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); diff --git a/src/relayed/resources.ts b/src/relayed/resources.ts index 4ffc5cf83..cb0494653 100644 --- a/src/relayed/resources.ts +++ b/src/relayed/resources.ts @@ -1,8 +1,7 @@ import { ITransaction } from "../interface"; -export type CreateV1RelayedTransactionInput = { nonce: bigint; innerTransaction: ITransaction }; -export type CreateV2RelayedTransactionInput = { - nonce: bigint; +export type RelayedV1TransactionInput = { innerTransaction: ITransaction }; +export type RelayedV2TransactionInput = { innerTransaction: ITransaction; innerTransactionGasLimit: bigint; }; From 54a869c0001221b2f6978b232aa355069716e461 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 14 Nov 2024 15:48:06 +0200 Subject: [PATCH 020/214] Update relayed to follow structions --- src/relayed/relayedController.ts | 4 +-- .../relayedTransactionsFactory.spec.ts | 28 +++++++------------ src/relayed/relayedTransactionsFactory.ts | 20 +++++++------ 3 files changed, 23 insertions(+), 29 deletions(-) diff --git a/src/relayed/relayedController.ts b/src/relayed/relayedController.ts index 21cf739b8..2b48500e0 100644 --- a/src/relayed/relayedController.ts +++ b/src/relayed/relayedController.ts @@ -25,7 +25,7 @@ export class RelayedController { nonce: bigint, options: RelayedV1TransactionInput, ): Promise { - const transaction = this.factory.createRelayedV1Transaction({ ...options, relayerAddress: sender.address }); + const transaction = this.factory.createRelayedV1Transaction(sender.address, options); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -38,7 +38,7 @@ export class RelayedController { nonce: bigint, options: RelayedV2TransactionInput, ): Promise { - const transaction = this.factory.createRelayedV2Transaction({ ...options, relayerAddress: sender.address }); + const transaction = this.factory.createRelayedV2Transaction(sender.address, options); transaction.nonce = nonce; transaction.gasLimit = BigInt(0); diff --git a/src/relayed/relayedTransactionsFactory.spec.ts b/src/relayed/relayedTransactionsFactory.spec.ts index 8adca1afb..cbd41f337 100644 --- a/src/relayed/relayedTransactionsFactory.spec.ts +++ b/src/relayed/relayedTransactionsFactory.spec.ts @@ -25,7 +25,7 @@ describe("test relayed transactions factory", function () { }); assert.throws(() => { - factory.createRelayedV1Transaction({ innerTransaction: innerTransaction, relayerAddress: bob.address }), + factory.createRelayedV1Transaction(bob.address, { innerTransaction: innerTransaction }), "The inner transaction is not signed"; }); @@ -33,7 +33,7 @@ describe("test relayed transactions factory", function () { innerTransaction.signature = Buffer.from("invalidsignature"); assert.throws(() => { - factory.createRelayedV1Transaction({ innerTransaction: innerTransaction, relayerAddress: bob.address }), + factory.createRelayedV1Transaction(bob.address, { innerTransaction: innerTransaction }), "The gas limit is not set for the inner transaction"; }); }); @@ -51,9 +51,8 @@ describe("test relayed transactions factory", function () { const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); innerTransaction.signature = await bob.signer.sign(serializedInnerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction({ + const relayedTransaction = factory.createRelayedV1Transaction(alice.getAddress(), { innerTransaction: innerTransaction, - relayerAddress: alice.address, }); relayedTransaction.nonce = 2627n; @@ -85,9 +84,8 @@ describe("test relayed transactions factory", function () { const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); innerTransaction.signature = await carol.signer.sign(serializedInnerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction({ + const relayedTransaction = factory.createRelayedV1Transaction(frank.getAddress(), { innerTransaction: innerTransaction, - relayerAddress: frank.address, }); relayedTransaction.nonce = 715n; @@ -119,9 +117,8 @@ describe("test relayed transactions factory", function () { const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); innerTransaction.signature = await carol.signer.sign(serializedInnerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction({ + const relayedTransaction = factory.createRelayedV1Transaction(frank.getAddress(), { innerTransaction: innerTransaction, - relayerAddress: frank.address, }); relayedTransaction.nonce = 715n; @@ -155,9 +152,8 @@ describe("test relayed transactions factory", function () { innerTransaction.signature = await bob.signer.sign(serializedInnerTransaction); innerTransaction.guardianSignature = await grace.signer.sign(serializedInnerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction({ + const relayedTransaction = factory.createRelayedV1Transaction(alice.getAddress(), { innerTransaction: innerTransaction, - relayerAddress: alice.address, }); relayedTransaction.nonce = 2627n; @@ -191,9 +187,8 @@ describe("test relayed transactions factory", function () { innerTransaction.signature = await bob.signer.sign(serializedInnerTransaction); innerTransaction.guardianSignature = await grace.signer.sign(serializedInnerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction({ + const relayedTransaction = factory.createRelayedV1Transaction(alice.getAddress(), { innerTransaction: innerTransaction, - relayerAddress: alice.address, }); relayedTransaction.nonce = 2627n; relayedTransaction.options = 2; @@ -222,10 +217,9 @@ describe("test relayed transactions factory", function () { }); assert.throws(() => { - factory.createRelayedV2Transaction({ + factory.createRelayedV2Transaction(carol.getAddress(), { innerTransaction: innerTransaction, innerTransactionGasLimit: 50000n, - relayerAddress: carol.address, }), "The gas limit should not be set for the inner transaction"; }); @@ -233,10 +227,9 @@ describe("test relayed transactions factory", function () { innerTransaction.gasLimit = 0n; assert.throws(() => { - factory.createRelayedV2Transaction({ + factory.createRelayedV2Transaction(carol.getAddress(), { innerTransaction: innerTransaction, innerTransactionGasLimit: 50000n, - relayerAddress: carol.address, }), "The inner transaction is not signed"; }); @@ -257,10 +250,9 @@ describe("test relayed transactions factory", function () { const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); innerTransaction.signature = await bob.signer.sign(serializedInnerTransaction); - const relayedTransaction = factory.createRelayedV2Transaction({ + const relayedTransaction = factory.createRelayedV2Transaction(alice.getAddress(), { innerTransaction: innerTransaction, innerTransactionGasLimit: 60000000n, - relayerAddress: alice.address, }); relayedTransaction.nonce = 37n; diff --git a/src/relayed/relayedTransactionsFactory.ts b/src/relayed/relayedTransactionsFactory.ts index 13c2a8e6c..52f008536 100644 --- a/src/relayed/relayedTransactionsFactory.ts +++ b/src/relayed/relayedTransactionsFactory.ts @@ -2,7 +2,7 @@ import BigNumber from "bignumber.js"; import { AddressValue, ArgSerializer, BytesValue, U64Value } from "../abi"; import { Address } from "../address"; import { ErrInvalidInnerTransaction } from "../errors"; -import { IAddress, ITransaction } from "../interface"; +import { ITransaction } from "../interface"; import { Transaction } from "../transaction"; const JSONbig = require("json-bigint"); @@ -23,7 +23,7 @@ export class RelayedTransactionsFactory { this.config = options.config; } - createRelayedV1Transaction(options: { innerTransaction: ITransaction; relayerAddress: IAddress }): Transaction { + createRelayedV1Transaction(relayerAddress: Address, options: { innerTransaction: ITransaction }): Transaction { if (!options.innerTransaction.gasLimit) { throw new ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction"); } @@ -40,18 +40,20 @@ export class RelayedTransactionsFactory { return new Transaction({ chainID: this.config.chainID, - sender: options.relayerAddress.bech32(), + sender: relayerAddress.bech32(), receiver: options.innerTransaction.sender, gasLimit: gasLimit, data: Buffer.from(data), }); } - createRelayedV2Transaction(options: { - innerTransaction: ITransaction; - innerTransactionGasLimit: bigint; - relayerAddress: IAddress; - }): Transaction { + createRelayedV2Transaction( + relayerAddress: Address, + options: { + innerTransaction: ITransaction; + innerTransactionGasLimit: bigint; + }, + ): Transaction { if (options.innerTransaction.gasLimit) { throw new ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction"); } @@ -73,7 +75,7 @@ export class RelayedTransactionsFactory { const gasLimit = options.innerTransactionGasLimit + this.config.minGasLimit + additionalGasForDataLength; return new Transaction({ - sender: options.relayerAddress.bech32(), + sender: relayerAddress.bech32(), receiver: options.innerTransaction.sender, value: 0n, gasLimit: gasLimit, From 4751fce512720cdc7ad2765d839a919343a16569 Mon Sep 17 00:00:00 2001 From: danielailie Date: Fri, 15 Nov 2024 12:14:26 +0200 Subject: [PATCH 021/214] Fix integration tests --- src/abi/smartContract.local.net.spec.ts | 38 +++++++++---------------- src/smartContracts/resources.ts | 2 +- 2 files changed, 14 insertions(+), 26 deletions(-) diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 57c5646f8..818cc0349 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -3,12 +3,12 @@ import { promises } from "fs"; import { QueryRunnerAdapter } from "../adapters/queryRunnerAdapter"; import { Logger } from "../logger"; import { SmartContractQueriesController } from "../smartContractQueriesController"; +import { SmartContractTransactionsFactory } from "../smartContracts"; import { prepareDeployment } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { loadTestWallets, TestWallet } from "../testutils/wallets"; import { TransactionComputer } from "../transactionComputer"; import { TransactionsFactoryConfig } from "../transactionsFactories"; -import { SmartContractTransactionsFactory } from "../transactionsFactories/smartContractTransactionsFactory"; import { TransactionWatcher } from "../transactionWatcher"; import { decodeUnsignedNumber } from "./codec"; import { ContractFunction } from "./function"; @@ -129,8 +129,7 @@ describe("test on local testnet", function () { const bytecode = await promises.readFile("src/testdata/counter.wasm"); - const deployTransaction = factory.createTransactionForDeploy({ - sender: alice.address, + const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); @@ -144,8 +143,7 @@ describe("test on local testnet", function () { const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); alice.account.incrementNonce(); - const smartContractCallTransaction = factory.createTransactionForExecute({ - sender: alice.address, + const smartContractCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, @@ -157,8 +155,7 @@ describe("test on local testnet", function () { alice.account.incrementNonce(); - const simulateOne = factory.createTransactionForExecute({ - sender: alice.address, + const simulateOne = factory.createTransactionForExecute(alice.address, { function: "increment", contract: contractAddress, gasLimit: 100000n, @@ -171,8 +168,7 @@ describe("test on local testnet", function () { alice.account.incrementNonce(); - const simulateTwo = factory.createTransactionForExecute({ - sender: alice.address, + const simulateTwo = factory.createTransactionForExecute(alice.address, { function: "foobar", contract: contractAddress, gasLimit: 500000n, @@ -283,8 +279,7 @@ describe("test on local testnet", function () { const bytecode = await promises.readFile("src/testdata/counter.wasm"); - const deployTransaction = factory.createTransactionForDeploy({ - sender: alice.address, + const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); @@ -298,8 +293,7 @@ describe("test on local testnet", function () { const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); alice.account.incrementNonce(); - const firstScCallTransaction = factory.createTransactionForExecute({ - sender: alice.address, + const firstScCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, @@ -311,8 +305,7 @@ describe("test on local testnet", function () { alice.account.incrementNonce(); - const secondScCallTransaction = factory.createTransactionForExecute({ - sender: alice.address, + const secondScCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, @@ -449,8 +442,7 @@ describe("test on local testnet", function () { const bytecode = await promises.readFile("src/testdata/erc20.wasm"); - const deployTransaction = factory.createTransactionForDeploy({ - sender: alice.address, + const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 50000000n, arguments: [new U32Value(10000)], @@ -464,8 +456,7 @@ describe("test on local testnet", function () { const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); alice.account.incrementNonce(); - const transactionMintBob = factory.createTransactionForExecute({ - sender: alice.address, + const transactionMintBob = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "transferToken", gasLimit: 9000000n, @@ -478,8 +469,7 @@ describe("test on local testnet", function () { alice.account.incrementNonce(); - const transactionMintCarol = factory.createTransactionForExecute({ - sender: alice.address, + const transactionMintCarol = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "transferToken", gasLimit: 9000000n, @@ -629,8 +619,7 @@ describe("test on local testnet", function () { const bytecode = await promises.readFile("src/testdata/lottery-esdt.wasm"); - const deployTransaction = factory.createTransactionForDeploy({ - sender: alice.address, + const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 50000000n, }); @@ -644,8 +633,7 @@ describe("test on local testnet", function () { const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); alice.account.incrementNonce(); - const startTransaction = factory.createTransactionForExecute({ - sender: alice.address, + const startTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "start", gasLimit: 10000000n, diff --git a/src/smartContracts/resources.ts b/src/smartContracts/resources.ts index 2b1bc298e..a4cab3eb2 100644 --- a/src/smartContracts/resources.ts +++ b/src/smartContracts/resources.ts @@ -4,7 +4,7 @@ import { TokenTransfer } from "../tokens"; export type ContractDepoyInput = { bytecode: Uint8Array; gasLimit: bigint; - arguments: any[]; + arguments?: any[]; nativeTransferAmount?: bigint; isUpgradeable?: boolean; isReadable?: boolean; From 3881372b0dcc4ee728c9254bcafd04b88c54202c Mon Sep 17 00:00:00 2001 From: danielailie Date: Fri, 15 Nov 2024 12:29:50 +0200 Subject: [PATCH 022/214] Fix integration tests --- src/abi/interaction.local.net.spec.ts | 32 +++++++------------ .../smartContractResults.local.net.spec.ts | 14 ++++---- 2 files changed, 17 insertions(+), 29 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 2f1c286af..2a2487688 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -3,13 +3,13 @@ import { assert } from "chai"; import { promises } from "fs"; import { QueryRunnerAdapter } from "../adapters/queryRunnerAdapter"; import { SmartContractQueriesController } from "../smartContractQueriesController"; +import { SmartContractTransactionsFactory } from "../smartContracts"; import { loadAbiRegistry, loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; import { ContractController } from "../testutils/contractController"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; import { TransactionsFactoryConfig } from "../transactionsFactories"; -import { SmartContractTransactionsFactory } from "../transactionsFactories/smartContractTransactionsFactory"; import { TransactionWatcher } from "../transactionWatcher"; import { Interaction } from "./interaction"; import { ResultsParser } from "./resultsParser"; @@ -102,8 +102,7 @@ describe("test smart contract interactor", function () { const bytecode = await promises.readFile("src/testdata/answer.wasm"); - const deployTransaction = factory.createTransactionForDeploy({ - sender: alice.address, + const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); @@ -144,8 +143,7 @@ describe("test smart contract interactor", function () { assert.deepEqual(parsed[0], new BigNumber(42)); // Query - let transaction = factory.createTransactionForExecute({ - sender: alice.address, + let transaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "getUltimateAnswer", gasLimit: 3000000n, @@ -160,8 +158,7 @@ describe("test smart contract interactor", function () { await provider.sendTransaction(transaction); // Execute, and wait for execution - transaction = factory.createTransactionForExecute({ - sender: alice.address, + transaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "getUltimateAnswer", gasLimit: 3000000n, @@ -393,8 +390,7 @@ describe("test smart contract interactor", function () { const bytecode = await promises.readFile("src/testdata/counter.wasm"); - const deployTransaction = factory.createTransactionForDeploy({ - sender: alice.address, + const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); @@ -422,8 +418,7 @@ describe("test smart contract interactor", function () { const queryRunner = new QueryRunnerAdapter({ networkProvider: provider }); const queryController = new SmartContractQueriesController({ abi: abiRegistry, queryRunner: queryRunner }); - let incrementTransaction = factory.createTransactionForExecute({ - sender: alice.address, + let incrementTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, @@ -451,8 +446,7 @@ describe("test smart contract interactor", function () { let typedBundle = resultsParser.parseOutcome(transactionOnNetwork, abiRegistry.getEndpoint("increment")); assert.deepEqual(typedBundle.firstValue!.valueOf(), new BigNumber(2)); - let decrementTransaction = factory.createTransactionForExecute({ - sender: alice.address, + let decrementTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "decrement", gasLimit: 3000000n, @@ -590,8 +584,7 @@ describe("test smart contract interactor", function () { const bytecode = await promises.readFile("src/testdata/lottery-esdt.wasm"); // Deploy the contract - const deployTransaction = factory.createTransactionForDeploy({ - sender: alice.address, + const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 100000000n, }); @@ -617,8 +610,7 @@ describe("test smart contract interactor", function () { assert.isTrue(untypedBundle.returnCode.isSuccess()); // start() - let startTransaction = factory.createTransactionForExecute({ - sender: alice.address, + let startTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "start", arguments: ["lucky", "EGLD", 1, null, null, 1, null, null], @@ -638,8 +630,7 @@ describe("test smart contract interactor", function () { assert.lengthOf(typedBundle.values, 0); // status() - let lotteryStatusTransaction = factory.createTransactionForExecute({ - sender: alice.address, + let lotteryStatusTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "status", arguments: ["lucky"], @@ -660,8 +651,7 @@ describe("test smart contract interactor", function () { assert.equal(typedBundle.firstValue!.valueOf().name, "Running"); // getlotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) - let lotteryInfoTransaction = factory.createTransactionForExecute({ - sender: alice.address, + let lotteryInfoTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "getLotteryInfo", arguments: ["lucky"], diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 1ad837676..850bd9a35 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -1,14 +1,14 @@ import { assert } from "chai"; +import { promises } from "fs"; +import { SmartContractTransactionsFactory } from "../smartContracts"; import { loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { ContractFunction } from "./function"; import { ResultsParser } from "./resultsParser"; import { SmartContract } from "./smartContract"; -import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; -import { SmartContractTransactionsFactory } from "../transactionsFactories/smartContractTransactionsFactory"; -import { promises } from "fs"; -import { TransactionComputer } from "../transactionComputer"; describe("fetch transactions from local testnet", function () { let alice: TestWallet; @@ -91,8 +91,7 @@ describe("fetch transactions from local testnet", function () { const bytecode = await promises.readFile("src/testdata/counter.wasm"); - const deployTransaction = factory.createTransactionForDeploy({ - sender: alice.address, + const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); @@ -106,8 +105,7 @@ describe("fetch transactions from local testnet", function () { const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); alice.account.incrementNonce(); - const smartContractCallTransaction = factory.createTransactionForExecute({ - sender: alice.address, + const smartContractCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, From 60cc1ed49dd3b7f4ea828d417d66970db4c45c4b Mon Sep 17 00:00:00 2001 From: danielailie Date: Fri, 15 Nov 2024 12:54:44 +0200 Subject: [PATCH 023/214] Add token Management controller --- src/index.ts | 1 + src/interface.ts | 4 +- src/testutils/mockNetworkProvider.ts | 12 +- src/tokenManagement/index.ts | 3 + src/tokenManagement/resources.ts | 113 ++++ .../tokenManagementController.ts | 495 ++++++++++++++++++ ...tokenManagementTransactionFactory.spec.ts} | 120 ++--- .../tokenManagementTransactionsFactory.ts | 366 ++++--------- ...anagementTransactionsOutcomeParser.spec.ts | 7 +- ...okenManagementTransactionsOutcomeParser.ts | 21 +- src/transactionWatcher.spec.ts | 2 +- src/transactionWatcher.ts | 7 +- src/transactionsFactories/index.ts | 1 - src/transactionsOutcomeParsers/index.ts | 2 +- 14 files changed, 808 insertions(+), 346 deletions(-) create mode 100644 src/tokenManagement/index.ts create mode 100644 src/tokenManagement/resources.ts create mode 100644 src/tokenManagement/tokenManagementController.ts rename src/{transactionsFactories/tokenManagementTransactionIntentsFactory.spec.ts => tokenManagement/tokenManagementTransactionFactory.spec.ts} (87%) rename src/{transactionsFactories => tokenManagement}/tokenManagementTransactionsFactory.ts (72%) rename src/{transactionsOutcomeParsers => tokenManagement}/tokenManagementTransactionsOutcomeParser.spec.ts (99%) rename src/{transactionsOutcomeParsers => tokenManagement}/tokenManagementTransactionsOutcomeParser.ts (97%) diff --git a/src/index.ts b/src/index.ts index 87ed40c94..7b89d4c2c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,7 @@ export * from "./relayedTransactionV1Builder"; export * from "./relayedTransactionV2Builder"; export * from "./signableMessage"; export * from "./smartContractQueriesController"; +export * from "./tokenManagement"; export * from "./tokenOperations"; export * from "./tokens"; export * from "./transaction"; diff --git a/src/interface.ts b/src/interface.ts index 97c86a54f..5adf540bd 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -1,11 +1,11 @@ import BigNumber from "bignumber.js"; -import { ITransactionOnNetwork } from "./interfaceOfNetwork"; +import { TransactionOnNetwork } from "./networkProviders"; export interface ITransactionFetcher { /** * Fetches the state of a {@link Transaction}. */ - getTransaction(txHash: string): Promise; + getTransaction(txHash: string): Promise; } export interface IPlainTransactionObject { diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 53276a27b..432f58243 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -20,14 +20,14 @@ export class MockNetworkProvider { static AddressOfBob = new Address("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); static AddressOfCarol = new Address("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"); - private readonly transactions: Map; + private readonly transactions: Map; private nextTransactionTimelinePoints: any[] = []; private readonly accounts: Map; private readonly queryContractResponders: QueryContractResponder[] = []; private readonly getTransactionResponders: GetTransactionResponder[] = []; constructor() { - this.transactions = new Map(); + this.transactions = new Map(); this.accounts = new Map(); this.accounts.set(MockNetworkProvider.AddressOfAlice.bech32(), { @@ -55,7 +55,7 @@ export class MockNetworkProvider { } } - mockPutTransaction(hash: TransactionHash, item: ITransactionOnNetwork) { + mockPutTransaction(hash: TransactionHash, item: TransactionOnNetwork) { item.isCompleted = false; this.transactions.set(hash.toString(), item); } @@ -134,7 +134,7 @@ export class MockNetworkProvider { return {}; } - async getTransaction(txHash: string): Promise { + async getTransaction(txHash: string): Promise { // At first, try to use a mock responder for (const responder of this.getTransactionResponders) { if (responder.matches(txHash)) { @@ -193,9 +193,9 @@ class QueryContractResponder { class GetTransactionResponder { readonly matches: (hash: string) => boolean; - readonly response: ITransactionOnNetwork; + readonly response: TransactionOnNetwork; - constructor(matches: (hash: string) => boolean, response: ITransactionOnNetwork) { + constructor(matches: (hash: string) => boolean, response: TransactionOnNetwork) { this.matches = matches; this.response = response; } diff --git a/src/tokenManagement/index.ts b/src/tokenManagement/index.ts new file mode 100644 index 000000000..c5b0ff043 --- /dev/null +++ b/src/tokenManagement/index.ts @@ -0,0 +1,3 @@ +export * from "./tokenManagementController"; +export * from "./tokenManagementTransactionsFactory"; +export * from "./tokenManagementTransactionsOutcomeParser"; diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts new file mode 100644 index 000000000..32e4ce3c6 --- /dev/null +++ b/src/tokenManagement/resources.ts @@ -0,0 +1,113 @@ +import { IAddress } from "../interface"; + +export type IssueFungibleInput = IssueInput & { initialSupply: bigint; numDecimals: bigint }; + +export type IssueSemiFungibleInput = IssueNonFungibleInput; + +export type IssueNonFungibleInput = IssueInput & { canTransferNFTCreateRole: boolean }; + +export type IssueInput = { + tokenName: string; + tokenTicker: string; + canFreeze: boolean; + canWipe: boolean; + canPause: boolean; + canChangeOwner: boolean; + canUpgrade: boolean; + canAddSpecialRoles: boolean; +}; + +export type FungibleSpecialRoleInput = { + user: IAddress; + tokenIdentifier: string; + addRoleLocalMint: boolean; + addRoleLocalBurn: boolean; + addRoleESDTTransferRole: boolean; +}; +export type SemiFungibleSpecialRoleInput = SpecialRoleInput & { addRoleNFTAddQuantity: boolean }; + +export type SpecialRoleInput = { + user: IAddress; + tokenIdentifier: string; + addRoleNFTCreate: boolean; + addRoleNFTBurn: boolean; + addRoleNFTUpdateAttributes: boolean; + addRoleNFTAddURI: boolean; + addRoleESDTTransferRole: boolean; + addRoleESDTModifyCreator?: boolean; + addRoleNFTRecreate?: boolean; + addRoleESDTSetNewURI?: boolean; + addRoleESDTModifyRoyalties?: boolean; +}; + +export type MintInput = { + tokenIdentifier: string; + initialQuantity: bigint; + name: string; + royalties: number; + hash: string; + attributes: Uint8Array; + uris: string[]; +}; +export type ManagementInput = { user: IAddress; tokenIdentifier: string }; +export type LocalBurnInput = { tokenIdentifier: string; supplyToBurn: bigint }; +export type LocalMintInput = { tokenIdentifier: string; supplyToMint: bigint }; + +export type UpdateAttributesInput = UpdateInput & { attributes: Uint8Array }; + +export type UpdateQuantityInput = UpdateInput & { quantity: bigint }; + +export type UpdateInput = { tokenIdentifier: string; tokenNonce: bigint }; +export type BurnRoleGloballyInput = { tokenIdentifier: string }; + +export type RegisterRolesInput = { + tokenName: string; + tokenTicker: string; + tokenType: TokenType; + numDecimals: bigint; +}; + +export type RegisterMetaESDTInput = { + tokenName: string; + tokenTicker: string; + numDecimals: bigint; + canFreeze: boolean; + canWipe: boolean; + canPause: boolean; + canTransferNFTCreateRole: boolean; + canChangeOwner: boolean; + canUpgrade: boolean; + canAddSpecialRoles: boolean; +}; + +export type ModifyRoyaltiesInput = BaseInput & { newRoyalties: bigint }; + +export type BaseInput = { tokenIdentifier: string; tokenNonce: bigint }; + +export type SetNewUriInput = BaseInput & { newUris: string[] }; + +export type UpdateMetadataInput = { + tokenIdentifier: string; + tokenNonce: bigint; + newTokenName?: string; + newRoyalties?: bigint; + newHash?: string; + newAttributes?: Uint8Array; + newUris?: string[]; +}; + +export type RegisteringDynamicTokenInput = { tokenName: string; tokenTicker: string; tokenType: TokenType }; + +type TokenType = "NFT" | "SFT" | "META" | "FNG"; + +export type SpecialRoleOutput = { + userAddress: string; + tokenIdentifier: string; + roles: string[]; +}; + +export type MintNftOutput = { + tokenIdentifier: string; + nonce: bigint; + initialQuantity: bigint; +}; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts new file mode 100644 index 000000000..a552b895c --- /dev/null +++ b/src/tokenManagement/tokenManagementController.ts @@ -0,0 +1,495 @@ +import { IAccount } from "../accounts/interfaces"; +import { TransactionOnNetwork } from "../networkProviders"; +import { INetworkProvider } from "../networkProviders/interface"; +import { IESDTIssueOutcome } from "../tokenOperations"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TokenManagementTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; +import { TransactionWatcher } from "../transactionWatcher"; +import * as resources from "./resources"; +import { TokenManagementTransactionsFactory } from "./tokenManagementTransactionsFactory"; + +export class TokenManagementController { + private factory: TokenManagementTransactionsFactory; + private transactionAwaiter: TransactionWatcher; + private txComputer: TransactionComputer; + private parser: TokenManagementTransactionsOutcomeParser; + + constructor(options: { chainID: string; networkProvider: INetworkProvider }) { + this.factory = new TokenManagementTransactionsFactory({ + config: new TransactionsFactoryConfig({ chainID: options.chainID }), + }); + this.transactionAwaiter = new TransactionWatcher(options.networkProvider); + this.txComputer = new TransactionComputer(); + this.parser = new TokenManagementTransactionsOutcomeParser(); + } + + async createTransactionForIssuingFungible( + sender: IAccount, + nonce: bigint, + options: resources.IssueFungibleInput, + ): Promise { + const transaction = this.factory.createTransactionForIssuingFungible(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedIssueFungible(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseIssueFungible(transaction); + } + + parseIssueFungible(transactionOnNetwork: TransactionOnNetwork): IESDTIssueOutcome[] { + return this.parser.parseIssueFungible(transactionOnNetwork); + } + + async createTransactionForIssuingSemiFungible( + sender: IAccount, + nonce: bigint, + options: resources.IssueSemiFungibleInput, + ): Promise { + const transaction = this.factory.createTransactionForIssuingSemiFungible(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedIssueSemiFungible(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseIssueSemiFungible(transaction); + } + + parseIssueSemiFungible(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseIssueSemiFungible(transactionOnNetwork); + } + + async createTransactionForIssuingNonFungible( + sender: IAccount, + nonce: bigint, + options: resources.IssueNonFungibleInput, + ): Promise { + const transaction = this.factory.createTransactionForIssuingNonFungible(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedIssueNonFungible(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseIssueNonFungible(transaction); + } + + parseIssueNonFungible(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseIssueNonFungible(transactionOnNetwork); + } + + async createTransactionForRegisteringMetaEsdt( + sender: IAccount, + nonce: bigint, + options: resources.RegisterMetaESDTInput, + ): Promise { + const transaction = this.factory.createTransactionForRegisteringMetaESDT(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedRegisterMetaEsdt(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseRegisterMetaEsdt(transaction); + } + + parseRegisterMetaEsdt(transactionOnNetwork: TransactionOnNetwork): IESDTIssueOutcome[] { + return this.parser.parseRegisterMetaEsdt(transactionOnNetwork); + } + + async createTransactionForRegisteringAndSettingRoles( + sender: IAccount, + nonce: bigint, + options: resources.RegisterRolesInput, + ): Promise { + const transaction = this.factory.createTransactionForRegisteringAndSettingRoles(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedRegisterAndSettingRoles(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseRegisterAndSetAllRoles(transaction); + } + + parseRegisterAndSetAllRoles(transactionOnNetwork: TransactionOnNetwork): IESDTIssueOutcome[] { + return this.parser.parseRegisterMetaEsdt(transactionOnNetwork); + } + + async createTransactionForSetBurnRoleGlobally( + sender: IAccount, + nonce: bigint, + options: resources.BurnRoleGloballyInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingBurnRoleGlobally(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedSetBurnRoleGlobally(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseSetBurnRoleGlobally(transaction); + } + + parseSetBurnRoleGlobally(transactionOnNetwork: TransactionOnNetwork): void { + return this.parser.parseSetBurnRoleGlobally(transactionOnNetwork); + } + + async createTransactionForUnsettingBurnRoleGlobally( + sender: IAccount, + nonce: bigint, + options: resources.BurnRoleGloballyInput, + ): Promise { + const transaction = this.factory.createTransactionForUnsettingBurnRoleGlobally(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedUnsetBurnRoleGlobally(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseUnsetBurnRoleGlobally(transaction); + } + + parseUnsetBurnRoleGlobally(transactionOnNetwork: TransactionOnNetwork): void { + return this.parser.parseUnsetBurnRoleGlobally(transactionOnNetwork); + } + + async createTransactionForSettingSpecialRoleOnFungibleToken( + sender: IAccount, + nonce: bigint, + options: resources.FungibleSpecialRoleInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingSpecialRoleOnFungibleToken(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedSetSpecialRoleOnFungibleToken(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseSetSpecialRoleOnFungible(transaction); + } + + parseSetSpecialRoleOnFungible(transactionOnNetwork: TransactionOnNetwork): resources.SpecialRoleOutput[] { + return this.parser.parseSetSpecialRole(transactionOnNetwork); + } + + async createTransactionForSettingSpecialRoleOnSemiFungibleToken( + sender: IAccount, + nonce: bigint, + options: resources.SemiFungibleSpecialRoleInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingSpecialRoleOnSemiFungibleToken( + sender.address, + options, + ); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedSetSpecialRoleOnSemiFungibleToken(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseSetSpecialRoleOnSemiFungibleToken(transaction); + } + + parseSetSpecialRoleOnSemiFungibleToken(transactionOnNetwork: TransactionOnNetwork): resources.SpecialRoleOutput[] { + return this.parser.parseSetSpecialRole(transactionOnNetwork); + } + + async createTransactionForSettingSpecialRoleOnNonFungibleToken( + sender: IAccount, + nonce: bigint, + options: resources.SpecialRoleInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingSpecialRoleOnNonFungibleToken( + sender.address, + options, + ); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedSetSpecialRoleOnNonFungibleToken(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseSetSpecialRoleOnNonFungibleToken(transaction); + } + + parseSetSpecialRoleOnNonFungibleToken(transactionOnNetwork: TransactionOnNetwork): resources.SpecialRoleOutput[] { + return this.parser.parseSetSpecialRole(transactionOnNetwork); + } + + async createTransactionForCreatingNft( + sender: IAccount, + nonce: bigint, + options: resources.MintInput, + ): Promise { + const transaction = this.factory.createTransactionForCreatingNFT(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedCreateNft(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseNftCreate(transaction); + } + + parseNftCreate(transactionOnNetwork: TransactionOnNetwork): resources.MintNftOutput[] { + return this.parser.parseNftCreate(transactionOnNetwork); + } + + async createTransactionForPausing( + sender: IAccount, + nonce: bigint, + options: resources.ManagementInput, + ): Promise { + const transaction = this.factory.createTransactionForPausing(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedPause(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parsePause(transaction); + } + + parsePause(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parsePause(transactionOnNetwork); + } + + async createTransactionForUnpausing( + sender: IAccount, + nonce: bigint, + options: resources.ManagementInput, + ): Promise { + const transaction = this.factory.createTransactionForUnpausing(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedUnpause(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseUnpause(transaction); + } + + parseUnpause(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseUnpause(transactionOnNetwork); + } + + async createTransactionForFreezing( + sender: IAccount, + nonce: bigint, + options: resources.ManagementInput, + ): Promise { + const transaction = this.factory.createTransactionForFreezing(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedFreeze(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseFreeze(transaction); + } + + parseFreeze(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseFreeze(transactionOnNetwork); + } + + async createTransactionForUnFreezing( + sender: IAccount, + nonce: bigint, + options: resources.ManagementInput, + ): Promise { + const transaction = this.factory.createTransactionForUnfreezing(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedUnfreeze(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseUnfreeze(transaction); + } + + parseUnfreeze(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseUnfreeze(transactionOnNetwork); + } + + async createTransactionForWiping( + sender: IAccount, + nonce: bigint, + options: resources.ManagementInput, + ): Promise { + const transaction = this.factory.createTransactionForWiping(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedWipe(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parser.parseWipe(transaction); + } + + parseWipe(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseWipe(transactionOnNetwork); + } + + async createTransactionForLocaMinting( + sender: IAccount, + nonce: bigint, + options: resources.LocalMintInput, + ): Promise { + const transaction = this.factory.createTransactionForLocalMint(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedLocalMint(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseLocalMint(transaction); + } + + parseLocalMint(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseLocalMint(transactionOnNetwork); + } + + async createTransactionForLocalBurning( + sender: IAccount, + nonce: bigint, + options: resources.LocalBurnInput, + ): Promise { + const transaction = this.factory.createTransactionForLocalBurning(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompleteLocalBurn(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseLocalBurn(transaction); + } + + parseLocalBurn(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseLocalBurn(transactionOnNetwork); + } + + async createTransactionForUpdatingAttributes( + sender: IAccount, + nonce: bigint, + options: resources.UpdateAttributesInput, + ): Promise { + const transaction = this.factory.createTransactionForUpdatingAttributes(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedUpdateAttributes(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseUpdateAttributes(transaction); + } + + parseUpdateAttributes(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseUpdateAttributes(transactionOnNetwork); + } + + async createTransactionForAddingQuantity( + sender: IAccount, + nonce: bigint, + options: resources.UpdateQuantityInput, + ): Promise { + const transaction = this.factory.createTransactionForAddingQuantity(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedAddQuantity(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseAddQuantity(transaction); + } + + parseAddQuantity(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseAddQuantity(transactionOnNetwork); + } + + async createTransactionForBurningQuantity( + sender: IAccount, + nonce: bigint, + options: resources.UpdateQuantityInput, + ): Promise { + const transaction = this.factory.createTransactionForBurningQuantity(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedBurnQuantity(txHash: string): Promise<{ tokenIdentifier: string }[]> { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseBurnQuantity(transaction); + } + + parseBurnQuantity(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + return this.parser.parseBurnQuantity(transactionOnNetwork); + } +} diff --git a/src/transactionsFactories/tokenManagementTransactionIntentsFactory.spec.ts b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts similarity index 87% rename from src/transactionsFactories/tokenManagementTransactionIntentsFactory.spec.ts rename to src/tokenManagement/tokenManagementTransactionFactory.spec.ts index f5c489903..2c2d432cc 100644 --- a/src/transactionsFactories/tokenManagementTransactionIntentsFactory.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts @@ -2,8 +2,8 @@ import { assert } from "chai"; import { Address } from "../address"; import { ESDT_CONTRACT_ADDRESS_HEX } from "../constants"; import { loadTestWallets, TestWallet } from "../testutils"; +import { TransactionsFactoryConfig } from "../transactionsFactories"; import { TokenManagementTransactionsFactory } from "./tokenManagementTransactionsFactory"; -import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; describe("test token management transactions factory", () => { let frank: TestWallet, grace: TestWallet; @@ -17,8 +17,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for registering and setting roles", () => { - const transaction = tokenManagementFactory.createTransactionForRegisteringAndSettingRoles({ - sender: frank.address, + const transaction = tokenManagementFactory.createTransactionForRegisteringAndSettingRoles(frank.address, { tokenName: "TEST", tokenTicker: "TEST", tokenType: "FNG", @@ -33,8 +32,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for issuing fungible token", () => { - const transaction = tokenManagementFactory.createTransactionForIssuingFungible({ - sender: frank.address, + const transaction = tokenManagementFactory.createTransactionForIssuingFungible(frank.address, { tokenName: "FRANK", tokenTicker: "FRANK", initialSupply: 100n, @@ -59,8 +57,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for issuing semi-fungible token", () => { - const transaction = tokenManagementFactory.createTransactionForIssuingSemiFungible({ - sender: frank.address, + const transaction = tokenManagementFactory.createTransactionForIssuingSemiFungible(frank.address, { tokenName: "FRANK", tokenTicker: "FRANK", canFreeze: true, @@ -84,8 +81,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for issuing non-fungible token", () => { - const transaction = tokenManagementFactory.createTransactionForIssuingNonFungible({ - sender: frank.address, + const transaction = tokenManagementFactory.createTransactionForIssuingNonFungible(frank.address, { tokenName: "FRANK", tokenTicker: "FRANK", canFreeze: true, @@ -109,8 +105,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for registering metaEsdt", () => { - const transaction = tokenManagementFactory.createTransactionForRegisteringMetaESDT({ - sender: frank.address, + const transaction = tokenManagementFactory.createTransactionForRegisteringMetaESDT(frank.address, { tokenName: "FRANK", tokenTicker: "FRANK", numDecimals: 10n, @@ -135,14 +130,16 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for setting special role on fungible token", () => { - const transaction = tokenManagementFactory.createTransactionForSettingSpecialRoleOnFungibleToken({ - sender: frank.address, - user: grace.address, - tokenIdentifier: "FRANK-11ce3e", - addRoleLocalMint: true, - addRoleLocalBurn: false, - addRoleESDTTransferRole: false, - }); + const transaction = tokenManagementFactory.createTransactionForSettingSpecialRoleOnFungibleToken( + frank.address, + { + user: grace.address, + tokenIdentifier: "FRANK-11ce3e", + addRoleLocalMint: true, + addRoleLocalBurn: false, + addRoleESDTTransferRole: false, + }, + ); assert.deepEqual( transaction.data, @@ -156,14 +153,16 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for setting all special roles on fungible token", () => { - const transaction = tokenManagementFactory.createTransactionForSettingSpecialRoleOnFungibleToken({ - sender: frank.address, - user: grace.address, - tokenIdentifier: "FRANK-11ce3e", - addRoleLocalMint: true, - addRoleLocalBurn: true, - addRoleESDTTransferRole: true, - }); + const transaction = tokenManagementFactory.createTransactionForSettingSpecialRoleOnFungibleToken( + frank.address, + { + user: grace.address, + tokenIdentifier: "FRANK-11ce3e", + addRoleLocalMint: true, + addRoleLocalBurn: true, + addRoleESDTTransferRole: true, + }, + ); assert.deepEqual( transaction.data, @@ -177,18 +176,20 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for setting special role on non-fungible token", () => { - const transaction = tokenManagementFactory.createTransactionForSettingSpecialRoleOnNonFungibleToken({ - sender: frank.address, - user: grace.address, - tokenIdentifier: "FRANK-11ce3e", - addRoleNFTCreate: true, - addRoleNFTBurn: false, - addRoleNFTUpdateAttributes: true, - addRoleNFTAddURI: true, - addRoleESDTTransferRole: false, - addRoleESDTModifyCreator: true, - addRoleNFTRecreate: true, - }); + const transaction = tokenManagementFactory.createTransactionForSettingSpecialRoleOnNonFungibleToken( + frank.address, + { + user: grace.address, + tokenIdentifier: "FRANK-11ce3e", + addRoleNFTCreate: true, + addRoleNFTBurn: false, + addRoleNFTUpdateAttributes: true, + addRoleNFTAddURI: true, + addRoleESDTTransferRole: false, + addRoleESDTModifyCreator: true, + addRoleNFTRecreate: true, + }, + ); assert.deepEqual( transaction.data, @@ -202,8 +203,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for creating nft", () => { - const transaction = tokenManagementFactory.createTransactionForCreatingNFT({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForCreatingNFT(grace.address, { tokenIdentifier: "FRANK-aa9e8d", initialQuantity: 1n, name: "test", @@ -223,8 +223,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for modifying royalties", () => { - const transaction = tokenManagementFactory.createTransactionForModifyingRoyalties({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForModifyingRoyalties(grace.address, { tokenIdentifier: "TEST-123456", tokenNonce: 1n, newRoyalties: 1234n, @@ -238,8 +237,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for setting new URIs", () => { - const transaction = tokenManagementFactory.createTransactionForSettingNewUris({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForSettingNewUris(grace.address, { tokenIdentifier: "TEST-123456", tokenNonce: 1n, newUris: ["firstURI", "secondURI"], @@ -256,8 +254,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for modifying creator", () => { - const transaction = tokenManagementFactory.createTransactionForModifyingCreator({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForModifyingCreator(grace.address, { tokenIdentifier: "TEST-123456", tokenNonce: 1n, }); @@ -270,8 +267,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for updating metadata", () => { - const transaction = tokenManagementFactory.createTransactionForUpdatingMetadata({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForUpdatingMetadata(grace.address, { tokenIdentifier: "TEST-123456", tokenNonce: 1n, newTokenName: "Test", @@ -294,8 +290,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for recreating metadata", () => { - const transaction = tokenManagementFactory.createTransactionForMetadataRecreate({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForMetadataRecreate(grace.address, { tokenIdentifier: "TEST-123456", tokenNonce: 1n, newTokenName: "Test", @@ -318,8 +313,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for changing to dynamic", () => { - const transaction = tokenManagementFactory.createTransactionForChangingTokenToDynamic({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForChangingTokenToDynamic(grace.address, { tokenIdentifier: "TEST-123456", }); @@ -331,8 +325,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for updating token id", () => { - const transaction = tokenManagementFactory.createTransactionForUpdatingTokenId({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForUpdatingTokenId(grace.address, { tokenIdentifier: "TEST-123456", }); @@ -344,8 +337,7 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for registering dynamic", () => { - const transaction = tokenManagementFactory.createTransactionForRegisteringDynamicToken({ - sender: grace.address, + const transaction = tokenManagementFactory.createTransactionForRegisteringDynamicToken(grace.address, { tokenName: "Test", tokenTicker: "TEST-123456", tokenType: "FNG", @@ -359,12 +351,14 @@ describe("test token management transactions factory", () => { }); it("should create 'Transaction' for registering and setting all roles", () => { - const transaction = tokenManagementFactory.createTransactionForRegisteringDynamicAndSettingRoles({ - sender: grace.address, - tokenName: "Test", - tokenTicker: "TEST-123456", - tokenType: "FNG", - }); + const transaction = tokenManagementFactory.createTransactionForRegisteringDynamicAndSettingRoles( + grace.address, + { + tokenName: "Test", + tokenTicker: "TEST-123456", + tokenType: "FNG", + }, + ); assert.deepEqual( transaction.data, diff --git a/src/transactionsFactories/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts similarity index 72% rename from src/transactionsFactories/tokenManagementTransactionsFactory.ts rename to src/tokenManagement/tokenManagementTransactionsFactory.ts index eff2cdf69..2388a2df1 100644 --- a/src/transactionsFactories/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -5,7 +5,8 @@ import { ErrBadUsage } from "../errors"; import { IAddress } from "../interface"; import { Logger } from "../logger"; import { Transaction } from "../transaction"; -import { TransactionBuilder } from "./transactionBuilder"; +import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; +import * as resources from "./resources"; interface IConfig { chainID: string; @@ -36,8 +37,6 @@ interface IConfig { issueCost: bigint; } -type TokenType = "NFT" | "SFT" | "META" | "FNG"; - /** * Use this class to create token management transactions like issuing ESDTs, creating NFTs, setting roles, etc. */ @@ -56,19 +55,7 @@ export class TokenManagementTransactionsFactory { this.esdtContractAddress = Address.fromHex(ESDT_CONTRACT_ADDRESS_HEX, this.config.addressHrp); } - createTransactionForIssuingFungible(options: { - sender: IAddress; - tokenName: string; - tokenTicker: string; - initialSupply: bigint; - numDecimals: bigint; - canFreeze: boolean; - canWipe: boolean; - canPause: boolean; - canChangeOwner: boolean; - canUpgrade: boolean; - canAddSpecialRoles: boolean; - }): Transaction { + createTransactionForIssuingFungible(sender: IAddress, options: resources.IssueFungibleInput): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const args = [ @@ -94,7 +81,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitIssue, @@ -103,18 +90,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForIssuingSemiFungible(options: { - sender: IAddress; - tokenName: string; - tokenTicker: string; - canFreeze: boolean; - canWipe: boolean; - canPause: boolean; - canTransferNFTCreateRole: boolean; - canChangeOwner: boolean; - canUpgrade: boolean; - canAddSpecialRoles: boolean; - }): Transaction { + createTransactionForIssuingSemiFungible(sender: IAddress, options: resources.IssueSemiFungibleInput): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const args = [ @@ -140,7 +116,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitIssue, @@ -149,18 +125,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForIssuingNonFungible(options: { - sender: IAddress; - tokenName: string; - tokenTicker: string; - canFreeze: boolean; - canWipe: boolean; - canPause: boolean; - canTransferNFTCreateRole: boolean; - canChangeOwner: boolean; - canUpgrade: boolean; - canAddSpecialRoles: boolean; - }): Transaction { + createTransactionForIssuingNonFungible(sender: IAddress, options: resources.IssueNonFungibleInput): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const args = [ @@ -186,7 +151,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitIssue, @@ -195,19 +160,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForRegisteringMetaESDT(options: { - sender: IAddress; - tokenName: string; - tokenTicker: string; - numDecimals: bigint; - canFreeze: boolean; - canWipe: boolean; - canPause: boolean; - canTransferNFTCreateRole: boolean; - canChangeOwner: boolean; - canUpgrade: boolean; - canAddSpecialRoles: boolean; - }): Transaction { + createTransactionForRegisteringMetaESDT(sender: IAddress, options: resources.RegisterMetaESDTInput): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const args = [ @@ -234,7 +187,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitIssue, @@ -243,13 +196,10 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForRegisteringAndSettingRoles(options: { - sender: IAddress; - tokenName: string; - tokenTicker: string; - tokenType: TokenType; - numDecimals: bigint; - }): Transaction { + createTransactionForRegisteringAndSettingRoles( + sender: IAddress, + options: resources.RegisterRolesInput, + ): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const dataParts = [ @@ -264,7 +214,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitIssue, @@ -273,7 +223,10 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForSettingBurnRoleGlobally(options: { sender: IAddress; tokenIdentifier: string }): Transaction { + createTransactionForSettingBurnRoleGlobally( + sender: IAddress, + options: resources.BurnRoleGloballyInput, + ): Transaction { const dataParts = [ "setBurnRoleGlobally", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), @@ -281,7 +234,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitToggleBurnRoleGlobally, @@ -289,7 +242,10 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUnsettingBurnRoleGlobally(options: { sender: IAddress; tokenIdentifier: string }): Transaction { + createTransactionForUnsettingBurnRoleGlobally( + sender: IAddress, + options: resources.BurnRoleGloballyInput, + ): Transaction { const dataParts = [ "unsetBurnRoleGlobally", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), @@ -297,7 +253,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitToggleBurnRoleGlobally, @@ -305,14 +261,10 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForSettingSpecialRoleOnFungibleToken(options: { - sender: IAddress; - user: IAddress; - tokenIdentifier: string; - addRoleLocalMint: boolean; - addRoleLocalBurn: boolean; - addRoleESDTTransferRole: boolean; - }): Transaction { + createTransactionForSettingSpecialRoleOnFungibleToken( + sender: IAddress, + options: resources.FungibleSpecialRoleInput, + ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; options.addRoleLocalMint ? args.push(new StringValue("ESDTRoleLocalMint")) : 0; @@ -323,7 +275,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitSetSpecialRole, @@ -331,16 +283,10 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForSettingSpecialRoleOnSemiFungibleToken(options: { - sender: IAddress; - user: IAddress; - tokenIdentifier: string; - addRoleNFTCreate: boolean; - addRoleNFTBurn: boolean; - addRoleNFTAddQuantity: boolean; - addRoleESDTTransferRole: boolean; - addRoleESDTModifyCreator?: boolean; - }): Transaction { + createTransactionForSettingSpecialRoleOnSemiFungibleToken( + sender: IAddress, + options: resources.SemiFungibleSpecialRoleInput, + ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; options.addRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; @@ -353,7 +299,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitSetSpecialRole, @@ -361,32 +307,17 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForSettingSpecialRoleOnMetaESDT(options: { - sender: IAddress; - user: IAddress; - tokenIdentifier: string; - addRoleNFTCreate: boolean; - addRoleNFTBurn: boolean; - addRoleNFTAddQuantity: boolean; - addRoleESDTTransferRole: boolean; - }): Transaction { - return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(options); - } - - createTransactionForSettingSpecialRoleOnNonFungibleToken(options: { - sender: IAddress; - user: IAddress; - tokenIdentifier: string; - addRoleNFTCreate: boolean; - addRoleNFTBurn: boolean; - addRoleNFTUpdateAttributes: boolean; - addRoleNFTAddURI: boolean; - addRoleESDTTransferRole: boolean; - addRoleESDTModifyCreator?: boolean; - addRoleNFTRecreate?: boolean; - addRoleESDTSetNewURI?: boolean; - addRoleESDTModifyRoyalties?: boolean; - }): Transaction { + createTransactionForSettingSpecialRoleOnMetaESDT( + sender: IAddress, + options: resources.SemiFungibleSpecialRoleInput, + ): Transaction { + return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(sender, options); + } + + createTransactionForSettingSpecialRoleOnNonFungibleToken( + sender: IAddress, + options: resources.SpecialRoleInput, + ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; options.addRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; @@ -403,7 +334,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitSetSpecialRole, @@ -411,16 +342,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForCreatingNFT(options: { - sender: IAddress; - tokenIdentifier: string; - initialQuantity: bigint; - name: string; - royalties: number; - hash: string; - attributes: Uint8Array; - uris: string[]; - }): Transaction { + createTransactionForCreatingNFT(sender: IAddress, options: resources.MintInput): Transaction { const dataParts = [ "ESDTNFTCreate", ...this.argSerializer.valuesToStrings([ @@ -440,28 +362,28 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtNftCreate + storageGasLimit, addDataMovementGas: true, }).build(); } - createTransactionForPausing(options: { sender: IAddress; tokenIdentifier: string }): Transaction { + createTransactionForPausing(sender: IAddress, options: resources.ManagementInput): Transaction { const dataParts = ["pause", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)])]; return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitPausing, addDataMovementGas: true, }).build(); } - createTransactionForUnpausing(options: { sender: IAddress; tokenIdentifier: string }): Transaction { + createTransactionForUnpausing(sender: IAddress, options: resources.ManagementInput): Transaction { const dataParts = [ "unPause", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), @@ -469,15 +391,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitPausing, addDataMovementGas: true, }).build(); } - createTransactionForFreezing(options: { sender: IAddress; user: IAddress; tokenIdentifier: string }): Transaction { + createTransactionForFreezing(sender: IAddress, options: resources.ManagementInput): Transaction { const dataParts = [ "freeze", ...this.argSerializer.valuesToStrings([ @@ -488,19 +410,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitFreezing, addDataMovementGas: true, }).build(); } - createTransactionForUnfreezing(options: { - sender: IAddress; - user: IAddress; - tokenIdentifier: string; - }): Transaction { + createTransactionForUnfreezing(sender: IAddress, options: resources.ManagementInput): Transaction { const dataParts = [ "UnFreeze", ...this.argSerializer.valuesToStrings([ @@ -511,15 +429,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitFreezing, addDataMovementGas: true, }).build(); } - createTransactionForWiping(options: { sender: IAddress; user: IAddress; tokenIdentifier: string }): Transaction { + createTransactionForWiping(sender: IAddress, options: resources.ManagementInput): Transaction { const dataParts = [ "wipe", ...this.argSerializer.valuesToStrings([ @@ -530,19 +448,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitWiping, addDataMovementGas: true, }).build(); } - createTransactionForLocalMint(options: { - sender: IAddress; - tokenIdentifier: string; - supplyToMint: bigint; - }): Transaction { + createTransactionForLocalMint(sender: IAddress, options: resources.LocalMintInput): Transaction { const dataParts = [ "ESDTLocalMint", ...this.argSerializer.valuesToStrings([ @@ -553,19 +467,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtLocalMint, addDataMovementGas: true, }).build(); } - createTransactionForLocalBurning(options: { - sender: IAddress; - tokenIdentifier: string; - supplyToBurn: bigint; - }): Transaction { + createTransactionForLocalBurning(sender: IAddress, options: resources.LocalBurnInput): Transaction { const dataParts = [ "ESDTLocalBurn", ...this.argSerializer.valuesToStrings([ @@ -576,20 +486,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtLocalBurn, addDataMovementGas: true, }).build(); } - createTransactionForUpdatingAttributes(options: { - sender: IAddress; - tokenIdentifier: string; - tokenNonce: bigint; - attributes: Uint8Array; - }): Transaction { + createTransactionForUpdatingAttributes(sender: IAddress, options: resources.UpdateAttributesInput): Transaction { const dataParts = [ "ESDTNFTUpdateAttributes", ...this.argSerializer.valuesToStrings([ @@ -601,70 +506,55 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtNftUpdateAttributes, addDataMovementGas: true, }).build(); } - createTransactionForAddingQuantity(options: { - sender: IAddress; - tokenIdentifier: string; - tokenNonce: bigint; - quantityToAdd: bigint; - }): Transaction { + createTransactionForAddingQuantity(sender: IAddress, options: resources.UpdateQuantityInput): Transaction { const dataParts = [ "ESDTNFTAddQuantity", ...this.argSerializer.valuesToStrings([ new StringValue(options.tokenIdentifier), new BigUIntValue(options.tokenNonce), - new BigUIntValue(options.quantityToAdd), + new BigUIntValue(options.quantity), ]), ]; return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtNftAddQuantity, addDataMovementGas: true, }).build(); } - createTransactionForBurningQuantity(options: { - sender: IAddress; - tokenIdentifier: string; - tokenNonce: bigint; - quantityToBurn: bigint; - }): Transaction { + createTransactionForBurningQuantity(sender: IAddress, options: resources.UpdateQuantityInput): Transaction { const dataParts = [ "ESDTNFTBurn", ...this.argSerializer.valuesToStrings([ new StringValue(options.tokenIdentifier), new BigUIntValue(options.tokenNonce), - new BigUIntValue(options.quantityToBurn), + new BigUIntValue(options.quantity), ]), ]; return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtNftBurn, addDataMovementGas: true, }).build(); } - createTransactionForModifyingRoyalties(options: { - sender: IAddress; - tokenIdentifier: string; - tokenNonce: bigint; - newRoyalties: bigint; - }): Transaction { + createTransactionForModifyingRoyalties(sender: IAddress, options: resources.ModifyRoyaltiesInput): Transaction { const dataParts = [ "ESDTModifyRoyalties", ...this.argSerializer.valuesToStrings([ @@ -676,20 +566,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtModifyRoyalties, addDataMovementGas: true, }).build(); } - createTransactionForSettingNewUris(options: { - sender: IAddress; - tokenIdentifier: string; - tokenNonce: bigint; - newUris: string[]; - }): Transaction { + createTransactionForSettingNewUris(sender: IAddress, options: resources.SetNewUriInput): Transaction { if (!options.newUris.length) { throw new ErrBadUsage("No URIs provided"); } @@ -705,19 +590,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitSetNewUris, addDataMovementGas: true, }).build(); } - createTransactionForModifyingCreator(options: { - sender: IAddress; - tokenIdentifier: string; - tokenNonce: bigint; - }): Transaction { + createTransactionForModifyingCreator(sender: IAddress, options: resources.BaseInput): Transaction { const dataParts = [ "ESDTModifyCreator", ...this.argSerializer.valuesToStrings([ @@ -728,24 +609,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtModifyCreator, addDataMovementGas: true, }).build(); } - createTransactionForUpdatingMetadata(options: { - sender: IAddress; - tokenIdentifier: string; - tokenNonce: bigint; - newTokenName?: string; - newRoyalties?: bigint; - newHash?: string; - newAttributes?: Uint8Array; - newUris?: string[]; - }): Transaction { + createTransactionForUpdatingMetadata(sender: IAddress, options: resources.UpdateMetadataInput): Transaction { const dataParts = [ "ESDTMetaDataUpdate", ...this.argSerializer.valuesToStrings([ @@ -761,24 +633,15 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitEsdtMetadataUpdate, addDataMovementGas: true, }).build(); } - createTransactionForMetadataRecreate(options: { - sender: IAddress; - tokenIdentifier: string; - tokenNonce: bigint; - newTokenName: string; - newRoyalties: bigint; - newHash: string; - newAttributes: Uint8Array; - newUris: string[]; - }): Transaction { + createTransactionForMetadataRecreate(sender: IAddress, options: resources.UpdateMetadataInput): Transaction { const dataParts = [ "ESDTMetaDataRecreate", ...this.argSerializer.valuesToStrings([ @@ -794,15 +657,18 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: this.config.gasLimitNftMetadataRecreate, addDataMovementGas: true, }).build(); } - createTransactionForChangingTokenToDynamic(options: { sender: IAddress; tokenIdentifier: string }): Transaction { + createTransactionForChangingTokenToDynamic( + sender: IAddress, + options: resources.BurnRoleGloballyInput, + ): Transaction { const dataParts = [ "changeToDynamic", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), @@ -810,7 +676,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitNftChangeToDynamic, @@ -818,7 +684,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUpdatingTokenId(options: { sender: IAddress; tokenIdentifier: string }): Transaction { + createTransactionForUpdatingTokenId(sender: IAddress, options: resources.BurnRoleGloballyInput): Transaction { const dataParts = [ "updateTokenID", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), @@ -826,7 +692,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitUpdateTokenId, @@ -834,12 +700,10 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForRegisteringDynamicToken(options: { - sender: IAddress; - tokenName: string; - tokenTicker: string; - tokenType: TokenType; - }): Transaction { + createTransactionForRegisteringDynamicToken( + sender: IAddress, + options: resources.RegisteringDynamicTokenInput, + ): Transaction { const dataParts = [ "registerDynamic", ...this.argSerializer.valuesToStrings([ @@ -851,7 +715,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitRegisterDynamic, @@ -860,12 +724,10 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForRegisteringDynamicAndSettingRoles(options: { - sender: IAddress; - tokenName: string; - tokenTicker: string; - tokenType: TokenType; - }): Transaction { + createTransactionForRegisteringDynamicAndSettingRoles( + sender: IAddress, + options: resources.RegisteringDynamicTokenInput, + ): Transaction { const dataParts = [ "registerAndSetAllRolesDynamic", ...this.argSerializer.valuesToStrings([ @@ -877,7 +739,7 @@ export class TokenManagementTransactionsFactory { return new TransactionBuilder({ config: this.config, - sender: options.sender, + sender: sender, receiver: this.esdtContractAddress, dataParts: dataParts, gasLimit: this.config.gasLimitRegisterDynamic, diff --git a/src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.spec.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts similarity index 99% rename from src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.spec.ts rename to src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts index 136fe6d5b..4bb1a9a37 100644 --- a/src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts @@ -1,7 +1,12 @@ import { assert } from "chai"; import { ErrParseTransactionOutcome } from "../errors"; import { b64TopicsToBytes } from "../testutils"; -import { SmartContractResult, TransactionEvent, TransactionLogs, TransactionOutcome } from "./resources"; +import { + SmartContractResult, + TransactionEvent, + TransactionLogs, + TransactionOutcome, +} from "../transactionsOutcomeParsers/resources"; import { TokenManagementTransactionsOutcomeParser } from "./tokenManagementTransactionsOutcomeParser"; describe("test token management transactions outcome parser", () => { diff --git a/src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts similarity index 97% rename from src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.ts rename to src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index 43345ddc2..1c6696f51 100644 --- a/src/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -3,7 +3,8 @@ import { Address } from "../address"; import { TransactionsConverter } from "../converters/transactionsConverter"; import { ErrParseTransactionOutcome } from "../errors"; import { ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { TransactionEvent, TransactionOutcome, findEventsByIdentifier } from "./resources"; +import { TransactionEvent, TransactionOutcome, findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; +import { MintNftOutput, SpecialRoleOutput } from "./resources"; export class TokenManagementTransactionsOutcomeParser { constructor() {} @@ -79,11 +80,7 @@ export class TokenManagementTransactionsOutcomeParser { this.ensureNoError(transaction.logs.events); } - parseSetSpecialRole(transaction: TransactionOutcome | ITransactionOnNetwork): { - userAddress: string; - tokenIdentifier: string; - roles: string[]; - }[] { + parseSetSpecialRole(transaction: TransactionOutcome | ITransactionOnNetwork): SpecialRoleOutput[] { transaction = this.ensureTransactionOutcome(transaction); this.ensureNoError(transaction.logs.events); @@ -92,11 +89,7 @@ export class TokenManagementTransactionsOutcomeParser { return events.map((event) => this.getOutputForSetSpecialRoleEvent(event)); } - private getOutputForSetSpecialRoleEvent(event: TransactionEvent): { - userAddress: string; - tokenIdentifier: string; - roles: string[]; - } { + private getOutputForSetSpecialRoleEvent(event: TransactionEvent): SpecialRoleOutput { const userAddress = event.address; const tokenIdentifier = this.extractTokenIdentifier(event); const encodedRoles = event.topics.slice(3); @@ -105,11 +98,7 @@ export class TokenManagementTransactionsOutcomeParser { return { userAddress: userAddress, tokenIdentifier: tokenIdentifier, roles: roles }; } - parseNftCreate(transaction: TransactionOutcome | ITransactionOnNetwork): { - tokenIdentifier: string; - nonce: bigint; - initialQuantity: bigint; - }[] { + parseNftCreate(transaction: TransactionOutcome | ITransactionOnNetwork): MintNftOutput[] { transaction = this.ensureTransactionOutcome(transaction); this.ensureNoError(transaction.logs.events); diff --git a/src/transactionWatcher.spec.ts b/src/transactionWatcher.spec.ts index dd223af6d..018313440 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/transactionWatcher.spec.ts @@ -1,5 +1,5 @@ -import { TransactionOnNetwork, TransactionStatus } from "./networkProviders"; import { assert } from "chai"; +import { TransactionOnNetwork, TransactionStatus } from "./networkProviders"; import { MarkCompleted, MockNetworkProvider, Wait } from "./testutils"; import { TransactionHash } from "./transaction"; import { TransactionWatcher } from "./transactionWatcher"; diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index ae077b38b..741548769 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -9,6 +9,7 @@ import { import { ITransactionFetcher } from "./interface"; import { ITransactionEvent, ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork"; import { Logger } from "./logger"; +import { TransactionOnNetwork } from "./networkProviders"; export type PredicateIsAwaitedStatus = (status: ITransactionStatus) => boolean; @@ -77,7 +78,7 @@ export class TransactionWatcher { * Waits until the transaction is completely processed. * @param txHash The hex-encoded transaction hash */ - public async awaitCompleted(transactionOrTxHash: ITransaction | string): Promise { + public async awaitCompleted(transactionOrTxHash: ITransaction | string): Promise { const isCompleted = (transactionOnNetwork: ITransactionOnNetwork) => { if (transactionOnNetwork.isCompleted === undefined) { throw new ErrIsCompletedFieldIsMissingOnTransaction(); @@ -91,7 +92,7 @@ export class TransactionWatcher { }; const errorProvider = () => new ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(isCompleted, doFetch, errorProvider); + return this.awaitConditionally(isCompleted, doFetch, errorProvider); } public async awaitAllEvents( @@ -236,7 +237,7 @@ class TransactionFetcherWithTracing implements ITransactionFetcher { this.fetcher = fetcher; } - async getTransaction(txHash: string): Promise { + async getTransaction(txHash: string): Promise { Logger.debug(`transactionWatcher, getTransaction(${txHash})`); return await this.fetcher.getTransaction(txHash); } diff --git a/src/transactionsFactories/index.ts b/src/transactionsFactories/index.ts index 23d727598..505dff76b 100644 --- a/src/transactionsFactories/index.ts +++ b/src/transactionsFactories/index.ts @@ -1,3 +1,2 @@ -export * from "./tokenManagementTransactionsFactory"; export * from "./transactionsFactoryConfig"; export * from "./transferTransactionsFactory"; diff --git a/src/transactionsOutcomeParsers/index.ts b/src/transactionsOutcomeParsers/index.ts index 6511796e7..e3f3bafff 100644 --- a/src/transactionsOutcomeParsers/index.ts +++ b/src/transactionsOutcomeParsers/index.ts @@ -1,4 +1,4 @@ export * from "../smartContracts/smartContractTransactionsOutcomeParser"; +export * from "../tokenManagement/tokenManagementTransactionsOutcomeParser"; export * from "./resources"; -export * from "./tokenManagementTransactionsOutcomeParser"; export * from "./transactionEventsParser"; From c62e53eab8c82624143af99fd4a2fc2903e8f17b Mon Sep 17 00:00:00 2001 From: danielailie Date: Fri, 15 Nov 2024 12:56:01 +0200 Subject: [PATCH 024/214] Update input name --- src/smartContracts/resources.ts | 2 +- src/smartContracts/smartContractController.ts | 2 +- src/smartContracts/smartContractTransactionsFactory.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/smartContracts/resources.ts b/src/smartContracts/resources.ts index a4cab3eb2..4ebefe5b5 100644 --- a/src/smartContracts/resources.ts +++ b/src/smartContracts/resources.ts @@ -12,7 +12,7 @@ export type ContractDepoyInput = { isPayableBySmartContract?: boolean; }; -export type TransactionInput = { +export type ExecuteTransactionInput = { contract: Address; gasLimit: bigint; function: string; diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index 27dacb489..fa2318aef 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -69,7 +69,7 @@ export class SmartContractController { async createTransactionForExecute( sender: IAccount, nonce: bigint, - options: resources.TransactionInput, + options: resources.ExecuteTransactionInput, ): Promise { const transaction = this.factory.createTransactionForExecute(sender.address, options); diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index e4caeab19..0822384c5 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -71,7 +71,7 @@ export class SmartContractTransactionsFactory { }).build(); } - createTransactionForExecute(sender: Address, options: resources.TransactionInput): Transaction { + createTransactionForExecute(sender: Address, options: resources.ExecuteTransactionInput): Transaction { const args = options.arguments || []; let tokenTransfers = options.tokenTransfers ? [...options.tokenTransfers] : []; let nativeTransferAmount = options.nativeTransferAmount ?? 0n; From 0002e96ff3d22ade765a7c6658aaf9f6e55d45a2 Mon Sep 17 00:00:00 2001 From: danielailie Date: Fri, 15 Nov 2024 13:04:20 +0200 Subject: [PATCH 025/214] Update input naming --- src/smartContracts/resources.ts | 6 +++--- src/smartContracts/smartContractController.ts | 4 ++-- src/smartContracts/smartContractTransactionsFactory.ts | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/smartContracts/resources.ts b/src/smartContracts/resources.ts index 4ebefe5b5..78285aad8 100644 --- a/src/smartContracts/resources.ts +++ b/src/smartContracts/resources.ts @@ -1,7 +1,7 @@ import { Address } from "../address"; import { TokenTransfer } from "../tokens"; -export type ContractDepoyInput = { +export type ContractDeployInput = { bytecode: Uint8Array; gasLimit: bigint; arguments?: any[]; @@ -12,7 +12,7 @@ export type ContractDepoyInput = { isPayableBySmartContract?: boolean; }; -export type ExecuteTransactionInput = { +export type ContractExecuteInput = { contract: Address; gasLimit: bigint; function: string; @@ -21,7 +21,7 @@ export type ExecuteTransactionInput = { tokenTransfers?: TokenTransfer[]; }; -export type ContractUpgradeInput = ContractDepoyInput & { contract: Address }; +export type ContractUpgradeInput = ContractDeployInput & { contract: Address }; export interface SmartContractDeployOutcome { returnCode: string; diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index fa2318aef..8c4fb1790 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -38,7 +38,7 @@ export class SmartContractController { async createTransactionForDeploy( sender: IAccount, nonce: bigint, - options: resources.ContractDepoyInput, + options: resources.ContractDeployInput, ): Promise { const transaction = this.factory.createTransactionForDeploy(sender.address, options); @@ -69,7 +69,7 @@ export class SmartContractController { async createTransactionForExecute( sender: IAccount, nonce: bigint, - options: resources.ExecuteTransactionInput, + options: resources.ContractExecuteInput, ): Promise { const transaction = this.factory.createTransactionForExecute(sender.address, options); diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index 0822384c5..c5731dcc8 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -46,7 +46,7 @@ export class SmartContractTransactionsFactory { this.contractDeployAddress = Address.fromHex(CONTRACT_DEPLOY_ADDRESS_HEX, this.config.addressHrp); } - createTransactionForDeploy(sender: Address, options: resources.ContractDepoyInput): Transaction { + createTransactionForDeploy(sender: Address, options: resources.ContractDeployInput): Transaction { const nativeTransferAmount = options.nativeTransferAmount ?? 0n; const isUpgradeable = options.isUpgradeable ?? true; const isReadable = options.isReadable ?? true; @@ -71,7 +71,7 @@ export class SmartContractTransactionsFactory { }).build(); } - createTransactionForExecute(sender: Address, options: resources.ExecuteTransactionInput): Transaction { + createTransactionForExecute(sender: Address, options: resources.ContractExecuteInput): Transaction { const args = options.arguments || []; let tokenTransfers = options.tokenTransfers ? [...options.tokenTransfers] : []; let nativeTransferAmount = options.nativeTransferAmount ?? 0n; From 1d206ec52f9fd2e801d67676400e01cdce3fb186 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 10:57:09 +0200 Subject: [PATCH 026/214] Update types --- src/testutils/networkProviders.ts | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 18c8f1b25..6e3bebaf1 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,13 +1,7 @@ import { Query } from "../abi"; import { IAddress } from "../interface"; -import { - IAccountOnNetwork, - IContractQueryResponse, - INetworkConfig, - ITransactionOnNetwork, - ITransactionStatus, -} from "../interfaceOfNetwork"; -import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; +import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionStatus } from "../interfaceOfNetwork"; +import { ApiNetworkProvider, ProxyNetworkProvider, TransactionOnNetwork } from "../networkProviders"; import { Transaction } from "../transaction"; @@ -39,7 +33,7 @@ export function createMainnetProvider(): INetworkProvider { export interface INetworkProvider { getNetworkConfig(): Promise; getAccount(address: IAddress): Promise; - getTransaction(txHash: string, withProcessStatus?: boolean): Promise; + getTransaction(txHash: string, withProcessStatus?: boolean): Promise; getTransactionStatus(txHash: string): Promise; sendTransaction(tx: Transaction): Promise; simulateTransaction(tx: Transaction): Promise; From a0260901070267605db921e084895d4a37b50b8c Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 11:51:09 +0200 Subject: [PATCH 027/214] Add transfers controller --- src/abi/interaction.local.net.spec.ts | 2 +- src/abi/interaction.ts | 2 +- src/abi/smartContract.local.net.spec.ts | 2 +- src/abi/smartContract.ts | 2 +- .../smartContractResults.local.net.spec.ts | 2 +- src/accountManagement/accountController.ts | 2 +- .../accountTransactionsFactory.spec.ts | 2 +- .../accountTransactionsFactory.ts | 2 +- src/delegation/delegationController.ts | 2 +- .../delegationTransactionsFactory.spec.ts | 2 +- .../delegationTransactionsFactory.ts | 2 +- src/index.ts | 2 +- src/relayed/relayedController.ts | 2 +- .../relayedTransactionsFactory.spec.ts | 2 +- src/smartContracts/smartContractController.ts | 2 +- .../smartContractTransactionsFactory.spec.ts | 2 +- .../smartContractTransactionsFactory.ts | 4 +- .../tokenManagementController.ts | 2 +- .../tokenManagementTransactionFactory.spec.ts | 2 +- .../tokenManagementTransactionsFactory.ts | 2 +- .../tokenTransfersDataBuilder.ts | 6 +- src/transaction.local.net.spec.ts | 4 +- .../transactionBuilder.ts | 8 +- .../transactionsFactoryConfig.ts | 2 +- src/transferTransactionsFactory.spec.ts | 128 ------------------ .../index.ts | 2 +- src/transfers/resources.ts | 20 +++ .../transferTransactionsFactory.spec.ts | 53 +++----- .../transferTransactionsFactory.ts | 65 ++++----- src/transfers/transfersControllers.ts | 55 ++++++++ 30 files changed, 153 insertions(+), 232 deletions(-) rename src/{transactionsFactories => }/tokenTransfersDataBuilder.ts (92%) rename src/{transactionsFactories => }/transactionBuilder.ts (89%) rename src/{transactionsFactories => }/transactionsFactoryConfig.ts (98%) delete mode 100644 src/transferTransactionsFactory.spec.ts rename src/{transactionsFactories => transfers}/index.ts (51%) create mode 100644 src/transfers/resources.ts rename src/{transactionsFactories => transfers}/transferTransactionsFactory.spec.ts (93%) rename src/{transactionsFactories => transfers}/transferTransactionsFactory.ts (91%) create mode 100644 src/transfers/transfersControllers.ts diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 2a2487688..a827d2bc8 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -9,7 +9,7 @@ import { ContractController } from "../testutils/contractController"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { Interaction } from "./interaction"; import { ResultsParser } from "./resultsParser"; diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index 8519308d7..0cca6ae47 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -6,7 +6,7 @@ import { IAddress, IChainID, IGasLimit, IGasPrice, INonce, ITokenTransfer, ITran import { SmartContractTransactionsFactory } from "../smartContracts"; import { TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { ContractFunction } from "./function"; import { InteractionChecker } from "./interactionChecker"; import { CallArguments } from "./interface"; diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 818cc0349..d4401526a 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -8,7 +8,7 @@ import { prepareDeployment } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { loadTestWallets, TestWallet } from "../testutils/wallets"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { decodeUnsignedNumber } from "./codec"; import { ContractFunction } from "./function"; diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index ff8122bf4..6b1b4db08 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -4,7 +4,7 @@ import { TRANSACTION_MIN_GAS_PRICE } from "../constants"; import { ErrContractHasNoAddress } from "../errors"; import { INonce } from "../interface"; import { Transaction } from "../transaction"; -import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { guardValueIsSet } from "../utils"; import { SmartContractTransactionsFactory } from "./../smartContracts/smartContractTransactionsFactory"; import { CodeMetadata } from "./codeMetadata"; diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 850bd9a35..2f7ec81d7 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -4,7 +4,7 @@ import { SmartContractTransactionsFactory } from "../smartContracts"; import { loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { ContractFunction } from "./function"; import { ResultsParser } from "./resultsParser"; diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index 91ca55150..a73b92b8f 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -1,7 +1,7 @@ import { IAccount } from "../accounts/interfaces"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; import { SaveKeyValueInput, SetGuardianInput } from "./resources"; diff --git a/src/accountManagement/accountTransactionsFactory.spec.ts b/src/accountManagement/accountTransactionsFactory.spec.ts index 78660dd6f..77ce1a041 100644 --- a/src/accountManagement/accountTransactionsFactory.spec.ts +++ b/src/accountManagement/accountTransactionsFactory.spec.ts @@ -1,6 +1,6 @@ import { assert } from "chai"; import { Address } from "../address"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; describe("test account transactions factory", function () { diff --git a/src/accountManagement/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts index f9bbc5a16..8fdeed7db 100644 --- a/src/accountManagement/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -1,7 +1,7 @@ import { Address } from "../address"; import { IAddress } from "../interface"; import { Transaction } from "../transaction"; -import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; +import { TransactionBuilder } from "../transactionBuilder"; import { SaveKeyValueInput, SetGuardianInput } from "./resources"; interface IConfig { diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index e8ad9c787..01ebbef58 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -3,7 +3,7 @@ import { ITransactionOnNetwork } from "../interfaceOfNetwork"; import { INetworkProvider } from "../networkProviders/interface"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; diff --git a/src/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index 67f21a49e..6a9e53f88 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import { Address } from "../address"; import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../constants"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { ValidatorPublicKey } from "../wallet"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; diff --git a/src/delegation/delegationTransactionsFactory.ts b/src/delegation/delegationTransactionsFactory.ts index 193521827..2c5f94374 100644 --- a/src/delegation/delegationTransactionsFactory.ts +++ b/src/delegation/delegationTransactionsFactory.ts @@ -4,7 +4,7 @@ import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../constants"; import { Err } from "../errors"; import { IAddress } from "../interface"; import { Transaction } from "../transaction"; -import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; +import { TransactionBuilder } from "../transactionBuilder"; import * as resources from "./resources"; interface IConfig { diff --git a/src/index.ts b/src/index.ts index 7b89d4c2c..7207227d3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -34,8 +34,8 @@ export * from "./tokens"; export * from "./transaction"; export * from "./transactionComputer"; export * from "./transactionPayload"; -export * from "./transactionsFactories"; export * from "./transactionsOutcomeParsers"; export * from "./transactionWatcher"; +export * from "./transfers"; export * from "./utils"; export * from "./wallet"; diff --git a/src/relayed/relayedController.ts b/src/relayed/relayedController.ts index 2b48500e0..3a219c470 100644 --- a/src/relayed/relayedController.ts +++ b/src/relayed/relayedController.ts @@ -1,7 +1,7 @@ import { IAccount } from "../accounts/interfaces"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; import { RelayedV1TransactionInput, RelayedV2TransactionInput } from "./resources"; diff --git a/src/relayed/relayedTransactionsFactory.spec.ts b/src/relayed/relayedTransactionsFactory.spec.ts index cbd41f337..0be7b0d43 100644 --- a/src/relayed/relayedTransactionsFactory.spec.ts +++ b/src/relayed/relayedTransactionsFactory.spec.ts @@ -2,7 +2,7 @@ import { assert } from "chai"; import { TestWallet, loadTestWallets } from "../testutils"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; describe("test relayed transactions factory", function () { diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index 8c4fb1790..a469b39d0 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -7,7 +7,7 @@ import { INetworkProvider } from "../networkProviders/interface"; import { SmartContractQueriesController } from "../smartContractQueriesController"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { SmartContractTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; import { TransactionWatcher } from "../transactionWatcher"; import * as resources from "./resources"; diff --git a/src/smartContracts/smartContractTransactionsFactory.spec.ts b/src/smartContracts/smartContractTransactionsFactory.spec.ts index b2c88ff97..eae01d4c0 100644 --- a/src/smartContracts/smartContractTransactionsFactory.spec.ts +++ b/src/smartContracts/smartContractTransactionsFactory.spec.ts @@ -4,7 +4,7 @@ import { Address } from "../address"; import { Err } from "../errors"; import { loadAbiRegistry, loadContractCode } from "../testutils/utils"; import { Token, TokenTransfer } from "../tokens"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { SmartContractTransactionsFactory } from "./smartContractTransactionsFactory"; describe("test smart contract transactions factory", function () { diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index c5731dcc8..899904d0c 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -6,9 +6,9 @@ import { CONTRACT_DEPLOY_ADDRESS_HEX, VM_TYPE_WASM_VM } from "../constants"; import { Err } from "../errors"; import { Logger } from "../logger"; import { TokenComputer, TokenTransfer } from "../tokens"; +import { TokenTransfersDataBuilder } from "../tokenTransfersDataBuilder"; import { Transaction } from "../transaction"; -import { TokenTransfersDataBuilder } from "../transactionsFactories/tokenTransfersDataBuilder"; -import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; +import { TransactionBuilder } from "../transactionBuilder"; import { byteArrayToHex, utf8ToHex } from "../utils.codec"; import * as resources from "./resources"; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index a552b895c..2acaff254 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -4,7 +4,7 @@ import { INetworkProvider } from "../networkProviders/interface"; import { IESDTIssueOutcome } from "../tokenOperations"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TokenManagementTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; import { TransactionWatcher } from "../transactionWatcher"; import * as resources from "./resources"; diff --git a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts index 2c2d432cc..9808d41ae 100644 --- a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts @@ -2,7 +2,7 @@ import { assert } from "chai"; import { Address } from "../address"; import { ESDT_CONTRACT_ADDRESS_HEX } from "../constants"; import { loadTestWallets, TestWallet } from "../testutils"; -import { TransactionsFactoryConfig } from "../transactionsFactories"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TokenManagementTransactionsFactory } from "./tokenManagementTransactionsFactory"; describe("test token management transactions factory", () => { diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index 2388a2df1..0c8a34222 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -5,7 +5,7 @@ import { ErrBadUsage } from "../errors"; import { IAddress } from "../interface"; import { Logger } from "../logger"; import { Transaction } from "../transaction"; -import { TransactionBuilder } from "../transactionsFactories/transactionBuilder"; +import { TransactionBuilder } from "../transactionBuilder"; import * as resources from "./resources"; interface IConfig { diff --git a/src/transactionsFactories/tokenTransfersDataBuilder.ts b/src/tokenTransfersDataBuilder.ts similarity index 92% rename from src/transactionsFactories/tokenTransfersDataBuilder.ts rename to src/tokenTransfersDataBuilder.ts index 75e8b2409..17e416d13 100644 --- a/src/transactionsFactories/tokenTransfersDataBuilder.ts +++ b/src/tokenTransfersDataBuilder.ts @@ -1,6 +1,6 @@ -import { AddressValue, ArgSerializer, BigUIntValue, TokenIdentifierValue, TypedValue, U32Value } from "../abi"; -import { IAddress } from "../interface"; -import { TokenComputer, TokenTransfer } from "../tokens"; +import { AddressValue, ArgSerializer, BigUIntValue, TokenIdentifierValue, TypedValue, U32Value } from "./abi"; +import { IAddress } from "./interface"; +import { TokenComputer, TokenTransfer } from "./tokens"; export class TokenTransfersDataBuilder { private tokenComputer: TokenComputer; diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 15082da7d..d0c07dc8d 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -7,9 +7,9 @@ import { TokenTransfer } from "./tokens"; import { Transaction } from "./transaction"; import { TransactionComputer } from "./transactionComputer"; import { TransactionPayload } from "./transactionPayload"; +import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; import { TransactionWatcher } from "./transactionWatcher"; -import { TransactionsFactoryConfig } from "./transactionsFactories/transactionsFactoryConfig"; -import { TransferTransactionsFactory } from "./transactionsFactories/transferTransactionsFactory"; +import { TransferTransactionsFactory } from "./transfers/transferTransactionsFactory"; describe("test transaction", function () { let alice: TestWallet, bob: TestWallet; diff --git a/src/transactionsFactories/transactionBuilder.ts b/src/transactionBuilder.ts similarity index 89% rename from src/transactionsFactories/transactionBuilder.ts rename to src/transactionBuilder.ts index 6c163e816..d4b684a6b 100644 --- a/src/transactionsFactories/transactionBuilder.ts +++ b/src/transactionBuilder.ts @@ -1,7 +1,7 @@ -import { ARGUMENTS_SEPARATOR } from "../constants"; -import { IAddress, ITransactionPayload } from "../interface"; -import { Transaction } from "../transaction"; -import { TransactionPayload } from "../transactionPayload"; +import { ARGUMENTS_SEPARATOR } from "./constants"; +import { IAddress, ITransactionPayload } from "./interface"; +import { Transaction } from "./transaction"; +import { TransactionPayload } from "./transactionPayload"; interface Config { chainID: string; diff --git a/src/transactionsFactories/transactionsFactoryConfig.ts b/src/transactionsFactoryConfig.ts similarity index 98% rename from src/transactionsFactories/transactionsFactoryConfig.ts rename to src/transactionsFactoryConfig.ts index c1d21df92..1ad0007f1 100644 --- a/src/transactionsFactories/transactionsFactoryConfig.ts +++ b/src/transactionsFactoryConfig.ts @@ -1,4 +1,4 @@ -import { LibraryConfig } from "../config"; +import { LibraryConfig } from "./config"; export class TransactionsFactoryConfig { chainID: string; diff --git a/src/transferTransactionsFactory.spec.ts b/src/transferTransactionsFactory.spec.ts deleted file mode 100644 index 39e6f96d1..000000000 --- a/src/transferTransactionsFactory.spec.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { assert } from "chai"; -import { Address } from "./address"; -import { GasEstimator } from "./gasEstimator"; -import { TokenTransfer } from "./tokens"; -import { TransactionPayload } from "./transactionPayload"; -import { TransferTransactionsFactory } from "./transactionsFactories/transferTransactionsFactory"; - -describe("test transaction factory", () => { - const factory = new TransferTransactionsFactory(new GasEstimator()); - - it("should create EGLD transfers", () => { - const transactionWithData = factory.createEGLDTransfer({ - value: TokenTransfer.egldFromAmount(10.5), - sender: Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), - receiver: new Address("erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha"), - data: new TransactionPayload("hello"), - chainID: "D", - }); - - assert.equal( - transactionWithData.getSender().bech32(), - "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - ); - assert.equal( - transactionWithData.getReceiver().bech32(), - "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha", - ); - assert.equal(transactionWithData.getValue(), "10500000000000000000"); - assert.equal(transactionWithData.getGasLimit(), 50000 + 5 * 1500); - assert.equal(transactionWithData.getData().toString(), "hello"); - assert.equal(transactionWithData.getChainID(), "D"); - - const transactionWithoutData = factory.createEGLDTransfer({ - value: TokenTransfer.egldFromAmount(10.5), - sender: Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), - receiver: new Address("erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha"), - chainID: "D", - }); - - assert.equal( - transactionWithoutData.getSender().bech32(), - "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - ); - assert.equal( - transactionWithoutData.getReceiver().bech32(), - "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha", - ); - assert.equal(transactionWithoutData.getValue(), "10500000000000000000"); - assert.equal(transactionWithoutData.getGasLimit(), 50000); - assert.equal(transactionWithoutData.getData().toString(), ""); - assert.equal(transactionWithoutData.getChainID(), "D"); - }); - - it("should create ESDT transfers", () => { - const transaction = factory.createESDTTransfer({ - tokenTransfer: TokenTransfer.fungibleFromAmount("TEST-8b028f", "100.00", 2), - sender: Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), - receiver: Address.fromBech32("erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha"), - chainID: "D", - }); - - assert.equal( - transaction.getSender().bech32(), - "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - ); - assert.equal( - transaction.getReceiver().bech32(), - "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha", - ); - assert.equal(transaction.getValue(), ""); - assert.equal(transaction.getGasLimit(), 50000 + 40 * 1500 + 200000 + 100000); - assert.equal(transaction.getData().toString(), "ESDTTransfer@544553542d386230323866@2710"); - assert.equal(transaction.getChainID(), "D"); - }); - - it("should create ESDTNFT transfers", () => { - const transaction = factory.createESDTNFTTransfer({ - tokenTransfer: TokenTransfer.nonFungible("TEST-38f249", 1), - destination: new Address("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), - sender: new Address("erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha"), - chainID: "D", - }); - - assert.equal( - transaction.getSender().bech32(), - "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha", - ); - assert.equal( - transaction.getReceiver().bech32(), - "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha", - ); - assert.equal(transaction.getValue(), ""); - assert.equal(transaction.getGasLimit(), 50000 + 109 * 1500 + 200000 + 800000); - assert.equal( - transaction.getData().toString(), - "ESDTNFTTransfer@544553542d333866323439@01@01@8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8", - ); - assert.equal(transaction.getChainID(), "D"); - }); - - it("should create Multi ESDTNFT transfers", () => { - const transaction = factory.createMultiESDTNFTTransfer({ - tokenTransfers: [ - TokenTransfer.nonFungible("FOO-38f249", 1), - TokenTransfer.fungibleFromAmount("BAR-c80d29", "10.00", 18), - ], - destination: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), - sender: new Address("erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha"), - chainID: "D", - }); - - assert.equal( - transaction.getSender().bech32(), - "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha", - ); - assert.equal( - transaction.getReceiver().bech32(), - "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha", - ); - assert.equal(transaction.getValue(), ""); - assert.equal(transaction.getGasLimit(), 50000 + 154 * 1500 + (200000 + 800000) * 2); - assert.equal( - transaction.getData().toString(), - "MultiESDTNFTTransfer@0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1@02@464f4f2d333866323439@01@01@4241522d633830643239@@8ac7230489e80000", - ); - assert.equal(transaction.getChainID(), "D"); - }); -}); diff --git a/src/transactionsFactories/index.ts b/src/transfers/index.ts similarity index 51% rename from src/transactionsFactories/index.ts rename to src/transfers/index.ts index 505dff76b..1542bb8ce 100644 --- a/src/transactionsFactories/index.ts +++ b/src/transfers/index.ts @@ -1,2 +1,2 @@ -export * from "./transactionsFactoryConfig"; +export * from "./transfersControllers"; export * from "./transferTransactionsFactory"; diff --git a/src/transfers/resources.ts b/src/transfers/resources.ts new file mode 100644 index 000000000..4590092f2 --- /dev/null +++ b/src/transfers/resources.ts @@ -0,0 +1,20 @@ +import { Address } from "../address"; +import { TokenTransfer } from "../tokens"; + +export type NativeTokenTransferInput = { + receiver: Address; + nativeAmount?: bigint; + data?: Uint8Array; +}; + +export type ESDTTokenTransferInput = { + receiver: Address; + tokenTransfers: TokenTransfer[]; +}; + +export type CreateTransferTransactionInput = { + receiver: Address; + nativeAmount?: bigint; + tokenTransfers?: TokenTransfer[]; + data?: Uint8Array; +}; diff --git a/src/transactionsFactories/transferTransactionsFactory.spec.ts b/src/transfers/transferTransactionsFactory.spec.ts similarity index 93% rename from src/transactionsFactories/transferTransactionsFactory.spec.ts rename to src/transfers/transferTransactionsFactory.spec.ts index 6a7581c3e..b4cda39f9 100644 --- a/src/transactionsFactories/transferTransactionsFactory.spec.ts +++ b/src/transfers/transferTransactionsFactory.spec.ts @@ -3,7 +3,7 @@ import { Address } from "../address"; import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../constants"; import { ErrBadUsage } from "../errors"; import { Token, TokenTransfer } from "../tokens"; -import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransferTransactionsFactory } from "./transferTransactionsFactory"; describe("test transfer transactions factory", function () { @@ -20,8 +20,7 @@ describe("test transfer transactions factory", function () { assert.throw( () => { - transferFactory.createTransactionForESDTTokenTransfer({ - sender: alice, + transferFactory.createTransactionForESDTTokenTransfer(alice, { receiver: bob, tokenTransfers: transfers, }); @@ -32,8 +31,7 @@ describe("test transfer transactions factory", function () { }); it("should create 'Transaction' for native token transfer without data", async () => { - const transaction = transferFactory.createTransactionForNativeTokenTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForNativeTokenTransfer(alice, { receiver: bob, nativeAmount: 1000000000000000000n, }); @@ -46,8 +44,7 @@ describe("test transfer transactions factory", function () { }); it("should create 'Transaction' for native token transfer with data", async () => { - const transaction = transferFactory.createTransactionForNativeTokenTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForNativeTokenTransfer(alice, { receiver: bob, nativeAmount: 1000000000000000000n, data: Buffer.from("test data"), @@ -64,8 +61,7 @@ describe("test transfer transactions factory", function () { const fooToken = new Token({ identifier: "FOO-123456", nonce: 0n }); const transfer = new TokenTransfer({ token: fooToken, amount: 1000000n }); - const transaction = transferFactory.createTransactionForESDTTokenTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForESDTTokenTransfer(alice, { receiver: bob, tokenTransfers: [transfer], }); @@ -81,8 +77,7 @@ describe("test transfer transactions factory", function () { const nft = new Token({ identifier: "NFT-123456", nonce: 10n }); const transfer = new TokenTransfer({ token: nft, amount: 1n }); - const transaction = transferFactory.createTransactionForESDTTokenTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForESDTTokenTransfer(alice, { receiver: bob, tokenTransfers: [transfer], }); @@ -101,8 +96,7 @@ describe("test transfer transactions factory", function () { const nft = new Token({ identifier: "t0-NFT-123456", nonce: 10n }); const transfer = new TokenTransfer({ token: nft, amount: 1n }); - const transaction = transferFactory.createTransactionForESDTTokenTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForESDTTokenTransfer(alice, { receiver: bob, tokenTransfers: [transfer], }); @@ -124,8 +118,7 @@ describe("test transfer transactions factory", function () { const secondNft = new Token({ identifier: "TEST-987654", nonce: 1n }); const secondTransfer = new TokenTransfer({ token: secondNft, amount: 1n }); - const transaction = transferFactory.createTransactionForESDTTokenTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForESDTTokenTransfer(alice, { receiver: bob, tokenTransfers: [firstTransfer, secondTransfer], }); @@ -139,8 +132,7 @@ describe("test transfer transactions factory", function () { "MultiESDTNFTTransfer@8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8@02@4e46542d313233343536@0a@01@544553542d393837363534@01@01", ); - const secondTransaction = transferFactory.createTransactionForTransfer({ - sender: alice, + const secondTransaction = transferFactory.createTransactionForTransfer(alice, { receiver: bob, tokenTransfers: [firstTransfer, secondTransfer], }); @@ -155,8 +147,7 @@ describe("test transfer transactions factory", function () { const secondNft = new Token({ identifier: "t0-TEST-987654", nonce: 1n }); const secondTransfer = new TokenTransfer({ token: secondNft, amount: 1n }); - const transaction = transferFactory.createTransactionForESDTTokenTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForESDTTokenTransfer(alice, { receiver: bob, tokenTransfers: [firstTransfer, secondTransfer], }); @@ -170,8 +161,7 @@ describe("test transfer transactions factory", function () { "MultiESDTNFTTransfer@8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8@02@74302d4e46542d313233343536@0a@01@74302d544553542d393837363534@01@01", ); - const secondTransaction = transferFactory.createTransactionForTransfer({ - sender: alice, + const secondTransaction = transferFactory.createTransactionForTransfer(alice, { receiver: bob, tokenTransfers: [firstTransfer, secondTransfer], }); @@ -184,8 +174,7 @@ describe("test transfer transactions factory", function () { const nft = new Token({ identifier: "NFT-123456", nonce: 10n }); const transfer = new TokenTransfer({ token: nft, amount: 1n }); - transferFactory.createTransactionForTransfer({ - sender: alice, + transferFactory.createTransactionForTransfer(alice, { receiver: bob, tokenTransfers: [transfer], data: Buffer.from("test"), @@ -194,8 +183,7 @@ describe("test transfer transactions factory", function () { }); it("should create transaction for native transfers", async () => { - const transaction = transferFactory.createTransactionForTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForTransfer(alice, { receiver: bob, nativeAmount: 1000000000000000000n, }); @@ -207,8 +195,7 @@ describe("test transfer transactions factory", function () { }); it("should create transaction for native transfers and set data field", async () => { - const transaction = transferFactory.createTransactionForTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForTransfer(alice, { receiver: bob, nativeAmount: 1000000000000000000n, data: Buffer.from("hello"), @@ -222,8 +209,7 @@ describe("test transfer transactions factory", function () { }); it("should create transaction for notarizing", async () => { - const transaction = transferFactory.createTransactionForTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForTransfer(alice, { receiver: bob, data: Buffer.from("hello"), }); @@ -241,8 +227,7 @@ describe("test transfer transactions factory", function () { const secondNft = new Token({ identifier: "TEST-987654", nonce: 1n }); const secondTransfer = new TokenTransfer({ token: secondNft, amount: 1n }); - const transaction = transferFactory.createTransactionForTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForTransfer(alice, { receiver: bob, nativeAmount: 1000000000000000000n, tokenTransfers: [firstTransfer, secondTransfer], @@ -265,8 +250,7 @@ describe("test transfer transactions factory", function () { const secondNft = new Token({ identifier: "t0-TEST-987654", nonce: 1n }); const secondTransfer = new TokenTransfer({ token: secondNft, amount: 1n }); - const transaction = transferFactory.createTransactionForTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForTransfer(alice, { receiver: bob, nativeAmount: 1000000000000000000n, tokenTransfers: [firstTransfer, secondTransfer], @@ -286,8 +270,7 @@ describe("test transfer transactions factory", function () { const firstNft = new Token({ identifier: EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER }); const firstTransfer = new TokenTransfer({ token: firstNft, amount: 1000000000000000000n }); - const transaction = transferFactory.createTransactionForESDTTokenTransfer({ - sender: alice, + const transaction = transferFactory.createTransactionForESDTTokenTransfer(alice, { receiver: bob, tokenTransfers: [firstTransfer], }); diff --git a/src/transactionsFactories/transferTransactionsFactory.ts b/src/transfers/transferTransactionsFactory.ts similarity index 91% rename from src/transactionsFactories/transferTransactionsFactory.ts rename to src/transfers/transferTransactionsFactory.ts index b4e43c079..852331e31 100644 --- a/src/transactionsFactories/transferTransactionsFactory.ts +++ b/src/transfers/transferTransactionsFactory.ts @@ -12,10 +12,11 @@ import { ITransactionValue, } from "../interface"; import { TokenComputer, TokenTransfer } from "../tokens"; +import { TokenTransfersDataBuilder } from "../tokenTransfersDataBuilder"; import { Transaction } from "../transaction"; +import { TransactionBuilder } from "../transactionBuilder"; import { TransactionPayload } from "../transactionPayload"; -import { TokenTransfersDataBuilder } from "./tokenTransfersDataBuilder"; -import { TransactionBuilder } from "./transactionBuilder"; +import * as resources from "./resources"; const ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 100000; const ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 800000; @@ -81,31 +82,25 @@ export class TransferTransactionsFactory { } } - createTransactionForNativeTokenTransfer(options: { - sender: IAddress; - receiver: IAddress; - nativeAmount: bigint; - data?: Uint8Array; - }): Transaction { + createTransactionForNativeTokenTransfer( + sender: IAddress, + options: resources.NativeTokenTransferInput, + ): Transaction { this.ensureConfigIsDefined(); const data = options.data || new Uint8Array(); return new Transaction({ - sender: options.sender.bech32(), + sender: sender.bech32(), receiver: options.receiver.bech32(), chainID: this.config!.chainID, gasLimit: this.computeGasForMoveBalance(this.config!, data), data: data, - value: options.nativeAmount, + value: options.nativeAmount ?? BigInt(0), }); } - createTransactionForESDTTokenTransfer(options: { - sender: IAddress; - receiver: IAddress; - tokenTransfers: TokenTransfer[]; - }): Transaction { + createTransactionForESDTTokenTransfer(sender: IAddress, options: resources.ESDTTokenTransferInput): Transaction { this.ensureConfigIsDefined(); const numberOfTransfers = options.tokenTransfers.length; @@ -115,7 +110,7 @@ export class TransferTransactionsFactory { } if (numberOfTransfers === 1) { - return this.createSingleESDTTransferTransaction(options); + return this.createSingleESDTTransferTransaction(sender, options); } const { dataParts, extraGasForTransfer } = this.buildMultiESDTNFTTransferData( @@ -125,21 +120,15 @@ export class TransferTransactionsFactory { return new TransactionBuilder({ config: this.config!, - sender: options.sender, - receiver: options.sender, + sender: sender, + receiver: sender, dataParts: dataParts, gasLimit: extraGasForTransfer, addDataMovementGas: true, }).build(); } - createTransactionForTransfer(options: { - sender: IAddress; - receiver: IAddress; - nativeAmount?: bigint; - tokenTransfers?: TokenTransfer[]; - data?: Uint8Array; - }): Transaction { + createTransactionForTransfer(sender: IAddress, options: resources.CreateTransferTransactionInput): Transaction { const nativeAmount = options.nativeAmount ?? 0n; let tokenTransfers = options.tokenTransfers ? [...options.tokenTransfers] : []; const numberOfTokens = tokenTransfers.length; @@ -149,8 +138,7 @@ export class TransferTransactionsFactory { } if ((nativeAmount && numberOfTokens === 0) || options.data) { - return this.createTransactionForNativeTokenTransfer({ - sender: options.sender, + return this.createTransactionForNativeTokenTransfer(sender, { receiver: options.receiver, nativeAmount: nativeAmount, data: options.data, @@ -162,8 +150,7 @@ export class TransferTransactionsFactory { tokenTransfers.push(nativeTransfer); } - return this.createTransactionForESDTTokenTransfer({ - sender: options.sender, + return this.createTransactionForESDTTokenTransfer(sender, { receiver: options.receiver, tokenTransfers: tokenTransfers, }); @@ -348,20 +335,24 @@ export class TransferTransactionsFactory { }); } - private createSingleESDTTransferTransaction(options: { - sender: IAddress; - receiver: IAddress; - tokenTransfers: TokenTransfer[]; - }): Transaction { + private createSingleESDTTransferTransaction( + sender: IAddress, + options: { + receiver: IAddress; + tokenTransfers: TokenTransfer[]; + }, + ): Transaction { this.ensureConfigIsDefined(); const transfer = options.tokenTransfers[0]; - - const { dataParts, extraGasForTransfer, receiver } = this.buildTransferData(transfer, options); + const { dataParts, extraGasForTransfer, receiver } = this.buildTransferData(transfer, { + sender, + receiver: options.receiver, + }); return new TransactionBuilder({ config: this.config!, - sender: options.sender, + sender: sender, receiver: receiver, dataParts: dataParts, gasLimit: extraGasForTransfer, diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts new file mode 100644 index 000000000..1692a36ae --- /dev/null +++ b/src/transfers/transfersControllers.ts @@ -0,0 +1,55 @@ +import { IAccount } from "../accounts/interfaces"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; +import * as resources from "./resources"; +import { TransferTransactionsFactory } from "./transferTransactionsFactory"; + +export class TransfersController { + private factory: TransferTransactionsFactory; + private txComputer: TransactionComputer; + + constructor(options: { chainID: string }) { + this.factory = new TransferTransactionsFactory({ config: new TransactionsFactoryConfig(options) }); + this.txComputer = new TransactionComputer(); + } + + async createTransactionForNativeTokenTransfer( + sender: IAccount, + nonce: bigint, + options: resources.NativeTokenTransferInput, + ): Promise { + const transaction = this.factory.createTransactionForNativeTokenTransfer(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForEsdtTokenTransfer( + sender: IAccount, + nonce: bigint, + options: resources.ESDTTokenTransferInput, + ): Promise { + const transaction = this.factory.createTransactionForESDTTokenTransfer(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForTransfer( + sender: IAccount, + nonce: bigint, + options: resources.CreateTransferTransactionInput, + ): Promise { + const transaction = this.factory.createTransactionForTransfer(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } +} From 73ac82f2583a0f497a00361cc0cde609640dc78b Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 11:53:45 +0200 Subject: [PATCH 028/214] Run build on all PRs --- .github/workflows/build.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5881ae129..26d36b49b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -5,7 +5,6 @@ name: Build and Test on: pull_request: - branches: [ main, development, feat/*, release/* ] workflow_dispatch: jobs: From cf1d4787db2923a3c3b0670c0d9e7f4dc046be83 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 12:08:59 +0200 Subject: [PATCH 029/214] Update input namings --- src/testutils/networkProviders.ts | 2 +- src/tokenManagement/resources.ts | 6 +++++- .../tokenManagementTransactionsFactory.ts | 14 +++++++------- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 6e3bebaf1..7e5f49ea0 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -33,7 +33,7 @@ export function createMainnetProvider(): INetworkProvider { export interface INetworkProvider { getNetworkConfig(): Promise; getAccount(address: IAddress): Promise; - getTransaction(txHash: string, withProcessStatus?: boolean): Promise; + getTransaction(txHash: string): Promise; getTransactionStatus(txHash: string): Promise; sendTransaction(tx: Transaction): Promise; simulateTransaction(tx: Transaction): Promise; diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 32e4ce3c6..a08a4ec0a 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -50,6 +50,7 @@ export type MintInput = { uris: string[]; }; export type ManagementInput = { user: IAddress; tokenIdentifier: string }; +export type PausingInput = { tokenIdentifier: string }; export type LocalBurnInput = { tokenIdentifier: string; supplyToBurn: bigint }; export type LocalMintInput = { tokenIdentifier: string; supplyToMint: bigint }; @@ -59,6 +60,8 @@ export type UpdateQuantityInput = UpdateInput & { quantity: bigint }; export type UpdateInput = { tokenIdentifier: string; tokenNonce: bigint }; export type BurnRoleGloballyInput = { tokenIdentifier: string }; +export type UpdateTokenIDInput = { tokenIdentifier: string }; +export type ChangeTokenToDynamicInput = { tokenIdentifier: string }; export type RegisterRolesInput = { tokenName: string; @@ -81,12 +84,13 @@ export type RegisterMetaESDTInput = { }; export type ModifyRoyaltiesInput = BaseInput & { newRoyalties: bigint }; +export type ModifyCreatorInput = BaseInput; export type BaseInput = { tokenIdentifier: string; tokenNonce: bigint }; export type SetNewUriInput = BaseInput & { newUris: string[] }; -export type UpdateMetadataInput = { +export type ManageMetadataInput = { tokenIdentifier: string; tokenNonce: bigint; newTokenName?: string; diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index 2388a2df1..261912046 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -370,7 +370,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForPausing(sender: IAddress, options: resources.ManagementInput): Transaction { + createTransactionForPausing(sender: IAddress, options: resources.PausingInput): Transaction { const dataParts = ["pause", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)])]; return new TransactionBuilder({ @@ -383,7 +383,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUnpausing(sender: IAddress, options: resources.ManagementInput): Transaction { + createTransactionForUnpausing(sender: IAddress, options: resources.PausingInput): Transaction { const dataParts = [ "unPause", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), @@ -598,7 +598,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForModifyingCreator(sender: IAddress, options: resources.BaseInput): Transaction { + createTransactionForModifyingCreator(sender: IAddress, options: resources.ModifyCreatorInput): Transaction { const dataParts = [ "ESDTModifyCreator", ...this.argSerializer.valuesToStrings([ @@ -617,7 +617,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUpdatingMetadata(sender: IAddress, options: resources.UpdateMetadataInput): Transaction { + createTransactionForUpdatingMetadata(sender: IAddress, options: resources.ManageMetadataInput): Transaction { const dataParts = [ "ESDTMetaDataUpdate", ...this.argSerializer.valuesToStrings([ @@ -641,7 +641,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForMetadataRecreate(sender: IAddress, options: resources.UpdateMetadataInput): Transaction { + createTransactionForMetadataRecreate(sender: IAddress, options: resources.ManageMetadataInput): Transaction { const dataParts = [ "ESDTMetaDataRecreate", ...this.argSerializer.valuesToStrings([ @@ -667,7 +667,7 @@ export class TokenManagementTransactionsFactory { createTransactionForChangingTokenToDynamic( sender: IAddress, - options: resources.BurnRoleGloballyInput, + options: resources.ChangeTokenToDynamicInput, ): Transaction { const dataParts = [ "changeToDynamic", @@ -684,7 +684,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUpdatingTokenId(sender: IAddress, options: resources.BurnRoleGloballyInput): Transaction { + createTransactionForUpdatingTokenId(sender: IAddress, options: resources.UpdateTokenIDInput): Transaction { const dataParts = [ "updateTokenID", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), From 4ab1934b5d2f42d198eb42ef5acfddff5fb7919f Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 12:15:37 +0200 Subject: [PATCH 030/214] Fix test --- src/testutils/contractController.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/testutils/contractController.ts b/src/testutils/contractController.ts index a053e4431..b8643fcf3 100644 --- a/src/testutils/contractController.ts +++ b/src/testutils/contractController.ts @@ -15,7 +15,7 @@ export class ContractController { this.provider = provider; this.transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { - return await provider.getTransaction(hash, true); + return await provider.getTransaction(hash); }, }); } From 1643a52d425d33107a6aac4e95713c8cdeb1a17f Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 12:16:59 +0200 Subject: [PATCH 031/214] Fix tests --- src/transaction.local.net.spec.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index d0c07dc8d..9c9d77326 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -156,8 +156,7 @@ describe("test transaction", function () { await bob.sync(provider); const initialBalanceOfBob = new BigNumber(bob.account.balance.toString()); - const transaction = factory.createTransactionForNativeTokenTransfer({ - sender: alice.address, + const transaction = factory.createTransactionForNativeTokenTransfer(alice.address, { receiver: bob.address, nativeAmount: 42000000000000000000n, }); From 50a09e18ae97cddf6dd430ebf4e90ced4a5b171c Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 12:27:18 +0200 Subject: [PATCH 032/214] Fix integration tests --- src/abi/interaction.local.net.spec.ts | 6 +++--- src/abi/smartContract.local.net.spec.ts | 2 +- src/abi/smartContractResults.local.net.spec.ts | 2 +- src/transaction.local.net.spec.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 2a2487688..68d119c79 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -118,7 +118,7 @@ describe("test smart contract interactor", function () { const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { - return await provider.getTransaction(hash, true); + return await provider.getTransaction(hash); }, }); @@ -406,7 +406,7 @@ describe("test smart contract interactor", function () { const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { - return await provider.getTransaction(hash, true); + return await provider.getTransaction(hash); }, }); @@ -600,7 +600,7 @@ describe("test smart contract interactor", function () { const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { - return await provider.getTransaction(hash, true); + return await provider.getTransaction(hash); }, }); diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 818cc0349..1bde9a611 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -35,7 +35,7 @@ describe("test on local testnet", function () { watcher = new TransactionWatcher({ getTransaction: async (hash: string) => { - return await provider.getTransaction(hash, true); + return await provider.getTransaction(hash); }, }); }); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 850bd9a35..5f74c6809 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -21,7 +21,7 @@ describe("fetch transactions from local testnet", function () { ({ alice } = await loadTestWallets()); watcher = new TransactionWatcher({ getTransaction: async (hash: string) => { - return await provider.getTransaction(hash, true); + return await provider.getTransaction(hash); }, }); }); diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 15082da7d..ed8dd0ab7 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -22,7 +22,7 @@ describe("test transaction", function () { return new TransactionWatcher( { getTransaction: async (hash: string) => { - return await provider.getTransaction(hash, true); + return await provider.getTransaction(hash); }, }, { timeoutMilliseconds: 100000 }, From 266fdb3eca8b6fddf7f86f96fa3b877871dacb15 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 12:38:37 +0200 Subject: [PATCH 033/214] Update naming to match factory --- src/tokenManagement/tokenManagementController.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index a552b895c..9a36baf01 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -276,7 +276,7 @@ export class TokenManagementController { async createTransactionForPausing( sender: IAccount, nonce: bigint, - options: resources.ManagementInput, + options: resources.PausingInput, ): Promise { const transaction = this.factory.createTransactionForPausing(sender.address, options); @@ -298,7 +298,7 @@ export class TokenManagementController { async createTransactionForUnpausing( sender: IAccount, nonce: bigint, - options: resources.ManagementInput, + options: resources.PausingInput, ): Promise { const transaction = this.factory.createTransactionForUnpausing(sender.address, options); From a344eaee63114cae0d93ca1d930d04e12239131e Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 13:43:17 +0200 Subject: [PATCH 034/214] Update name for input --- src/transfers/resources.ts | 2 +- src/transfers/transferTransactionsFactory.ts | 2 +- src/transfers/transfersControllers.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/transfers/resources.ts b/src/transfers/resources.ts index 4590092f2..7a6aa975b 100644 --- a/src/transfers/resources.ts +++ b/src/transfers/resources.ts @@ -7,7 +7,7 @@ export type NativeTokenTransferInput = { data?: Uint8Array; }; -export type ESDTTokenTransferInput = { +export type CustomTokenTransferInput = { receiver: Address; tokenTransfers: TokenTransfer[]; }; diff --git a/src/transfers/transferTransactionsFactory.ts b/src/transfers/transferTransactionsFactory.ts index 852331e31..8bb64c41d 100644 --- a/src/transfers/transferTransactionsFactory.ts +++ b/src/transfers/transferTransactionsFactory.ts @@ -100,7 +100,7 @@ export class TransferTransactionsFactory { }); } - createTransactionForESDTTokenTransfer(sender: IAddress, options: resources.ESDTTokenTransferInput): Transaction { + createTransactionForESDTTokenTransfer(sender: IAddress, options: resources.CustomTokenTransferInput): Transaction { this.ensureConfigIsDefined(); const numberOfTransfers = options.tokenTransfers.length; diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index 1692a36ae..74a0e3085 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -30,7 +30,7 @@ export class TransfersController { async createTransactionForEsdtTokenTransfer( sender: IAccount, nonce: bigint, - options: resources.ESDTTokenTransferInput, + options: resources.CustomTokenTransferInput, ): Promise { const transaction = this.factory.createTransactionForESDTTokenTransfer(sender.address, options); From 586031671179268d109fa128da18f08e3560dbf9 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 18 Nov 2024 14:25:26 +0200 Subject: [PATCH 035/214] Add entrypoints --- src/entrypoints/config.ts | 29 ++++++ src/entrypoints/entrypoints.spec.ts | 119 +++++++++++++++++++++++ src/entrypoints/entrypoints.ts | 142 ++++++++++++++++++++++++++++ src/entrypoints/index.ts | 2 + src/errors.ts | 9 ++ src/index.ts | 1 + src/message.ts | 7 +- 7 files changed, 305 insertions(+), 4 deletions(-) create mode 100644 src/entrypoints/config.ts create mode 100644 src/entrypoints/entrypoints.spec.ts create mode 100644 src/entrypoints/entrypoints.ts create mode 100644 src/entrypoints/index.ts diff --git a/src/entrypoints/config.ts b/src/entrypoints/config.ts new file mode 100644 index 000000000..039fbbc3d --- /dev/null +++ b/src/entrypoints/config.ts @@ -0,0 +1,29 @@ +export interface EntrypointConfig { + networkProviderUrl: string; + networkProviderKind: string; + chainId: string; +} + +export class TestnetEntrypointConfig implements EntrypointConfig { + networkProviderUrl = "https://testnet-api.multiversx.com"; + networkProviderKind = "api"; + chainId = "T"; +} + +export class DevnetEntrypointConfig implements EntrypointConfig { + networkProviderUrl = "https://devnet-api.multiversx.com"; + networkProviderKind = "api"; + chainId = "D"; +} + +export class MainnetEntrypointConfig implements EntrypointConfig { + networkProviderUrl = "https://api.multiversx.com"; + networkProviderKind = "api"; + chainId = "1"; +} + +export class LocalnetEntrypointConfig implements EntrypointConfig { + networkProviderUrl = "http://localhost:7950"; + networkProviderKind = "proxy"; + chainId = "localnet"; +} diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts new file mode 100644 index 000000000..43937c65b --- /dev/null +++ b/src/entrypoints/entrypoints.spec.ts @@ -0,0 +1,119 @@ +import { assert } from "chai"; +import { readFileSync } from "fs"; +import { Account } from "../accounts/account"; +import { Address } from "../address"; +import { loadAbiRegistry, loadTestWallet, TestWallet } from "../testutils"; +import { TransactionComputer } from "../transactionComputer"; +import { DevnetEntrypoint } from "./entrypoints"; + +describe("TestEntrypoint", () => { + const entrypoint = new DevnetEntrypoint(); + let alicePem: TestWallet; + let bobPem: TestWallet; + let txComputer: TransactionComputer; + + before(async function () { + alicePem = await loadTestWallet("alice"); + bobPem = await loadTestWallet("bob"); + txComputer = new TransactionComputer(); + }); + + it("native transfer", async () => { + const controller = entrypoint.createTransfersController(); + const sender = Account.newFromPem(alicePem.pemFileText); + sender.nonce = 77777; + + const transaction = await controller.createTransactionForTransfer( + sender, + BigInt(sender.getNonceThenIncrement().valueOf()), + { + receiver: sender.address, + nativeAmount: BigInt(0), + data: Buffer.from("hello"), + }, + ); + assert.equal( + Buffer.from(transaction.signature).toString("hex"), + "69bc7d1777edd0a901e6cf94830475716205c5efdf2fd44d4be31badead59fc8418b34f0aa3b2c80ba14aed5edd30031757d826af58a1abb690a0bee89ba9309", + ); + }); + + it("contract flow", async function () { + this.timeout(30000); + const abi = await loadAbiRegistry("src/testdata/adder.abi.json"); + const sender = Account.newFromPem(alicePem.pemFileText); + const accountAddress = new Address(sender.address.bech32()); + sender.nonce = await entrypoint.recallAccountNonce(accountAddress); + + const controller = entrypoint.createSmartContractController(abi); + const bytecode = readFileSync("src/testdata/adder.wasm"); + + const transaction = await controller.createTransactionForDeploy( + sender, + BigInt(sender.getNonceThenIncrement().valueOf()), + { + bytecode, + gasLimit: BigInt(10_000_000), + arguments: [0], + }, + ); + + const txHash = await entrypoint.sendTransaction(transaction); + const outcome = await controller.awaitCompletedDeploy(txHash); + + assert.equal(outcome.contracts.length, 1); + + const contractAddress = Address.fromBech32(outcome.contracts[0].address); + + const executeTransaction = await controller.createTransactionForExecute( + sender, + BigInt(sender.getNonceThenIncrement().valueOf()), + { + contract: contractAddress, + gasLimit: BigInt(10_000_000), + function: "add", + arguments: [7], + }, + ); + + const txHashExecute = await entrypoint.sendTransaction(executeTransaction); + await entrypoint.awaitCompletedTransaction(txHashExecute); + + const queryResult = await controller.queryContract(contractAddress, "getSum", []); + assert.equal(queryResult.length, 1); + assert.equal(queryResult[0], 7); + }); + + it("create relayed transaction", async function () { + const transferController = entrypoint.createTransfersController(); + const sender = Account.newFromPem(alicePem.pemFileText); + sender.nonce = 77777; + + const relayer = Account.newFromPem(bobPem.pemFileText); + relayer.nonce = 7; + + const transaction = await transferController.createTransactionForTransfer( + sender, + BigInt(sender.getNonceThenIncrement().valueOf()), + { + receiver: sender.address, + data: Buffer.from("hello"), + }, + ); + const innerTransactionGasLimit = transaction.gasLimit; + transaction.gasLimit = BigInt(0); + transaction.signature = await sender.sign(txComputer.computeBytesForSigning(transaction)); + + const relayedController = entrypoint.createRelayedController(); + const relayedTransaction = relayedController.createRelayedV2Transaction( + relayer, + BigInt(relayer.getNonceThenIncrement().valueOf()), + { + innerTransaction: transaction, + innerTransactionGasLimit, + }, + ); + + assert.equal((await relayedTransaction).chainID, "D"); + }); +}); diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts new file mode 100644 index 000000000..06379dfbd --- /dev/null +++ b/src/entrypoints/entrypoints.ts @@ -0,0 +1,142 @@ +import { AbiRegistry } from "../abi"; +import { AccountController } from "../accountManagement"; +import { IAccount } from "../accounts/interfaces"; +import { Address } from "../address"; +import { DelegationController } from "../delegation"; +import { ErrInvalidNetworkProviderKind } from "../errors"; +import { Message, MessageComputer } from "../message"; +import { ApiNetworkProvider, ProxyNetworkProvider, TransactionOnNetwork } from "../networkProviders"; +import { RelayedController } from "../relayed/relayedController"; +import { SmartContractController } from "../smartContracts/smartContractController"; +import { TokenManagementController } from "../tokenManagement"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionWatcher } from "../transactionWatcher"; +import { TransfersController } from "../transfers/transfersControllers"; +import { UserVerifier } from "../wallet"; +import { DevnetEntrypointConfig, MainnetEntrypointConfig, TestnetEntrypointConfig } from "./config"; + +class NetworkEntrypoint { + private networkProvider: ApiNetworkProvider | ProxyNetworkProvider; + private chainId: string; + + constructor(networkProviderUrl: string, networkProviderKind: string, chainId: string) { + if (networkProviderKind === "proxy") { + this.networkProvider = new ProxyNetworkProvider(networkProviderUrl); + } else if (networkProviderKind === "api") { + this.networkProvider = new ApiNetworkProvider(networkProviderUrl); + } else { + throw new ErrInvalidNetworkProviderKind(); + } + + this.chainId = chainId; + } + + async signTransaction(transaction: Transaction, account: IAccount): Promise { + const txComputer = new TransactionComputer(); + transaction.signature = await account.sign(txComputer.computeBytesForSigning(transaction)); + } + + verifyTransactionSignature(transaction: Transaction): boolean { + const verifier = UserVerifier.fromAddress(Address.fromBech32(transaction.sender)); + const txComputer = new TransactionComputer(); + return verifier.verify(txComputer.computeBytesForVerifying(transaction), transaction.signature); + } + + async signMessage(message: Message, account: IAccount): Promise { + const messageComputer = new MessageComputer(); + message.signature = await account.sign(messageComputer.computeBytesForSigning(message)); + } + + verifyMessageSignature(message: Message): boolean { + if (!message.address) { + throw new Error("`address` property of Message is not set"); + } + + if (!message.signature) { + throw new Error("`signature` property of Message is not set"); + } + + const verifier = UserVerifier.fromAddress(message.address); + const messageComputer = new MessageComputer(); + return verifier.verify(messageComputer.computeBytesForVerifying(message), message.signature); + } + + async recallAccountNonce(address: Address): Promise { + return (await this.networkProvider.getAccount(address)).nonce; + } + + sendTransactions(transactions: Transaction[]): Promise { + return this.networkProvider.sendTransactions(transactions); + } + + sendTransaction(transaction: Transaction): Promise { + return this.networkProvider.sendTransaction(transaction); + } + + async awaitCompletedTransaction(txHash: string): Promise { + const transactionAwaiter = new TransactionWatcher(this.networkProvider); + return transactionAwaiter.awaitCompleted(txHash); + } + + createNetworkProvider(): ApiNetworkProvider | ProxyNetworkProvider { + return this.networkProvider; + } + + createDelegationController(): DelegationController { + return new DelegationController({ chainID: this.chainId, networkProvider: this.networkProvider }); + } + + createAccountController(): AccountController { + return new AccountController({ chainID: this.chainId }); + } + + createRelayedController(): RelayedController { + return new RelayedController({ chainID: this.chainId }); + } + + createSmartContractController(abi?: AbiRegistry): SmartContractController { + return new SmartContractController({ chainID: this.chainId, networkProvider: this.networkProvider, abi }); + } + + createTokenManagementController(): TokenManagementController { + return new TokenManagementController({ chainID: this.chainId, networkProvider: this.networkProvider }); + } + + createTransfersController(): TransfersController { + return new TransfersController({ chainID: this.chainId }); + } +} + +export class TestnetEntrypoint extends NetworkEntrypoint { + constructor(url?: string, kind?: string) { + const entrypointConfig = new TestnetEntrypointConfig(); + super( + url || entrypointConfig.networkProviderUrl, + kind || entrypointConfig.networkProviderKind, + entrypointConfig.chainId, + ); + } +} + +export class DevnetEntrypoint extends NetworkEntrypoint { + constructor(url?: string, kind?: string) { + const entrypointConfig = new DevnetEntrypointConfig(); + super( + url || entrypointConfig.networkProviderUrl, + kind || entrypointConfig.networkProviderKind, + entrypointConfig.chainId, + ); + } +} + +export class MainnetEntrypoint extends NetworkEntrypoint { + constructor(url?: string, kind?: string) { + const entrypointConfig = new MainnetEntrypointConfig(); + super( + url || entrypointConfig.networkProviderUrl, + kind || entrypointConfig.networkProviderKind, + entrypointConfig.chainId, + ); + } +} diff --git a/src/entrypoints/index.ts b/src/entrypoints/index.ts new file mode 100644 index 000000000..311ba2137 --- /dev/null +++ b/src/entrypoints/index.ts @@ -0,0 +1,2 @@ +export * from "./config"; +export * from "./entrypoints"; diff --git a/src/errors.ts b/src/errors.ts index a0a47f0ab..67878c12f 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -448,3 +448,12 @@ export class ErrContractQuery extends Err { super(originalError.message.replace("executeQuery:", "")); } } + +/** + * Signals that the network provider provided is not valid + */ +export class ErrInvalidNetworkProviderKind extends Err { + public constructor() { + super("Invalid network provider kind. Choose between `api` and `proxy`."); + } +} diff --git a/src/index.ts b/src/index.ts index 7207227d3..2142dde9f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,7 @@ export * from "./asyncTimer"; export * from "./config"; export * from "./converters"; export * from "./delegation"; +export * from "./entrypoints"; export * from "./errors"; export * from "./gasEstimator"; export * from "./interface"; diff --git a/src/message.ts b/src/message.ts index 05c047abf..8b2dbfce1 100644 --- a/src/message.ts +++ b/src/message.ts @@ -1,6 +1,5 @@ -import { IAddress } from "./interface"; -import { DEFAULT_MESSAGE_VERSION, MESSAGE_PREFIX, SDK_JS_SIGNER, UNKNOWN_SIGNER } from "./constants"; import { Address } from "./address"; +import { DEFAULT_MESSAGE_VERSION, MESSAGE_PREFIX, SDK_JS_SIGNER, UNKNOWN_SIGNER } from "./constants"; const createKeccakHash = require("keccak"); @@ -16,7 +15,7 @@ export class Message { /** * Address of the wallet that performed the signing operation. */ - public address?: IAddress; + public address?: Address; /** * Number representing the message version. */ @@ -29,7 +28,7 @@ export class Message { constructor(options: { data: Uint8Array; signature?: Uint8Array; - address?: IAddress; + address?: Address; version?: number; signer?: string; }) { From 8882e4c8d7322dd4894b49d0edd194f143e56865 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 19 Nov 2024 10:32:18 +0200 Subject: [PATCH 036/214] Code review follow up --- src/entrypoints/config.ts | 71 ++++++++++++++++++++++------- src/entrypoints/entrypoints.spec.ts | 8 ++-- src/entrypoints/entrypoints.ts | 42 ++++++++--------- 3 files changed, 81 insertions(+), 40 deletions(-) diff --git a/src/entrypoints/config.ts b/src/entrypoints/config.ts index 039fbbc3d..479cd1e2c 100644 --- a/src/entrypoints/config.ts +++ b/src/entrypoints/config.ts @@ -4,26 +4,65 @@ export interface EntrypointConfig { chainId: string; } -export class TestnetEntrypointConfig implements EntrypointConfig { - networkProviderUrl = "https://testnet-api.multiversx.com"; - networkProviderKind = "api"; - chainId = "T"; +export class TestnetEntrypointConfig { + networkProviderUrl: string; + networkProviderKind: string; + chainId: string; + + constructor({ + networkProviderUrl = "https://testnet-api.multiversx.com", + networkProviderKind = "api", + chainId = "T", + }: Partial = {}) { + this.networkProviderUrl = networkProviderUrl; + this.networkProviderKind = networkProviderKind; + this.chainId = chainId; + } } -export class DevnetEntrypointConfig implements EntrypointConfig { - networkProviderUrl = "https://devnet-api.multiversx.com"; - networkProviderKind = "api"; - chainId = "D"; +export class DevnetEntrypointConfig { + networkProviderUrl: string; + networkProviderKind: string; + chainId: string; + constructor({ + networkProviderUrl = "https://devnet-api.multiversx.com", + networkProviderKind = "api", + chainId = "D", + }: Partial = {}) { + this.networkProviderUrl = networkProviderUrl; + this.networkProviderKind = networkProviderKind; + this.chainId = chainId; + } } -export class MainnetEntrypointConfig implements EntrypointConfig { - networkProviderUrl = "https://api.multiversx.com"; - networkProviderKind = "api"; - chainId = "1"; +export class MainnetEntrypointConfig { + networkProviderUrl: string; + networkProviderKind: string; + chainId: string; + + constructor({ + networkProviderUrl = "https://api.multiversx.com", + networkProviderKind = "api", + chainId = "1", + }: Partial = {}) { + this.networkProviderUrl = networkProviderUrl; + this.networkProviderKind = networkProviderKind; + this.chainId = chainId; + } } -export class LocalnetEntrypointConfig implements EntrypointConfig { - networkProviderUrl = "http://localhost:7950"; - networkProviderKind = "proxy"; - chainId = "localnet"; +export class LocalnetEntrypointConfig { + networkProviderUrl: string; + networkProviderKind: string; + chainId: string; + + constructor({ + networkProviderUrl = "http://localhost:7950", + networkProviderKind = "proxy", + chainId = "localnet", + }: Partial = {}) { + this.networkProviderUrl = networkProviderUrl; + this.networkProviderKind = networkProviderKind; + this.chainId = chainId; + } } diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 43937c65b..d088e3952 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -42,7 +42,7 @@ describe("TestEntrypoint", () => { this.timeout(30000); const abi = await loadAbiRegistry("src/testdata/adder.abi.json"); const sender = Account.newFromPem(alicePem.pemFileText); - const accountAddress = new Address(sender.address.bech32()); + const accountAddress = new Address(sender.address); sender.nonce = await entrypoint.recallAccountNonce(accountAddress); const controller = entrypoint.createSmartContractController(abi); @@ -105,7 +105,7 @@ describe("TestEntrypoint", () => { transaction.signature = await sender.sign(txComputer.computeBytesForSigning(transaction)); const relayedController = entrypoint.createRelayedController(); - const relayedTransaction = relayedController.createRelayedV2Transaction( + const relayedTransaction = await relayedController.createRelayedV2Transaction( relayer, BigInt(relayer.getNonceThenIncrement().valueOf()), { @@ -114,6 +114,8 @@ describe("TestEntrypoint", () => { }, ); - assert.equal((await relayedTransaction).chainID, "D"); + assert.equal(relayedTransaction.chainID, "D"); + assert.deepEqual(transaction.data, Buffer.from("hello")); + assert.equal(relayedTransaction.gasLimit, 0n); }); }); diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 06379dfbd..4dc8adbd6 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -20,16 +20,16 @@ class NetworkEntrypoint { private networkProvider: ApiNetworkProvider | ProxyNetworkProvider; private chainId: string; - constructor(networkProviderUrl: string, networkProviderKind: string, chainId: string) { - if (networkProviderKind === "proxy") { - this.networkProvider = new ProxyNetworkProvider(networkProviderUrl); - } else if (networkProviderKind === "api") { - this.networkProvider = new ApiNetworkProvider(networkProviderUrl); + constructor(options: { networkProviderUrl: string; networkProviderKind: string; chainId: string }) { + if (options.networkProviderKind === "proxy") { + this.networkProvider = new ProxyNetworkProvider(options.networkProviderUrl); + } else if (options.networkProviderKind === "api") { + this.networkProvider = new ApiNetworkProvider(options.networkProviderUrl); } else { throw new ErrInvalidNetworkProviderKind(); } - this.chainId = chainId; + this.chainId = options.chainId; } async signTransaction(transaction: Transaction, account: IAccount): Promise { @@ -111,32 +111,32 @@ class NetworkEntrypoint { export class TestnetEntrypoint extends NetworkEntrypoint { constructor(url?: string, kind?: string) { const entrypointConfig = new TestnetEntrypointConfig(); - super( - url || entrypointConfig.networkProviderUrl, - kind || entrypointConfig.networkProviderKind, - entrypointConfig.chainId, - ); + super({ + networkProviderUrl: url || entrypointConfig.networkProviderUrl, + networkProviderKind: kind || entrypointConfig.networkProviderKind, + chainId: entrypointConfig.chainId, + }); } } export class DevnetEntrypoint extends NetworkEntrypoint { constructor(url?: string, kind?: string) { const entrypointConfig = new DevnetEntrypointConfig(); - super( - url || entrypointConfig.networkProviderUrl, - kind || entrypointConfig.networkProviderKind, - entrypointConfig.chainId, - ); + super({ + networkProviderUrl: url || entrypointConfig.networkProviderUrl, + networkProviderKind: kind || entrypointConfig.networkProviderKind, + chainId: entrypointConfig.chainId, + }); } } export class MainnetEntrypoint extends NetworkEntrypoint { constructor(url?: string, kind?: string) { const entrypointConfig = new MainnetEntrypointConfig(); - super( - url || entrypointConfig.networkProviderUrl, - kind || entrypointConfig.networkProviderKind, - entrypointConfig.chainId, - ); + super({ + networkProviderUrl: url || entrypointConfig.networkProviderUrl, + networkProviderKind: kind || entrypointConfig.networkProviderKind, + chainId: entrypointConfig.chainId, + }); } } From dd67b79258de14848cc15f16fd9a480a54d9f5da Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 19 Nov 2024 10:54:30 +0200 Subject: [PATCH 037/214] Fix test for relayed controller --- src/entrypoints/entrypoints.spec.ts | 10 +++++++--- src/relayed/relayedController.ts | 1 - 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index d088e3952..42b2241e6 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -113,9 +113,13 @@ describe("TestEntrypoint", () => { innerTransactionGasLimit, }, ); - assert.equal(relayedTransaction.chainID, "D"); - assert.deepEqual(transaction.data, Buffer.from("hello")); - assert.equal(relayedTransaction.gasLimit, 0n); + assert.deepEqual( + relayedTransaction.data, + Buffer.from( + "relayedTxV2@0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1@012fd1@68656c6c6f@c1eed3ac766d6b94aa53a1348d38eac8db60be0a1b2d0873247b61b8b25bbcb45bf9c1518227bcadd5044d4c027bdb935e0164243b2b2df9a5b250a10aca260e", + ), + ); + assert.equal(relayedTransaction.gasLimit, 442000n); }); }); diff --git a/src/relayed/relayedController.ts b/src/relayed/relayedController.ts index 3a219c470..558cbb95f 100644 --- a/src/relayed/relayedController.ts +++ b/src/relayed/relayedController.ts @@ -41,7 +41,6 @@ export class RelayedController { const transaction = this.factory.createRelayedV2Transaction(sender.address, options); transaction.nonce = nonce; - transaction.gasLimit = BigInt(0); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; From aa68ee47efa43b109a206b27bf41fe8caa76f540 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 19 Nov 2024 14:07:30 +0200 Subject: [PATCH 038/214] Remove transation outcome and fix changes --- src/abi/resultsParser.spec.ts | 2 +- src/abi/typesystem/abiRegistry.ts | 1 + src/converters/transactionsConverter.ts | 63 +-- src/converters/transactionsConverters.spec.ts | 173 -------- src/delegation/delegationController.ts | 4 +- ...elegationTransactionsOutcomeParser.spec.ts | 60 ++- .../delegationTransactionsOutcomeParser.ts | 39 +- src/entrypoints/entrypoints.ts | 3 +- src/index.ts | 1 + src/interface.ts | 2 +- src/interfaceOfNetwork.ts | 5 +- src/networkProviders/apiNetworkProvider.ts | 2 +- src/networkProviders/contractResults.ts | 7 +- src/networkProviders/index.ts | 11 +- src/networkProviders/interface.ts | 2 +- src/networkProviders/proxyNetworkProvider.ts | 2 +- src/smartContracts/smartContractController.ts | 4 +- ...tTransactionsOutcomeParser.dev.net.spec.ts | 8 - ...tContractTransactionsOutcomeParser.spec.ts | 113 +---- .../smartContractTransactionsOutcomeParser.ts | 99 +---- src/testutils/mockNetworkProvider.ts | 3 +- src/tokenManagement/resources.ts | 3 +- .../tokenManagementController.ts | 2 +- ...anagementTransactionsOutcomeParser.spec.ts | 413 +++++++++++------- ...okenManagementTransactionsOutcomeParser.ts | 136 ++---- src/transaction.ts | 3 +- .../transactionEvents.ts | 5 +- src/{networkProviders => }/transactionLogs.ts | 7 +- src/transactionWatcher.spec.ts | 3 +- src/transactionWatcher.ts | 2 +- src/{networkProviders => }/transactions.ts | 10 +- .../resources.spec.ts | 35 +- src/transactionsOutcomeParsers/resources.ts | 57 +-- .../transactionEventsParser.spec.ts | 52 +-- .../transactionEventsParser.ts | 16 +- 35 files changed, 464 insertions(+), 884 deletions(-) rename src/{networkProviders => }/transactionEvents.ts (95%) rename src/{networkProviders => }/transactionLogs.ts (89%) rename src/{networkProviders => }/transactions.ts (92%) diff --git a/src/abi/resultsParser.spec.ts b/src/abi/resultsParser.spec.ts index c21234d1c..6cc08e449 100644 --- a/src/abi/resultsParser.spec.ts +++ b/src/abi/resultsParser.spec.ts @@ -10,9 +10,9 @@ import { TransactionEventOnNetwork, TransactionEventTopic, TransactionLogsOnNetwork, - TransactionOnNetwork, } from "../networkProviders"; import { loadAbiRegistry } from "../testutils"; +import { TransactionOnNetwork } from "../transactions"; import { ArgSerializer } from "./argSerializer"; import { ResultsParser } from "./resultsParser"; import { ReturnCode } from "./returnCode"; diff --git a/src/abi/typesystem/abiRegistry.ts b/src/abi/typesystem/abiRegistry.ts index 60a6c46ff..f57c52102 100644 --- a/src/abi/typesystem/abiRegistry.ts +++ b/src/abi/typesystem/abiRegistry.ts @@ -133,6 +133,7 @@ export class AbiRegistry { } getEvent(name: string): EventDefinition { + console.log({ name }); const result = this.events.find((e) => e.identifier == name); guardValueIsSetWithMessage(`event [${name}] not found`, result); return result!; diff --git a/src/converters/transactionsConverter.ts b/src/converters/transactionsConverter.ts index 5d47886e3..423f6026e 100644 --- a/src/converters/transactionsConverter.ts +++ b/src/converters/transactionsConverter.ts @@ -1,14 +1,9 @@ -import { ResultsParser } from "../abi"; import { IPlainTransactionObject, ITransaction } from "../interface"; -import { IContractResultItem, ITransactionEvent, ITransactionOnNetwork } from "../interfaceOfNetwork"; +import { IContractResultItem, ITransactionEvent } from "../interfaceOfNetwork"; import { Transaction } from "../transaction"; -import { - SmartContractCallOutcome, - SmartContractResult, - TransactionEvent, - TransactionLogs, - TransactionOutcome, -} from "../transactionsOutcomeParsers/resources"; +import { TransactionEvent, TransactionEventData, TransactionEventTopic } from "../transactionEvents"; +import { TransactionLogs } from "../transactionLogs"; +import { SmartContractResult } from "../transactionsOutcomeParsers/resources"; export class TransactionsConverter { public transactionToPlainObject(transaction: ITransaction): IPlainTransactionObject { @@ -71,42 +66,6 @@ export class TransactionsConverter { return Buffer.from(value || "", "hex"); } - /** - * @deprecated Where {@link TransactionOutcome} was needed (throughout the SDK), pass the {@link ITransactionOnNetwork} object instead. - * - * Summarizes the outcome of a transaction on the network, and maps it to the "standard" resources (according to the sdk-specs). - * - * In the future, this converter function will become obsolete, - * as the impedance mismatch between the network components and the "core" components will be reduced. - */ - public transactionOnNetworkToOutcome(transactionOnNetwork: ITransactionOnNetwork): TransactionOutcome { - // In the future, this will not be needed because the transaction, as returned from the API, - // will hold the data corresponding to the direct smart contract call outcome (in case of smart contract calls). - const legacyResultsParser = new ResultsParser(); - const callOutcomeBundle = legacyResultsParser.parseUntypedOutcome(transactionOnNetwork); - const callOutcome = new SmartContractCallOutcome({ - function: transactionOnNetwork.function, - returnCode: callOutcomeBundle.returnCode.toString(), - returnMessage: callOutcomeBundle.returnMessage, - returnDataParts: callOutcomeBundle.values, - }); - - const contractResults = transactionOnNetwork.contractResults.items.map((result) => - this.smartContractResultOnNetworkToSmartContractResult(result), - ); - - const logs = new TransactionLogs({ - address: transactionOnNetwork.logs.address.bech32(), - events: transactionOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)), - }); - - return new TransactionOutcome({ - logs: logs, - smartContractResults: contractResults, - directSmartContractCallOutcome: callOutcome, - }); - } - private smartContractResultOnNetworkToSmartContractResult( resultOnNetwork: IContractResultItem, ): SmartContractResult { @@ -115,7 +74,7 @@ export class TransactionsConverter { receiver: resultOnNetwork.receiver.bech32(), data: Buffer.from(resultOnNetwork.data), logs: new TransactionLogs({ - address: resultOnNetwork.logs.address.bech32(), + address: resultOnNetwork.logs.address, events: resultOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)), }), }); @@ -126,19 +85,21 @@ export class TransactionsConverter { // After Sirius, the "additionalData" field includes the payload of the legacy "data" field, as well (as its first element): // https://github.com/multiversx/mx-chain-go/blob/v1.6.18/process/transactionLog/process.go#L159 const legacyData = eventOnNetwork.dataPayload?.valueOf() || Buffer.from(eventOnNetwork.data || ""); - const dataItems = eventOnNetwork.additionalData?.map((data) => Buffer.from(data.valueOf())) || []; + const dataItems = + eventOnNetwork.additionalData?.map((data) => new TransactionEventData(Buffer.from(data.valueOf()))) || []; if (dataItems.length === 0) { if (legacyData.length) { - dataItems.push(Buffer.from(legacyData)); + dataItems.push(new TransactionEventData(Buffer.from(legacyData))); } } return new TransactionEvent({ - address: eventOnNetwork.address.bech32(), + address: eventOnNetwork.address, identifier: eventOnNetwork.identifier, - topics: eventOnNetwork.topics.map((topic) => Buffer.from(topic.hex(), "hex")), - dataItems: dataItems, + topics: eventOnNetwork.topics.map((topic) => new TransactionEventTopic(topic.hex())), + dataPayload: new TransactionEventData(Buffer.from(legacyData)), + additionalData: dataItems, }); } } diff --git a/src/converters/transactionsConverters.spec.ts b/src/converters/transactionsConverters.spec.ts index e491ab57a..2d91adf06 100644 --- a/src/converters/transactionsConverters.spec.ts +++ b/src/converters/transactionsConverters.spec.ts @@ -1,22 +1,5 @@ -import { - ContractResultItem, - ContractResults, - TransactionEventData, - TransactionEventOnNetwork, - TransactionEventTopic, - TransactionLogsOnNetwork, - TransactionOnNetwork, -} from "../networkProviders"; import { assert } from "chai"; -import { Address } from "../address"; import { Transaction } from "../transaction"; -import { - SmartContractCallOutcome, - SmartContractResult, - TransactionEvent, - TransactionLogs, - TransactionOutcome, -} from "../transactionsOutcomeParsers/resources"; import { TransactionsConverter } from "./transactionsConverter"; describe("test transactions converter", async () => { @@ -61,160 +44,4 @@ describe("test transactions converter", async () => { guardianSignature: undefined, }); }); - - it("converts transaction on network to transaction outcome", () => { - const converter = new TransactionsConverter(); - - const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 7, - function: "hello", - logs: new TransactionLogsOnNetwork({ - address: Address.fromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"), - events: [ - new TransactionEventOnNetwork({ - identifier: "foobar", - topics: [], - dataPayload: new TransactionEventData(Buffer.from("foo")), - additionalData: [], - }), - ], - }), - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 8, - data: "@6f6b@2a", - logs: new TransactionLogsOnNetwork({ - address: Address.fromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"), - events: [ - new TransactionEventOnNetwork({ - identifier: "writeLog", - topics: [ - new TransactionEventTopic( - // '@too much gas provided for processing: gas provided = 596384500, gas used = 733010' - "QHRvbyBtdWNoIGdhcyBwcm92aWRlZCBmb3IgcHJvY2Vzc2luZzogZ2FzIHByb3ZpZGVkID0gNTk2Mzg0NTAwLCBnYXMgdXNlZCA9IDczMzAxMA==", - ), - ], - dataPayload: TransactionEventData.fromBase64("QDZmNmI="), - }), - ], - }), - }), - ]), - }); - - const actualTransactionOutcome = converter.transactionOnNetworkToOutcome(transactionOnNetwork); - const expectedTransactionOutcome = new TransactionOutcome({ - directSmartContractCallOutcome: new SmartContractCallOutcome({ - function: "hello", - returnCode: "ok", - returnMessage: "ok", - returnDataParts: [Buffer.from([42])], - }), - smartContractResults: [ - new SmartContractResult({ - sender: "", - receiver: "", - data: Buffer.from("@6f6b@2a"), - logs: { - address: "erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8", - events: [ - new TransactionEvent({ - address: "", - identifier: "writeLog", - topics: [ - Buffer.from( - "@too much gas provided for processing: gas provided = 596384500, gas used = 733010", - ), - ], - dataItems: [Buffer.from("QDZmNmI=", "base64")], - }), - ], - }, - }), - ], - logs: new TransactionLogs({ - address: "erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8", - events: [ - new TransactionEvent({ - address: "", - identifier: "foobar", - topics: [], - dataItems: [Buffer.from("foo")], - }), - ], - }), - }); - - assert.deepEqual(actualTransactionOutcome, expectedTransactionOutcome); - }); - - it("converts transaction on network to transaction outcome (with signal error)", () => { - const converter = new TransactionsConverter(); - - const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 42, - function: "hello", - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 42, - data: "@657865637574696f6e206661696c6564", - logs: new TransactionLogsOnNetwork({ - address: Address.fromBech32("erd1qqqqqqqqqqqqqpgqj8k976l59n7fyth8ujl4as5uyn3twn0ha0wsge5r5x"), - events: [ - new TransactionEventOnNetwork({ - address: Address.fromBech32( - "erd1qqqqqqqqqqqqqpgqj8k976l59n7fyth8ujl4as5uyn3twn0ha0wsge5r5x", - ), - identifier: "signalError", - topics: [ - new TransactionEventTopic("XmC5/yOF6ie6DD2kaJd5qPc2Ss7h2w7nvuWaxmCiiXQ="), - new TransactionEventTopic("aW5zdWZmaWNpZW50IGZ1bmRz"), - ], - dataPayload: new TransactionEventData(Buffer.from("@657865637574696f6e206661696c6564")), - additionalData: [ - new TransactionEventData(Buffer.from("@657865637574696f6e206661696c6564")), - new TransactionEventData(Buffer.from("foobar")), - ], - }), - ], - }), - }), - ]), - }); - - const actualTransactionOutcome = converter.transactionOnNetworkToOutcome(transactionOnNetwork); - const expectedTransactionOutcome = new TransactionOutcome({ - directSmartContractCallOutcome: new SmartContractCallOutcome({ - function: "hello", - returnCode: "execution failed", - returnMessage: "execution failed", - returnDataParts: [], - }), - smartContractResults: [ - new SmartContractResult({ - sender: "", - receiver: "", - data: Buffer.from("@657865637574696f6e206661696c6564"), - logs: { - address: "erd1qqqqqqqqqqqqqpgqj8k976l59n7fyth8ujl4as5uyn3twn0ha0wsge5r5x", - events: [ - new TransactionEvent({ - address: "erd1qqqqqqqqqqqqqpgqj8k976l59n7fyth8ujl4as5uyn3twn0ha0wsge5r5x", - identifier: "signalError", - topics: [ - Address.fromBech32( - "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", - ).getPublicKey(), - Buffer.from("insufficient funds"), - ], - dataItems: [Buffer.from("@657865637574696f6e206661696c6564"), Buffer.from("foobar")], - }), - ], - }, - }), - ], - }); - - assert.deepEqual(actualTransactionOutcome, expectedTransactionOutcome); - }); }); diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index 01ebbef58..a37fabec5 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -1,8 +1,8 @@ import { IAccount } from "../accounts/interfaces"; -import { ITransactionOnNetwork } from "../interfaceOfNetwork"; import { INetworkProvider } from "../networkProviders/interface"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; +import { TransactionOnNetwork } from "../transactions"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; @@ -42,7 +42,7 @@ export class DelegationController { return this.parseCreateNewDelegationContract(transaction); } - parseCreateNewDelegationContract(transactionOnNetwork: ITransactionOnNetwork): { contractAddress: string }[] { + parseCreateNewDelegationContract(transactionOnNetwork: TransactionOnNetwork): { contractAddress: string }[] { return this.parser.parseCreateNewDelegationContract(transactionOnNetwork); } diff --git a/src/delegation/delegationTransactionsOutcomeParser.spec.ts b/src/delegation/delegationTransactionsOutcomeParser.spec.ts index aa043b548..a5e6b33ab 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.spec.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.spec.ts @@ -1,12 +1,9 @@ import { assert } from "chai"; import { Address } from "../address"; -import { b64TopicsToBytes } from "../testutils"; -import { - SmartContractResult, - TransactionEvent, - TransactionLogs, - TransactionOutcome, -} from "../transactionsOutcomeParsers/resources"; +import { ContractResultItem, ContractResults } from "../networkProviders"; +import { TransactionEvent, TransactionEventTopic } from "../transactionEvents"; +import { TransactionLogs } from "../transactionLogs"; +import { TransactionOnNetwork } from "../transactions"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; describe("test delegation transactions outcome parser", () => { @@ -15,54 +12,53 @@ describe("test delegation transactions outcome parser", () => { it("should test parseCreateNewDelegationContract ", () => { const contractAddress = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqy8lllls62y8s5"); let encodedTopics = [ - "Q8M8GTdWSAAA", - "Q8M8GTdWSAAA", - "AQ==", - "Q8M8GTdWSAAA", - "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABD///8=", + new TransactionEventTopic("Q8M8GTdWSAAA"), + new TransactionEventTopic("Q8M8GTdWSAAA"), + new TransactionEventTopic("AQ=="), + new TransactionEventTopic("Q8M8GTdWSAAA"), + new TransactionEventTopic("AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABD///8="), ]; const delegateEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "delegate", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); encodedTopics = [ - "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABD///8=", - "PDXX6ssamaSgzKpTfvDMCuEJ9B9sK0AiA+Yzv7sHH1w=", + new TransactionEventTopic("AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABD///8="), + new TransactionEventTopic("PDXX6ssamaSgzKpTfvDMCuEJ9B9sK0AiA+Yzv7sHH1w="), ]; const scDeployEvent = new TransactionEvent({ - address: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqy8lllls62y8s5", + address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqy8lllls62y8s5"), identifier: "SCDeploy", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const logs = new TransactionLogs({ events: [delegateEvent, scDeployEvent] }); - encodedTopics = ["b2g6sUl6beG17FCUIkFwCOTGJjoJJi5SjkP2077e6xA="]; + encodedTopics = [new TransactionEventTopic("b2g6sUl6beG17FCUIkFwCOTGJjoJJi5SjkP2077e6xA=")]; const scResultEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "completedTxEvent", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const scResultLog = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [scResultEvent], }); - const scResult = new SmartContractResult({ - sender: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6", - receiver: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", - data: Buffer.from( - "QDZmNmJAMDAwMDAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMGZmZmZmZg==", - "base64", - ), - logs: scResultLog, - }); + const scResult = new ContractResults([ + new ContractResultItem({ + sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"), + receiver: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + data: "QDZmNmJAMDAwMDAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMGZmZmZmZg==", + logs: scResultLog, + }), + ]); - const txOutcome = new TransactionOutcome({ smartContractResults: [scResult], logs: logs }); + const txOutcome = new TransactionOnNetwork({ contractResults: scResult, logs: logs }); const outcome = parser.parseCreateNewDelegationContract(txOutcome); diff --git a/src/delegation/delegationTransactionsOutcomeParser.ts b/src/delegation/delegationTransactionsOutcomeParser.ts index a267f8e8b..402853f67 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.ts @@ -1,17 +1,13 @@ import { Address } from "../address"; -import { TransactionsConverter } from "../converters/transactionsConverter"; import { ErrParseTransactionOutcome } from "../errors"; -import { ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { TransactionEvent, TransactionOutcome, findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; +import { TransactionEvent } from "../transactionEvents"; +import { TransactionOnNetwork } from "../transactions"; +import { findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; export class DelegationTransactionsOutcomeParser { constructor() {} - parseCreateNewDelegationContract( - transaction: TransactionOutcome | ITransactionOnNetwork, - ): { contractAddress: string }[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseCreateNewDelegationContract(transaction: TransactionOnNetwork): { contractAddress: string }[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "SCDeploy"); @@ -19,39 +15,22 @@ export class DelegationTransactionsOutcomeParser { return events.map((event) => ({ contractAddress: this.extractContractAddress(event) })); } - /** - * Temporary workaround, until "TransactionOnNetwork" completely replaces "TransactionOutcome". - */ - private ensureTransactionOutcome(transaction: TransactionOutcome | ITransactionOnNetwork): TransactionOutcome { - if ("hash" in transaction) { - return new TransactionsConverter().transactionOnNetworkToOutcome(transaction); - } - - return transaction; - } - private ensureNoError(transactionEvents: TransactionEvent[]) { for (const event of transactionEvents) { if (event.identifier == "signalError") { - const data = Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; - const message = this.decodeTopicAsString(event.topics[1]); + const data = event.dataPayload.toString(); + const message = event.topics[1].toString(); - throw new ErrParseTransactionOutcome( - `encountered signalError: ${message} (${Buffer.from(data, "hex").toString()})`, - ); + throw new ErrParseTransactionOutcome(`encountered signalError: ${message} (${data})`); } } } private extractContractAddress(event: TransactionEvent): string { - if (!event.topics[0]?.length) { + if (!event.topics[0]?.toString().length) { return ""; } const address = Buffer.from(event.topics[0]); - return Address.fromBuffer(address).bech32(); - } - - private decodeTopicAsString(topic: Uint8Array): string { - return Buffer.from(topic).toString(); + return new Address(address).bech32(); } } diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 4dc8adbd6..b3a3167b5 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -5,12 +5,13 @@ import { Address } from "../address"; import { DelegationController } from "../delegation"; import { ErrInvalidNetworkProviderKind } from "../errors"; import { Message, MessageComputer } from "../message"; -import { ApiNetworkProvider, ProxyNetworkProvider, TransactionOnNetwork } from "../networkProviders"; +import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { RelayedController } from "../relayed/relayedController"; import { SmartContractController } from "../smartContracts/smartContractController"; import { TokenManagementController } from "../tokenManagement"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; +import { TransactionOnNetwork } from "../transactions"; import { TransactionWatcher } from "../transactionWatcher"; import { TransfersController } from "../transfers/transfersControllers"; import { UserVerifier } from "../wallet"; diff --git a/src/index.ts b/src/index.ts index 2142dde9f..9c411e776 100644 --- a/src/index.ts +++ b/src/index.ts @@ -35,6 +35,7 @@ export * from "./tokens"; export * from "./transaction"; export * from "./transactionComputer"; export * from "./transactionPayload"; +export * from "./transactions"; export * from "./transactionsOutcomeParsers"; export * from "./transactionWatcher"; export * from "./transfers"; diff --git a/src/interface.ts b/src/interface.ts index 5adf540bd..46a22c3c4 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import { TransactionOnNetwork } from "./networkProviders"; +import { TransactionOnNetwork } from "./transactions"; export interface ITransactionFetcher { /** diff --git a/src/interfaceOfNetwork.ts b/src/interfaceOfNetwork.ts index eaee206aa..8d5303773 100644 --- a/src/interfaceOfNetwork.ts +++ b/src/interfaceOfNetwork.ts @@ -1,3 +1,4 @@ +import { Address } from "./address"; import { IAccountBalance, IAddress } from "./interface"; export interface IAccountOnNetwork { @@ -67,7 +68,7 @@ export interface IContractReturnCode { } export interface ITransactionLogs { - address: IAddress; + address: Address; events: ITransactionEvent[]; findSingleOrNoneEvent( @@ -77,7 +78,7 @@ export interface ITransactionLogs { } export interface ITransactionEvent { - readonly address: IAddress; + readonly address: Address; readonly identifier: string; readonly topics: ITransactionEventTopic[]; readonly data: string; diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index bf9cf6858..12653f90f 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,4 +1,5 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; +import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactions"; import { getAxios } from "../utils"; import { numberToPaddedHex } from "../utils.codec"; import { AccountOnNetwork, GuardianData } from "./accounts"; @@ -16,7 +17,6 @@ import { PairOnNetwork } from "./pairs"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; -import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "./transactions"; import { TransactionStatus } from "./transactionStatus"; import { extendUserAgentIfBackend } from "./userAgent"; diff --git a/src/networkProviders/contractResults.ts b/src/networkProviders/contractResults.ts index a7f2a3674..d8afa3fa5 100644 --- a/src/networkProviders/contractResults.ts +++ b/src/networkProviders/contractResults.ts @@ -1,6 +1,5 @@ import { Address } from "../address"; -import { IAddress } from "./interface"; -import { TransactionLogs } from "./transactionLogs"; +import { TransactionLogs } from "../transactionLogs"; export class ContractResults { readonly items: ContractResultItem[]; @@ -28,8 +27,8 @@ export class ContractResultItem { hash: string = ""; nonce: number = 0; value: string = ""; - receiver: IAddress = Address.empty(); - sender: IAddress = Address.empty(); + receiver: Address = Address.empty(); + sender: Address = Address.empty(); data: string = ""; previousHash: string = ""; originalHash: string = ""; diff --git a/src/networkProviders/index.ts b/src/networkProviders/index.ts index 99c22853f..1d0f5567a 100644 --- a/src/networkProviders/index.ts +++ b/src/networkProviders/index.ts @@ -1,17 +1,16 @@ export { ApiNetworkProvider } from "./apiNetworkProvider"; export { ProxyNetworkProvider } from "./proxyNetworkProvider"; -export { AccountOnNetwork } from "./accounts"; -export { ContractQueryResponse } from "./contractQueryResponse"; -export { ContractResultItem, ContractResults } from "./contractResults"; export { TransactionEventData, TransactionEvent as TransactionEventOnNetwork, TransactionEventTopic, -} from "./transactionEvents"; -export { TransactionLogs as TransactionLogsOnNetwork } from "./transactionLogs"; +} from "../transactionEvents"; +export { TransactionLogs as TransactionLogsOnNetwork } from "../transactionLogs"; +export { AccountOnNetwork } from "./accounts"; +export { ContractQueryResponse } from "./contractQueryResponse"; +export { ContractResultItem, ContractResults } from "./contractResults"; export { TransactionReceipt } from "./transactionReceipt"; -export { TransactionOnNetwork } from "./transactions"; export { TransactionStatus } from "./transactionStatus"; export { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index eb73db286..c43fdb8dc 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,4 +1,5 @@ import { ITransaction as ITransactionAsInSpecs } from "../interface"; +import { TransactionOnNetwork } from "../transactions"; import { AccountOnNetwork } from "./accounts"; import { ContractQueryResponse } from "./contractQueryResponse"; import { NetworkConfig } from "./networkConfig"; @@ -7,7 +8,6 @@ import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; -import { TransactionOnNetwork } from "./transactions"; import { TransactionStatus } from "./transactionStatus"; /** diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 5b2059752..a42915aef 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,4 +1,5 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; +import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactions"; import { getAxios } from "../utils"; import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; @@ -13,7 +14,6 @@ import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; -import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "./transactions"; import { TransactionStatus } from "./transactionStatus"; import { extendUserAgentIfBackend } from "./userAgent"; diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index a469b39d0..1b0b64f1e 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -2,11 +2,11 @@ import { AbiRegistry } from "../abi"; import { IAccount } from "../accounts/interfaces"; import { QueryRunnerAdapter } from "../adapters"; import { IAddress } from "../interface"; -import { ITransactionOnNetwork } from "../interfaceOfNetwork"; import { INetworkProvider } from "../networkProviders/interface"; import { SmartContractQueriesController } from "../smartContractQueriesController"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; +import { TransactionOnNetwork } from "../transactions"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { SmartContractTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; import { TransactionWatcher } from "../transactionWatcher"; @@ -89,7 +89,7 @@ export class SmartContractController { }); } - parseDeploy(transactionOnNetwork: ITransactionOnNetwork): resources.SmartContractDeployOutcome { + parseDeploy(transactionOnNetwork: TransactionOnNetwork): resources.SmartContractDeployOutcome { return this.parser.parseDeploy({ transactionOnNetwork }); } } diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts index 6eb10aa4f..a17bd3873 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts @@ -1,21 +1,16 @@ import { assert } from "chai"; -import { TransactionsConverter } from "../converters/transactionsConverter"; import { createDevnetProvider } from "../testutils/networkProviders"; import { SmartContractTransactionsOutcomeParser } from "./smartContractTransactionsOutcomeParser"; describe("test smart contract transactions outcome parser on devnet", () => { const networkProvider = createDevnetProvider(); const parser = new SmartContractTransactionsOutcomeParser(); - const transactionsConverter = new TransactionsConverter(); it("should parse outcome of deploy transactions (1)", async () => { const transactionHash = "5d2ff2af8eb3fe7f2acb7e29c0436854b4c6c44de02878b6afff582888024a55"; const transactionOnNetwork = await networkProvider.getTransaction(transactionHash); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); const parsedGivenTransactionOnNetwork = parser.parseDeploy({ transactionOnNetwork }); - const parsedGivenTransactionOutcome = parser.parseDeploy({ transactionOutcome }); - assert.deepEqual(parsedGivenTransactionOnNetwork, parsedGivenTransactionOutcome); assert.equal(parsedGivenTransactionOnNetwork.returnCode, "ok"); assert.deepEqual(parsedGivenTransactionOnNetwork.contracts, [ { @@ -29,11 +24,8 @@ describe("test smart contract transactions outcome parser on devnet", () => { it("should parse outcome of deploy transactions (2)", async () => { const transactionHash = "76683e926dad142fc9651afca208487f2a80d327fc87e5c876eec9d028196352"; const transactionOnNetwork = await networkProvider.getTransaction(transactionHash); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); const parsedGivenTransactionOnNetwork = parser.parseDeploy({ transactionOnNetwork }); - const parsedGivenTransactionOutcome = parser.parseDeploy({ transactionOutcome }); - assert.deepEqual(parsedGivenTransactionOnNetwork, parsedGivenTransactionOutcome); assert.equal(parsedGivenTransactionOnNetwork.returnCode, "execution failed"); assert.lengthOf(parsedGivenTransactionOnNetwork.contracts, 0); }); diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index 3e8149269..2c3fbaccf 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -1,67 +1,24 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Address } from "../address"; -import { TransactionsConverter } from "../converters/transactionsConverter"; import { ContractResultItem, ContractResults, TransactionEventOnNetwork, TransactionEventTopic, TransactionLogsOnNetwork, - TransactionOnNetwork, } from "../networkProviders"; import { loadAbiRegistry } from "../testutils"; -import { - SmartContractCallOutcome, - TransactionEvent, - TransactionLogs, - TransactionOutcome, -} from "../transactionsOutcomeParsers/resources"; +import { TransactionOnNetwork } from "../transactions"; import { SmartContractTransactionsOutcomeParser } from "./smartContractTransactionsOutcomeParser"; describe("test smart contract transactions outcome parser", () => { - it("parses deploy outcome (minimalistic)", async function () { - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqqacl85rd0gl2q8wggl8pwcyzcr4fflc5d8ssve45cj"); - const deployer = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const codeHash = Buffer.from("abba", "hex"); - - const parser = new SmartContractTransactionsOutcomeParser(); - - const parsed = parser.parseDeploy({ - transactionOutcome: new TransactionOutcome({ - directSmartContractCallOutcome: new SmartContractCallOutcome({ - returnCode: "ok", - returnMessage: "ok", - }), - logs: new TransactionLogs({ - events: [ - new TransactionEvent({ - identifier: "SCDeploy", - topics: [contract.getPublicKey(), deployer.getPublicKey(), codeHash], - }), - ], - }), - }), - }); - - assert.equal(parsed.returnCode, "ok"); - assert.equal(parsed.returnMessage, "ok"); - assert.deepEqual(parsed.contracts, [ - { - address: contract.toBech32(), - ownerAddress: deployer.toBech32(), - codeHash: codeHash, - }, - ]); - }); - it("parses deploy outcome", async function () { const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqqacl85rd0gl2q8wggl8pwcyzcr4fflc5d8ssve45cj"); const deployer = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const codeHash = Buffer.from("abba", "hex"); const parser = new SmartContractTransactionsOutcomeParser(); - const transactionsConverter = new TransactionsConverter(); const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, @@ -85,8 +42,7 @@ describe("test smart contract transactions outcome parser", () => { ]), }); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); - const parsed = parser.parseDeploy({ transactionOutcome }); + const parsed = parser.parseDeploy({ transactionOnNetwork }); assert.equal(parsed.returnCode, "ok"); assert.equal(parsed.returnMessage, "ok"); @@ -103,7 +59,6 @@ describe("test smart contract transactions outcome parser", () => { const deployer = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const parser = new SmartContractTransactionsOutcomeParser(); - const transactionsConverter = new TransactionsConverter(); const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, @@ -121,36 +76,15 @@ describe("test smart contract transactions outcome parser", () => { }), }); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); - const parsed = parser.parseDeploy({ transactionOutcome }); + const parsed = parser.parseDeploy({ transactionOnNetwork }); assert.equal(parsed.returnCode, "user error"); assert.equal(parsed.returnMessage, "wrong number of arguments"); assert.deepEqual(parsed.contracts, []); }); - it("parses execute outcome, without ABI (minimalistic)", function () { - const parser = new SmartContractTransactionsOutcomeParser(); - - const parsed = parser.parseExecute({ - transactionOutcome: new TransactionOutcome({ - directSmartContractCallOutcome: new SmartContractCallOutcome({ - function: "hello", - returnCode: "ok", - returnMessage: "ok", - returnDataParts: [Buffer.from([42])], - }), - }), - }); - - assert.deepEqual(parsed.values, [Buffer.from([42])]); - assert.equal(parsed.returnCode, "ok"); - assert.equal(parsed.returnMessage, "ok"); - }); - it("parses execute outcome, without ABI", function () { const parser = new SmartContractTransactionsOutcomeParser(); - const transactionsConverter = new TransactionsConverter(); const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, contractResults: new ContractResults([ @@ -161,44 +95,18 @@ describe("test smart contract transactions outcome parser", () => { ]), }); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); - - const parsed = parser.parseExecute({ transactionOutcome }); + const parsed = parser.parseExecute({ transactionOnNetwork }); assert.deepEqual(parsed.values, [Buffer.from([42])]); assert.equal(parsed.returnCode, "ok"); assert.equal(parsed.returnMessage, "ok"); }); - it("parses execute outcome, with ABI (minimalistic)", async function () { + it.only("parses execute outcome, with ABI", async function () { const parser = new SmartContractTransactionsOutcomeParser({ abi: await loadAbiRegistry("src/testdata/answer.abi.json"), }); - const parsed = parser.parseExecute({ - transactionOutcome: new TransactionOutcome({ - directSmartContractCallOutcome: new SmartContractCallOutcome({ - // For the sake of the test, let's say that we've called this function as a transaction, not as a query. - function: "getUltimateAnswer", - returnCode: "ok", - returnMessage: "ok", - returnDataParts: [Buffer.from([42])], - }), - }), - }); - - // At this moment, U64Value.valueOf() returns a BigNumber. This might change in the future. - assert.deepEqual(parsed.values, [new BigNumber("42")]); - assert.equal(parsed.returnCode, "ok"); - assert.equal(parsed.returnMessage, "ok"); - }); - - it("parses execute outcome, with ABI", async function () { - const parser = new SmartContractTransactionsOutcomeParser({ - abi: await loadAbiRegistry("src/testdata/answer.abi.json"), - }); - - const transactionsConverter = new TransactionsConverter(); const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, function: "getUltimateAnswer", @@ -210,10 +118,10 @@ describe("test smart contract transactions outcome parser", () => { ]), }); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); - const parsed = parser.parseExecute({ transactionOutcome }); + const parsed = parser.parseExecute({ transactionOnNetwork }); // At this moment, U64Value.valueOf() returns a BigNumber. This might change in the future. + console.log(1111, parsed.values); assert.deepEqual(parsed.values, [new BigNumber("42")]); assert.equal(parsed.returnCode, "ok"); assert.equal(parsed.returnMessage, "ok"); @@ -224,7 +132,6 @@ describe("test smart contract transactions outcome parser", () => { abi: await loadAbiRegistry("src/testdata/answer.abi.json"), }); - const transactionsConverter = new TransactionsConverter(); const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, contractResults: new ContractResults([ @@ -235,10 +142,8 @@ describe("test smart contract transactions outcome parser", () => { ]), }); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); - assert.throws(() => { - parser.parseExecute({ transactionOutcome }); - }, 'Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?'); + parser.parseExecute({ transactionOnNetwork }); + }, 'Function name is not available in the transaction, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?'); }); }); diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 5db245c85..06f5a3f72 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -1,13 +1,10 @@ -import { ArgSerializer, EndpointDefinition, ResultsParser, ReturnCode, Type, UntypedOutcomeBundle } from "../abi"; +import { ArgSerializer, EndpointDefinition, ResultsParser, Type, UntypedOutcomeBundle } from "../abi"; import { Address } from "../address"; import { ARGUMENTS_SEPARATOR } from "../constants"; import { Err } from "../errors"; import { IContractResultItem, ITransactionEvent, ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { - SmartContractCallOutcome, - TransactionOutcome, - findEventsByIdentifier, -} from "../transactionsOutcomeParsers/resources"; +import { TransactionOnNetwork } from "../transactions"; +import { SmartContractCallOutcome } from "../transactionsOutcomeParsers/resources"; enum Events { SCDeploy = "SCDeploy", @@ -43,9 +40,7 @@ export class SmartContractTransactionsOutcomeParser { this.legacyResultsParser = options?.legacyResultsParser || new ResultsParser(); } - parseDeploy( - options: { transactionOutcome: TransactionOutcome } | { transactionOnNetwork: ITransactionOnNetwork }, - ): { + parseDeploy(options: { transactionOnNetwork: TransactionOnNetwork }): { returnCode: string; returnMessage: string; contracts: { @@ -54,37 +49,10 @@ export class SmartContractTransactionsOutcomeParser { codeHash: Uint8Array; }[]; } { - if ("transactionOutcome" in options) { - return this.parseDeployGivenTransactionOutcome(options.transactionOutcome); - } - return this.parseDeployGivenTransactionOnNetwork(options.transactionOnNetwork); } - /** - * Legacy approach. - */ - protected parseDeployGivenTransactionOutcome(transactionOutcome: TransactionOutcome): { - returnCode: string; - returnMessage: string; - contracts: { - address: string; - ownerAddress: string; - codeHash: Uint8Array; - }[]; - } { - const directCallOutcome = transactionOutcome.directSmartContractCallOutcome; - const events = findEventsByIdentifier(transactionOutcome, Events.SCDeploy); - const contracts = events.map((event) => this.parseScDeployEvent(event)); - - return { - returnCode: directCallOutcome.returnCode, - returnMessage: directCallOutcome.returnMessage, - contracts: contracts, - }; - } - - protected parseDeployGivenTransactionOnNetwork(transactionOnNetwork: ITransactionOnNetwork): { + protected parseDeployGivenTransactionOnNetwork(transactionOnNetwork: TransactionOnNetwork): { returnCode: string; returnMessage: string; contracts: { @@ -132,68 +100,14 @@ export class SmartContractTransactionsOutcomeParser { }; } - parseExecute( - options: - | { transactionOutcome: TransactionOutcome; function?: string } - | { transactionOnNetwork: ITransactionOnNetwork; function?: string }, - ): { + parseExecute(options: { transactionOnNetwork: TransactionOnNetwork; function?: string }): { values: any[]; returnCode: string; returnMessage: string; } { - if ("transactionOutcome" in options) { - return this.parseExecuteGivenTransactionOutcome(options.transactionOutcome, options.function); - } - return this.parseExecuteGivenTransactionOnNetwork(options.transactionOnNetwork, options.function); } - /** - * Legacy approach. - */ - protected parseExecuteGivenTransactionOutcome( - transactionOutcome: TransactionOutcome, - functionName?: string, - ): { - values: any[]; - returnCode: string; - returnMessage: string; - } { - const directCallOutcome = transactionOutcome.directSmartContractCallOutcome; - - if (!this.abi) { - return { - values: directCallOutcome.returnDataParts, - returnCode: directCallOutcome.returnCode, - returnMessage: directCallOutcome.returnMessage, - }; - } - - functionName = functionName || directCallOutcome.function; - - if (!functionName) { - throw new Err( - `Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?`, - ); - } - - const endpoint = this.abi.getEndpoint(functionName); - - const legacyUntypedBundle = { - returnCode: new ReturnCode(directCallOutcome.returnCode), - returnMessage: directCallOutcome.returnMessage, - values: directCallOutcome.returnDataParts.map((part) => Buffer.from(part)), - }; - - const legacyTypedBundle = this.legacyResultsParser.parseOutcomeFromUntypedBundle(legacyUntypedBundle, endpoint); - - return { - values: legacyTypedBundle.values.map((value) => value.valueOf()), - returnCode: legacyTypedBundle.returnCode.toString(), - returnMessage: legacyTypedBundle.returnMessage, - }; - } - protected parseExecuteGivenTransactionOnNetwork( transactionOnNetwork: ITransactionOnNetwork, functionName?: string, @@ -202,6 +116,7 @@ export class SmartContractTransactionsOutcomeParser { returnCode: string; returnMessage: string; } { + console.log({ transactionOnNetwork, functionName }); const directCallOutcome = this.findDirectSmartContractCallOutcome(transactionOnNetwork); if (!this.abi) { diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 432f58243..ab44b1eea 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -11,8 +11,9 @@ import { ITransactionOnNetwork, ITransactionStatus, } from "../interfaceOfNetwork"; -import { ContractResultItem, ContractResults, TransactionOnNetwork, TransactionStatus } from "../networkProviders"; +import { ContractResultItem, ContractResults, TransactionStatus } from "../networkProviders"; import { Transaction, TransactionHash } from "../transaction"; +import { TransactionOnNetwork } from "../transactions"; import { createAccountBalance } from "./utils"; export class MockNetworkProvider { diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index a08a4ec0a..c68295a2f 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -1,3 +1,4 @@ +import { Address } from "../address"; import { IAddress } from "../interface"; export type IssueFungibleInput = IssueInput & { initialSupply: bigint; numDecimals: bigint }; @@ -105,7 +106,7 @@ export type RegisteringDynamicTokenInput = { tokenName: string; tokenTicker: str type TokenType = "NFT" | "SFT" | "META" | "FNG"; export type SpecialRoleOutput = { - userAddress: string; + userAddress: Address; tokenIdentifier: string; roles: string[]; }; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index e5d0f219f..60aea8a10 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -1,9 +1,9 @@ import { IAccount } from "../accounts/interfaces"; -import { TransactionOnNetwork } from "../networkProviders"; import { INetworkProvider } from "../networkProviders/interface"; import { IESDTIssueOutcome } from "../tokenOperations"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; +import { TransactionOnNetwork } from "../transactions"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TokenManagementTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; import { TransactionWatcher } from "../transactionWatcher"; diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts index 4bb1a9a37..25ee90ec9 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts @@ -1,28 +1,29 @@ import { assert } from "chai"; +import { Address } from "../address"; import { ErrParseTransactionOutcome } from "../errors"; -import { b64TopicsToBytes } from "../testutils"; -import { - SmartContractResult, - TransactionEvent, - TransactionLogs, - TransactionOutcome, -} from "../transactionsOutcomeParsers/resources"; +import { ContractResultItem, ContractResults } from "../networkProviders"; +import { TransactionEvent, TransactionEventData, TransactionEventTopic } from "../transactionEvents"; +import { TransactionLogs } from "../transactionLogs"; +import { TransactionOnNetwork } from "../transactions"; import { TokenManagementTransactionsOutcomeParser } from "./tokenManagementTransactionsOutcomeParser"; describe("test token management transactions outcome parser", () => { const parser = new TokenManagementTransactionsOutcomeParser(); it("should test ensure error", () => { - const encodedTopics = ["Avk0jZ1kR+l9c76wQQoYcu4hvXPz+jxxTdqQeaCrbX8=", "dGlja2VyIG5hbWUgaXMgbm90IHZhbGlk"]; + const encodedTopics = [ + new TransactionEventTopic("Avk0jZ1kR+l9c76wQQoYcu4hvXPz+jxxTdqQeaCrbX8="), + new TransactionEventTopic("dGlja2VyIG5hbWUgaXMgbm90IHZhbGlk"), + ]; const event = new TransactionEvent({ - address: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", + address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), identifier: "signalError", - topics: b64TopicsToBytes(encodedTopics), - dataItems: [Buffer.from("QDc1NzM2NTcyMjA2NTcyNzI2Zjcy", "base64")], + topics: encodedTopics, + dataPayload: new TransactionEventData(Buffer.from("QDc1NzM2NTcyMjA2NTcyNzI2Zjcy", "base64")), }); const logs = new TransactionLogs({ events: [event] }); - const txOutcome = new TransactionOutcome({ logs: logs }); + const txOutcome = new TransactionOnNetwork({ logs: logs }); assert.throws( () => { @@ -37,19 +38,25 @@ describe("test token management transactions outcome parser", () => { const identifier = "ZZZ-9ee87d"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [base64Identifier, "U0VDT05E", "Wlpa", "RnVuZ2libGVFU0RU", "Ag=="]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic("U0VDT05E"), + new TransactionEventTopic("Wlpa"), + new TransactionEventTopic("RnVuZ2libGVFU0RU"), + new TransactionEventTopic("Ag=="), + ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "issue", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const logs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ logs: logs }); + const txOutcome = new TransactionOnNetwork({ logs: logs }); const outcome = parser.parseIssueFungible(txOutcome); assert.lengthOf(outcome, 1); @@ -61,39 +68,49 @@ describe("test token management transactions outcome parser", () => { const base64Identifier = Buffer.from(identifier).toString("base64"); let encodedTopics = [ - "TkZULWYwMWQxZQ==", - "", - "Y2FuVXBncmFkZQ==", - "dHJ1ZQ==", - "Y2FuQWRkU3BlY2lhbFJvbGVz", - "dHJ1ZQ==", + new TransactionEventTopic("TkZULWYwMWQxZQ=="), + new TransactionEventTopic(""), + new TransactionEventTopic("Y2FuVXBncmFkZQ=="), + new TransactionEventTopic("dHJ1ZQ=="), + new TransactionEventTopic("Y2FuQWRkU3BlY2lhbFJvbGVz"), + new TransactionEventTopic("dHJ1ZQ=="), ]; const firstEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "upgradeProperties", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); - encodedTopics = ["TkZULWYwMWQxZQ==", "", "", "RVNEVFJvbGVCdXJuRm9yQWxs"]; + encodedTopics = [ + new TransactionEventTopic("TkZULWYwMWQxZQ=="), + new TransactionEventTopic(""), + new TransactionEventTopic(""), + new TransactionEventTopic("RVNEVFJvbGVCdXJuRm9yQWxs"), + ]; const secondEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTSetBurnRoleForAll", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); - encodedTopics = [base64Identifier, "TkZURVNU", "TkZU", "Tm9uRnVuZ2libGVFU0RU"]; + encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic("TkZURVNU"), + new TransactionEventTopic("TkZU"), + new TransactionEventTopic("Tm9uRnVuZ2libGVFU0RU"), + ]; const thirdEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "issueNonFungible", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const logs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [firstEvent, secondEvent, thirdEvent], }); - const txOutcome = new TransactionOutcome({ logs: logs }); + const txOutcome = new TransactionOnNetwork({ logs: logs }); const outcome = parser.parseIssueNonFungible(txOutcome); assert.lengthOf(outcome, 1); @@ -104,19 +121,24 @@ describe("test token management transactions outcome parser", () => { const identifier = "SEMIFNG-2c6d9f"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [base64Identifier, "U0VNSQ==", "U0VNSUZORw==", "U2VtaUZ1bmdpYmxlRVNEVA=="]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic("U0VNSQ=="), + new TransactionEventTopic("U0VNSUZORw=="), + new TransactionEventTopic("U2VtaUZ1bmdpYmxlRVNEVA=="), + ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "issueSemiFungible", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const logs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ logs: logs }); + const txOutcome = new TransactionOnNetwork({ logs: logs }); const outcome = parser.parseIssueSemiFungible(txOutcome); assert.lengthOf(outcome, 1); @@ -127,19 +149,24 @@ describe("test token management transactions outcome parser", () => { const identifier = "METATEST-e05d11"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [base64Identifier, "TUVURVNU", "TUVUQVRFU1Q=", "TWV0YUVTRFQ="]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic("TUVURVNU"), + new TransactionEventTopic("TUVUQVRFU1Q="), + new TransactionEventTopic("TWV0YUVTRFQ="), + ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "registerMetaESDT", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const logs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ logs: logs }); + const txOutcome = new TransactionOnNetwork({ logs: logs }); const outcome = parser.parseRegisterMetaEsdt(txOutcome); assert.lengthOf(outcome, 1); @@ -155,56 +182,79 @@ describe("test token management transactions outcome parser", () => { const roles = ["ESDTRoleLocalMint", "ESDTRoleLocalBurn"]; - let encodedTopics = [firstBase64Identifier, "TE1BTw==", "TE1BTw==", "RnVuZ2libGVFU0RU", "Ag=="]; + let encodedTopics = [ + new TransactionEventTopic(firstBase64Identifier), + new TransactionEventTopic("TE1BTw=="), + new TransactionEventTopic("TE1BTw=="), + new TransactionEventTopic("RnVuZ2libGVFU0RU"), + new TransactionEventTopic("Ag=="), + ]; const firstEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "registerAndSetAllRoles", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); - encodedTopics = [secondBase64Identifier, "TE1BTw==", "TE1BTw==", "RnVuZ2libGVFU0RU", "Ag=="]; + encodedTopics = [ + new TransactionEventTopic(secondBase64Identifier), + new TransactionEventTopic("TE1BTw=="), + new TransactionEventTopic("TE1BTw=="), + new TransactionEventTopic("RnVuZ2libGVFU0RU"), + new TransactionEventTopic("Ag=="), + ]; const secondEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "registerAndSetAllRoles", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [firstEvent, secondEvent], }); - encodedTopics = ["TE1BTy1kOWY4OTI=", "", "", "RVNEVFJvbGVMb2NhbE1pbnQ=", "RVNEVFJvbGVMb2NhbEJ1cm4="]; + encodedTopics = [ + new TransactionEventTopic("TE1BTy1kOWY4OTI="), + new TransactionEventTopic(""), + new TransactionEventTopic(""), + new TransactionEventTopic("RVNEVFJvbGVMb2NhbE1pbnQ="), + new TransactionEventTopic("RVNEVFJvbGVMb2NhbEJ1cm4="), + ]; const firstResultEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTSetRole", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); - encodedTopics = ["VFNULTEyMzQ1Ng==", "", "", "RVNEVFJvbGVMb2NhbE1pbnQ=", "RVNEVFJvbGVMb2NhbEJ1cm4="]; + encodedTopics = [ + new TransactionEventTopic("VFNULTEyMzQ1Ng=="), + new TransactionEventTopic(""), + new TransactionEventTopic(""), + new TransactionEventTopic("RVNEVFJvbGVMb2NhbE1pbnQ="), + new TransactionEventTopic("RVNEVFJvbGVMb2NhbEJ1cm4="), + ]; const secondResultEvent = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTSetRole", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const resultLogs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [firstResultEvent, secondResultEvent], }); - const scResult = new SmartContractResult({ - sender: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - receiver: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", - data: Buffer.from( - "RVNEVFNldFJvbGVANGM0ZDQxNGYyZDY0Mzk2NjM4MzkzMkA0NTUzNDQ1NDUyNmY2YzY1NGM2ZjYzNjE2YzRkNjk2ZTc0QDQ1NTM0NDU0NTI2ZjZjNjU0YzZmNjM2MTZjNDI3NTcyNmU=", - "base64", - ), - logs: resultLogs, - }); + const scResult = new ContractResults([ + new ContractResultItem({ + sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), + receiver: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + data: "RVNEVFNldFJvbGVANGM0ZDQxNGYyZDY0Mzk2NjM4MzkzMkA0NTUzNDQ1NDUyNmY2YzY1NGM2ZjYzNjE2YzRkNjk2ZTc0QDQ1NTM0NDU0NTI2ZjZjNjU0YzZmNjM2MTZjNDI3NTcyNmU=", + logs: resultLogs, + }), + ]); - const txOutcome = new TransactionOutcome({ - smartContractResults: [scResult], + const txOutcome = new TransactionOnNetwork({ + contractResults: scResult, logs: transactionLogs, }); @@ -224,31 +274,34 @@ describe("test token management transactions outcome parser", () => { const roles = ["ESDTRoleNFTCreate", "ESDTRoleNFTAddQuantity", "ESDTRoleNFTBurn"]; const encodedTopics = [ - base64Identifier, - "", - "", - "RVNEVFJvbGVORlRDcmVhdGU=", - "RVNEVFJvbGVORlRBZGRRdWFudGl0eQ==", - "RVNEVFJvbGVORlRCdXJu", + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic(""), + new TransactionEventTopic(""), + new TransactionEventTopic("RVNEVFJvbGVORlRDcmVhdGU="), + new TransactionEventTopic("RVNEVFJvbGVORlRBZGRRdWFudGl0eQ=="), + new TransactionEventTopic("RVNEVFJvbGVORlRCdXJu"), ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTSetRole", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); const outcome = parser.parseSetSpecialRole(txOutcome); assert.lengthOf(outcome, 1); - assert.equal(outcome[0].userAddress, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + assert.deepEqual( + outcome[0].userAddress, + new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); assert.equal(outcome[0].tokenIdentifier, identifier); assert.deepEqual(outcome[0].roles, roles); }); @@ -260,23 +313,25 @@ describe("test token management transactions outcome parser", () => { const initialQuantity = BigInt(1); const encodedTopics = [ - base64Identifier, - "AQ==", - "AQ==", - "CAESAgABIuUBCAESCE5GVEZJUlNUGiA8NdfqyxqZpKDMqlN+8MwK4Qn0H2wrQCID5jO/uwcfXCDEEyouUW1ZM3ZKQ3NVcWpNM3hxeGR3VWczemJoVFNMUWZoN0szbW5aWXhyaGNRRFl4RzJDaHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1ZM3ZKQ3NVcWpNM3hxeGR3VWczemJoVFNMUWZoN0szbW5aWXhyaGNRRFl4Rzo9dGFnczo7bWV0YWRhdGE6UW1SY1A5NGtYcjV6WmpSR3ZpN21KNnVuN0xweFVoWVZSNFI0UnBpY3h6Z1lrdA==", + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic("AQ=="), + new TransactionEventTopic("AQ=="), + new TransactionEventTopic( + "CAESAgABIuUBCAESCE5GVEZJUlNUGiA8NdfqyxqZpKDMqlN+8MwK4Qn0H2wrQCID5jO/uwcfXCDEEyouUW1ZM3ZKQ3NVcWpNM3hxeGR3VWczemJoVFNMUWZoN0szbW5aWXhyaGNRRFl4RzJDaHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1ZM3ZKQ3NVcWpNM3hxeGR3VWczemJoVFNMUWZoN0szbW5aWXhyaGNRRFl4Rzo9dGFnczo7bWV0YWRhdGE6UW1SY1A5NGtYcjV6WmpSR3ZpN21KNnVuN0xweFVoWVZSNFI0UnBpY3h6Z1lrdA==", + ), ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTNFTCreate", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); @@ -293,19 +348,23 @@ describe("test token management transactions outcome parser", () => { const nonce = BigInt(0); const mintedSupply = BigInt(100000); - const encodedTopics = [base64Identifier, "", "AYag"]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic(""), + new TransactionEventTopic("AYag"), + ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTLocalMint", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); @@ -323,19 +382,23 @@ describe("test token management transactions outcome parser", () => { const nonce = BigInt(0); const burntSupply = BigInt(100000); - const encodedTopics = [base64Identifier, "", "AYag"]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic(""), + new TransactionEventTopic("AYag"), + ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTLocalBurn", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); @@ -351,19 +414,19 @@ describe("test token management transactions outcome parser", () => { const identifier = "AAA-29c4c9"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [base64Identifier]; + const encodedTopics = [new TransactionEventTopic(base64Identifier)]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTPause", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); @@ -376,19 +439,19 @@ describe("test token management transactions outcome parser", () => { const identifier = "AAA-29c4c9"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [base64Identifier]; + const encodedTopics = [new TransactionEventTopic(base64Identifier)]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTUnPause", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); @@ -404,27 +467,34 @@ describe("test token management transactions outcome parser", () => { const balance = BigInt(10000000); const address = "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"; - const encodedTopics = [base64Identifier, "", "mJaA", "ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic(""), + new TransactionEventTopic("mJaA"), + new TransactionEventTopic("ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="), + ]; const event = new TransactionEvent({ - address: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", + address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), identifier: "ESDTFreeze", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), events: [event], }); - const scResult = new SmartContractResult({ - sender: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - receiver: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - data: Buffer.from("RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", "base64"), - logs: transactionLogs, - }); + const scResult = new ContractResults([ + new ContractResultItem({ + sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), + receiver: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + data: "RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", + logs: transactionLogs, + }), + ]); - const txOutcome = new TransactionOutcome({ - smartContractResults: [scResult], + const txOutcome = new TransactionOnNetwork({ + contractResults: scResult, }); const outcome = parser.parseFreeze(txOutcome); @@ -442,27 +512,34 @@ describe("test token management transactions outcome parser", () => { const balance = BigInt(10000000); const address = "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"; - const encodedTopics = [base64Identifier, "", "mJaA", "ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic(""), + new TransactionEventTopic("mJaA"), + new TransactionEventTopic("ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="), + ]; const event = new TransactionEvent({ - address: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", + address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), identifier: "ESDTUnFreeze", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), events: [event], }); - const scResult = new SmartContractResult({ - sender: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - receiver: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - data: Buffer.from("RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", "base64"), - logs: transactionLogs, - }); + const scResult = new ContractResults([ + new ContractResultItem({ + sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), + receiver: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + data: "RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", + logs: transactionLogs, + }), + ]); - const txOutcome = new TransactionOutcome({ - smartContractResults: [scResult], + const txOutcome = new TransactionOnNetwork({ + contractResults: scResult, }); const outcome = parser.parseUnfreeze(txOutcome); @@ -480,27 +557,34 @@ describe("test token management transactions outcome parser", () => { const balance = BigInt(10000000); const address = "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"; - const encodedTopics = [base64Identifier, "", "mJaA", "ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic(""), + new TransactionEventTopic("mJaA"), + new TransactionEventTopic("ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="), + ]; const event = new TransactionEvent({ - address: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", + address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), identifier: "ESDTWipe", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), events: [event], }); - const scResult = new SmartContractResult({ - sender: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - receiver: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - data: Buffer.from("RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", "base64"), - logs: transactionLogs, - }); + const scResult = new ContractResults([ + new ContractResultItem({ + sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), + receiver: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + data: "RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", + logs: transactionLogs, + }), + ]); - const txOutcome = new TransactionOutcome({ - smartContractResults: [scResult], + const txOutcome = new TransactionOnNetwork({ + contractResults: scResult, }); const outcome = parser.parseWipe(txOutcome); @@ -518,19 +602,24 @@ describe("test token management transactions outcome parser", () => { const attributes = "metadata:ipfsCID/test.json;tags:tag1,tag2"; const base64Attributes = Buffer.from(attributes).toString("base64"); - const encodedTopics = [base64Identifier, "AQ==", "", base64Attributes]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic("AQ=="), + new TransactionEventTopic(""), + new TransactionEventTopic(base64Attributes), + ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTNFTUpdateAttributes", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); @@ -547,19 +636,23 @@ describe("test token management transactions outcome parser", () => { const nonce = BigInt(1); const addedQuantity = BigInt(10); - const encodedTopics = [base64Identifier, "AQ==", "Cg=="]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic("AQ=="), + new TransactionEventTopic("Cg=="), + ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTNFTAddQuantity", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); @@ -576,19 +669,23 @@ describe("test token management transactions outcome parser", () => { const nonce = BigInt(1); const burntQuantity = BigInt(16); - const encodedTopics = [base64Identifier, "AQ==", "EA=="]; + const encodedTopics = [ + new TransactionEventTopic(base64Identifier), + new TransactionEventTopic("AQ=="), + new TransactionEventTopic("EA=="), + ]; const event = new TransactionEvent({ - address: "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2", + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTNFTBurn", - topics: b64TopicsToBytes(encodedTopics), + topics: encodedTopics, }); const transactionLogs = new TransactionLogs({ - address: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), events: [event], }); - const txOutcome = new TransactionOutcome({ + const txOutcome = new TransactionOnNetwork({ logs: transactionLogs, }); diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index 1c6696f51..44dd8f92e 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -1,55 +1,44 @@ import { bufferToBigInt } from "../abi/codec/utils"; import { Address } from "../address"; -import { TransactionsConverter } from "../converters/transactionsConverter"; import { ErrParseTransactionOutcome } from "../errors"; -import { ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { TransactionEvent, TransactionOutcome, findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; +import { ITransactionEvent } from "../interfaceOfNetwork"; +import { TransactionEvent, TransactionEventTopic } from "../transactionEvents"; +import { TransactionOnNetwork } from "../transactions"; +import { findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; import { MintNftOutput, SpecialRoleOutput } from "./resources"; export class TokenManagementTransactionsOutcomeParser { constructor() {} - parseIssueFungible(transaction: TransactionOutcome | ITransactionOnNetwork): { tokenIdentifier: string }[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseIssueFungible(transaction: TransactionOnNetwork): { tokenIdentifier: string }[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "issue"); return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); } - parseIssueNonFungible(transaction: TransactionOutcome | ITransactionOnNetwork): { tokenIdentifier: string }[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseIssueNonFungible(transaction: TransactionOnNetwork): { tokenIdentifier: string }[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "issueNonFungible"); return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); } - parseIssueSemiFungible(transaction: TransactionOutcome | ITransactionOnNetwork): { tokenIdentifier: string }[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseIssueSemiFungible(transaction: TransactionOnNetwork): { tokenIdentifier: string }[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "issueSemiFungible"); return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); } - parseRegisterMetaEsdt(transaction: TransactionOutcome | ITransactionOnNetwork): { tokenIdentifier: string }[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseRegisterMetaEsdt(transaction: TransactionOnNetwork): { tokenIdentifier: string }[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "registerMetaESDT"); return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); } - parseRegisterAndSetAllRoles( - transaction: TransactionOutcome | ITransactionOnNetwork, - ): { tokenIdentifier: string; roles: string[] }[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseRegisterAndSetAllRoles(transaction: TransactionOnNetwork): { tokenIdentifier: string; roles: string[] }[] { this.ensureNoError(transaction.logs.events); const registerEvents = findEventsByIdentifier(transaction, "registerAndSetAllRoles"); const setRoleEvents = findEventsByIdentifier(transaction, "ESDTSetRole"); @@ -63,26 +52,20 @@ export class TokenManagementTransactionsOutcomeParser { return registerEvents.map((registerEvent, index) => { const tokenIdentifier = this.extractTokenIdentifier(registerEvent); const encodedRoles = setRoleEvents[index].topics.slice(3); - const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); + const roles = encodedRoles.map((role) => role.toString()); return { tokenIdentifier, roles }; }); } - parseSetBurnRoleGlobally(transaction: TransactionOutcome | ITransactionOnNetwork) { - transaction = this.ensureTransactionOutcome(transaction); - + parseSetBurnRoleGlobally(transaction: TransactionOnNetwork) { this.ensureNoError(transaction.logs.events); } - parseUnsetBurnRoleGlobally(transaction: TransactionOutcome | ITransactionOnNetwork) { - transaction = this.ensureTransactionOutcome(transaction); - + parseUnsetBurnRoleGlobally(transaction: TransactionOnNetwork) { this.ensureNoError(transaction.logs.events); } - parseSetSpecialRole(transaction: TransactionOutcome | ITransactionOnNetwork): SpecialRoleOutput[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseSetSpecialRole(transaction: TransactionOnNetwork): SpecialRoleOutput[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTSetRole"); @@ -93,14 +76,12 @@ export class TokenManagementTransactionsOutcomeParser { const userAddress = event.address; const tokenIdentifier = this.extractTokenIdentifier(event); const encodedRoles = event.topics.slice(3); - const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); + const roles = encodedRoles.map((role) => role.toString()); return { userAddress: userAddress, tokenIdentifier: tokenIdentifier, roles: roles }; } - parseNftCreate(transaction: TransactionOutcome | ITransactionOnNetwork): MintNftOutput[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseNftCreate(transaction: TransactionOnNetwork): MintNftOutput[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTNFTCreate"); @@ -119,14 +100,12 @@ export class TokenManagementTransactionsOutcomeParser { return { tokenIdentifier: tokenIdentifier, nonce: nonce, initialQuantity: amount }; } - parseLocalMint(transaction: TransactionOutcome | ITransactionOnNetwork): { - userAddress: string; + parseLocalMint(transaction: TransactionOnNetwork): { + userAddress: Address; tokenIdentifier: string; nonce: bigint; mintedSupply: bigint; }[] { - transaction = this.ensureTransactionOutcome(transaction); - this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTLocalMint"); @@ -134,7 +113,7 @@ export class TokenManagementTransactionsOutcomeParser { } private getOutputForLocalMintEvent(event: TransactionEvent): { - userAddress: string; + userAddress: Address; tokenIdentifier: string; nonce: bigint; mintedSupply: bigint; @@ -152,14 +131,12 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parseLocalBurn(transaction: TransactionOutcome | ITransactionOnNetwork): { - userAddress: string; + parseLocalBurn(transaction: TransactionOnNetwork): { + userAddress: Address; tokenIdentifier: string; nonce: bigint; burntSupply: bigint; }[] { - transaction = this.ensureTransactionOutcome(transaction); - this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTLocalBurn"); @@ -167,7 +144,7 @@ export class TokenManagementTransactionsOutcomeParser { } private getOutputForLocalBurnEvent(event: TransactionEvent): { - userAddress: string; + userAddress: Address; tokenIdentifier: string; nonce: bigint; burntSupply: bigint; @@ -185,32 +162,26 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parsePause(transaction: TransactionOutcome | ITransactionOnNetwork): { tokenIdentifier: string }[] { - transaction = this.ensureTransactionOutcome(transaction); - + parsePause(transaction: TransactionOnNetwork): { tokenIdentifier: string }[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTPause"); return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); } - parseUnpause(transaction: TransactionOutcome | ITransactionOnNetwork): { tokenIdentifier: string }[] { - transaction = this.ensureTransactionOutcome(transaction); - + parseUnpause(transaction: TransactionOnNetwork): { tokenIdentifier: string }[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTUnPause"); return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); } - parseFreeze(transaction: TransactionOutcome | ITransactionOnNetwork): { + parseFreeze(transaction: TransactionOnNetwork): { userAddress: string; tokenIdentifier: string; nonce: bigint; balance: bigint; }[] { - transaction = this.ensureTransactionOutcome(transaction); - this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTFreeze"); @@ -236,14 +207,12 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parseUnfreeze(transaction: TransactionOutcome | ITransactionOnNetwork): { + parseUnfreeze(transaction: TransactionOnNetwork): { userAddress: string; tokenIdentifier: string; nonce: bigint; balance: bigint; }[] { - transaction = this.ensureTransactionOutcome(transaction); - this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTUnFreeze"); @@ -269,14 +238,12 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parseWipe(transaction: TransactionOutcome | ITransactionOnNetwork): { + parseWipe(transaction: TransactionOnNetwork): { userAddress: string; tokenIdentifier: string; nonce: bigint; balance: bigint; }[] { - transaction = this.ensureTransactionOutcome(transaction); - this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTWipe"); @@ -302,13 +269,11 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parseUpdateAttributes(transaction: TransactionOutcome | ITransactionOnNetwork): { + parseUpdateAttributes(transaction: TransactionOnNetwork): { tokenIdentifier: string; nonce: bigint; - attributes: Uint8Array; + attributes: TransactionEventTopic; }[] { - transaction = this.ensureTransactionOutcome(transaction); - this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTNFTUpdateAttributes"); @@ -318,11 +283,11 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForUpdateAttributesEvent(event: TransactionEvent): { tokenIdentifier: string; nonce: bigint; - attributes: Uint8Array; + attributes: TransactionEventTopic; } { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const attributes = event.topics[3] ? event.topics[3] : new Uint8Array(); + const attributes = event.topics[3] ? event.topics[3] : new TransactionEventTopic(""); return { tokenIdentifier: tokenIdentifier, @@ -331,13 +296,11 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parseAddQuantity(transaction: TransactionOutcome | ITransactionOnNetwork): { + parseAddQuantity(transaction: TransactionOnNetwork): { tokenIdentifier: string; nonce: bigint; addedQuantity: bigint; }[] { - transaction = this.ensureTransactionOutcome(transaction); - this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTNFTAddQuantity"); @@ -360,13 +323,11 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parseBurnQuantity(transaction: TransactionOutcome | ITransactionOnNetwork): { + parseBurnQuantity(transaction: TransactionOnNetwork): { tokenIdentifier: string; nonce: bigint; burntQuantity: bigint; }[] { - transaction = this.ensureTransactionOutcome(transaction); - this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTNFTBurn"); @@ -389,22 +350,11 @@ export class TokenManagementTransactionsOutcomeParser { }; } - /** - * Temporary workaround, until "TransactionOnNetwork" completely replaces "TransactionOutcome". - */ - private ensureTransactionOutcome(transaction: TransactionOutcome | ITransactionOnNetwork): TransactionOutcome { - if ("hash" in transaction) { - return new TransactionsConverter().transactionOnNetworkToOutcome(transaction); - } - - return transaction; - } - - private ensureNoError(transactionEvents: TransactionEvent[]) { + private ensureNoError(transactionEvents: ITransactionEvent[]) { for (const event of transactionEvents) { if (event.identifier == "signalError") { - const data = Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; - const message = this.decodeTopicAsString(event.topics[1]); + const data = event.dataPayload?.toString().slice(1) || ""; + const message = event.topics[1].toString(); throw new ErrParseTransactionOutcome( `encountered signalError: ${message} (${Buffer.from(data, "hex").toString()})`, @@ -414,14 +364,14 @@ export class TokenManagementTransactionsOutcomeParser { } private extractTokenIdentifier(event: TransactionEvent): string { - if (!event.topics[0]?.length) { + if (!event.topics[0].toString()?.length) { return ""; } - return this.decodeTopicAsString(event.topics[0]); + return event.topics[0].toString(); } private extractNonce(event: TransactionEvent): bigint { - if (!event.topics[1]?.length) { + if (!event.topics[1].toString()?.length) { return BigInt(0); } const nonce = Buffer.from(event.topics[1]); @@ -429,7 +379,7 @@ export class TokenManagementTransactionsOutcomeParser { } private extractAmount(event: TransactionEvent): bigint { - if (!event.topics[2]?.length) { + if (!event.topics[2].toString()?.length) { return BigInt(0); } const amount = Buffer.from(event.topics[2]); @@ -437,14 +387,10 @@ export class TokenManagementTransactionsOutcomeParser { } private extractAddress(event: TransactionEvent): string { - if (!event.topics[3]?.length) { + if (!event.topics[3].toString()?.length) { return ""; } const address = Buffer.from(event.topics[3]); - return Address.fromBuffer(address).bech32(); - } - - private decodeTopicAsString(topic: Uint8Array): string { - return Buffer.from(topic).toString(); + return new Address(address).bech32(); } } diff --git a/src/transaction.ts b/src/transaction.ts index a8fad0a9d..d6911146f 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -11,7 +11,6 @@ import { INonce, IPlainTransactionObject, ISignature, - ITransaction, ITransactionOptions, ITransactionPayload, ITransactionValue, @@ -20,8 +19,8 @@ import { import { INetworkConfig } from "./interfaceOfNetwork"; import { TransactionOptions, TransactionVersion } from "./networkParams"; import { interpretSignatureAsBuffer } from "./signature"; -import { TransactionPayload } from "./transactionPayload"; import { TransactionComputer } from "./transactionComputer"; +import { TransactionPayload } from "./transactionPayload"; /** * An abstraction for creating and signing transactions. diff --git a/src/networkProviders/transactionEvents.ts b/src/transactionEvents.ts similarity index 95% rename from src/networkProviders/transactionEvents.ts rename to src/transactionEvents.ts index ab11c5892..5650fd312 100644 --- a/src/networkProviders/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -1,8 +1,7 @@ -import { Address } from "../address"; -import { IAddress } from "./interface"; +import { Address } from "./address"; export class TransactionEvent { - address: IAddress = Address.empty(); + address: Address = Address.empty(); identifier: string = ""; topics: TransactionEventTopic[] = []; diff --git a/src/networkProviders/transactionLogs.ts b/src/transactionLogs.ts similarity index 89% rename from src/networkProviders/transactionLogs.ts rename to src/transactionLogs.ts index 36c10690d..081770f69 100644 --- a/src/networkProviders/transactionLogs.ts +++ b/src/transactionLogs.ts @@ -1,10 +1,9 @@ -import { Address } from "../address"; -import { ErrUnexpectedCondition } from "./../errors"; -import { IAddress } from "./interface"; +import { Address } from "./address"; +import { ErrUnexpectedCondition } from "./errors"; import { TransactionEvent } from "./transactionEvents"; export class TransactionLogs { - address: IAddress = Address.empty(); + address: Address = Address.empty(); events: TransactionEvent[] = []; constructor(init?: Partial) { diff --git a/src/transactionWatcher.spec.ts b/src/transactionWatcher.spec.ts index 018313440..0f2cc2cce 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/transactionWatcher.spec.ts @@ -1,8 +1,9 @@ import { assert } from "chai"; -import { TransactionOnNetwork, TransactionStatus } from "./networkProviders"; +import { TransactionStatus } from "./networkProviders"; import { MarkCompleted, MockNetworkProvider, Wait } from "./testutils"; import { TransactionHash } from "./transaction"; import { TransactionWatcher } from "./transactionWatcher"; +import { TransactionOnNetwork } from "./transactions"; describe("test transactionWatcher", () => { it("should await status == executed using hash", async () => { diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index 741548769..f21b760c3 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -9,7 +9,7 @@ import { import { ITransactionFetcher } from "./interface"; import { ITransactionEvent, ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork"; import { Logger } from "./logger"; -import { TransactionOnNetwork } from "./networkProviders"; +import { TransactionOnNetwork } from "./transactions"; export type PredicateIsAwaitedStatus = (status: ITransactionStatus) => boolean; diff --git a/src/networkProviders/transactions.ts b/src/transactions.ts similarity index 92% rename from src/networkProviders/transactions.ts rename to src/transactions.ts index 232691315..7fac1c86e 100644 --- a/src/networkProviders/transactions.ts +++ b/src/transactions.ts @@ -1,9 +1,9 @@ -import { Address } from "../address"; -import { ContractResults } from "./contractResults"; -import { IAddress, ITransaction, ITransactionNext } from "./interface"; +import { Address } from "./address"; +import { ContractResults } from "./networkProviders/contractResults"; +import { IAddress, ITransaction, ITransactionNext } from "./networkProviders/interface"; +import { TransactionReceipt } from "./networkProviders/transactionReceipt"; +import { TransactionStatus } from "./networkProviders/transactionStatus"; import { TransactionLogs } from "./transactionLogs"; -import { TransactionReceipt } from "./transactionReceipt"; -import { TransactionStatus } from "./transactionStatus"; export function prepareTransactionForBroadcasting(transaction: ITransaction | ITransactionNext): any { if ("toSendable" in transaction) { diff --git a/src/transactionsOutcomeParsers/resources.spec.ts b/src/transactionsOutcomeParsers/resources.spec.ts index 1d8fbd8ea..26967cf6d 100644 --- a/src/transactionsOutcomeParsers/resources.spec.ts +++ b/src/transactionsOutcomeParsers/resources.spec.ts @@ -1,40 +1,37 @@ import { assert } from "chai"; -import { - SmartContractResult, - TransactionEvent, - TransactionLogs, - TransactionOutcome, - findEventsByFirstTopic, - findEventsByIdentifier, -} from "./resources"; +import { ContractResultItem, ContractResults } from "../networkProviders/contractResults"; +import { TransactionEvent, TransactionEventTopic } from "../transactionEvents"; +import { TransactionLogs } from "../transactionLogs"; +import { TransactionOnNetwork } from "../transactions"; +import { findEventsByFirstTopic, findEventsByIdentifier } from "./resources"; describe("test resources", () => { it("finds events by identifier, by first topic", async function () { - const outcome = new TransactionOutcome({ + const outcome = new TransactionOnNetwork({ logs: new TransactionLogs({ events: [ new TransactionEvent({ identifier: "foo", - topics: [Buffer.from("a")], + topics: [new TransactionEventTopic("a")], }), ], }), - smartContractResults: [ - new SmartContractResult({ + contractResults: new ContractResults([ + new ContractResultItem({ logs: new TransactionLogs({ events: [ new TransactionEvent({ identifier: "foo", - topics: [Buffer.from("b")], + topics: [new TransactionEventTopic("b")], }), new TransactionEvent({ identifier: "bar", - topics: [Buffer.from("c")], + topics: [new TransactionEventTopic("c")], }), ], }), }), - ], + ]), }); const foundByIdentifierFoo = findEventsByIdentifier(outcome, "foo"); @@ -44,25 +41,25 @@ describe("test resources", () => { assert.deepEqual(foundByIdentifierFoo, [ new TransactionEvent({ identifier: "foo", - topics: [Buffer.from("a")], + topics: [new TransactionEventTopic("a")], }), new TransactionEvent({ identifier: "foo", - topics: [Buffer.from("b")], + topics: [new TransactionEventTopic("b")], }), ]); assert.deepEqual(foundByIdentifierBar, [ new TransactionEvent({ identifier: "bar", - topics: [Buffer.from("c")], + topics: [new TransactionEventTopic("c")], }), ]); assert.deepEqual(foundByTopic, [ new TransactionEvent({ identifier: "foo", - topics: [Buffer.from("b")], + topics: [new TransactionEventTopic("b")], }), ]); }); diff --git a/src/transactionsOutcomeParsers/resources.ts b/src/transactionsOutcomeParsers/resources.ts index b30bd2f1c..df9c4694d 100644 --- a/src/transactionsOutcomeParsers/resources.ts +++ b/src/transactionsOutcomeParsers/resources.ts @@ -1,30 +1,6 @@ -export class TransactionEvent { - address: string; - identifier: string; - topics: Uint8Array[]; - dataItems: Uint8Array[]; - - constructor(init: Partial) { - this.address = ""; - this.identifier = ""; - this.topics = []; - this.dataItems = []; - - Object.assign(this, init); - } -} - -export class TransactionLogs { - address: string; - events: TransactionEvent[]; - - constructor(init: Partial) { - this.address = ""; - this.events = []; - - Object.assign(this, init); - } -} +import { TransactionEvent } from "../transactionEvents"; +import { TransactionLogs } from "../transactionLogs"; +import { TransactionOnNetwork } from "../transactions"; export class SmartContractResult { sender: string; @@ -42,20 +18,6 @@ export class SmartContractResult { } } -export class TransactionOutcome { - directSmartContractCallOutcome: SmartContractCallOutcome; - smartContractResults: SmartContractResult[]; - logs: TransactionLogs; - - constructor(init: Partial) { - this.directSmartContractCallOutcome = new SmartContractCallOutcome({}); - this.smartContractResults = []; - this.logs = new TransactionLogs({}); - - Object.assign(this, init); - } -} - export class SmartContractCallOutcome { function: string; returnDataParts: Uint8Array[]; @@ -73,26 +35,29 @@ export class SmartContractCallOutcome { } export function findEventsByPredicate( - transactionOutcome: TransactionOutcome, + transactionOutcome: TransactionOnNetwork, predicate: (event: TransactionEvent) => boolean, ): TransactionEvent[] { return gatherAllEvents(transactionOutcome).filter(predicate); } -export function findEventsByIdentifier(transactionOutcome: TransactionOutcome, identifier: string): TransactionEvent[] { +export function findEventsByIdentifier( + transactionOutcome: TransactionOnNetwork, + identifier: string, +): TransactionEvent[] { return findEventsByPredicate(transactionOutcome, (event) => event.identifier == identifier); } -export function findEventsByFirstTopic(transactionOutcome: TransactionOutcome, topic: string): TransactionEvent[] { +export function findEventsByFirstTopic(transactionOutcome: TransactionOnNetwork, topic: string): TransactionEvent[] { return findEventsByPredicate(transactionOutcome, (event) => event.topics[0]?.toString() == topic); } -export function gatherAllEvents(transactionOutcome: TransactionOutcome): TransactionEvent[] { +export function gatherAllEvents(transactionOutcome: TransactionOnNetwork): TransactionEvent[] { const allEvents = []; allEvents.push(...transactionOutcome.logs.events); - for (const item of transactionOutcome.smartContractResults) { + for (const item of transactionOutcome.contractResults.items) { allEvents.push(...item.logs.events); } diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts index 6b1a3fa7d..18ee3309b 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts @@ -2,7 +2,6 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { AbiRegistry } from "../abi"; import { Address } from "../address"; -import { TransactionsConverter } from "../converters/transactionsConverter"; import { ContractResultItem, ContractResults, @@ -10,10 +9,11 @@ import { TransactionEventOnNetwork, TransactionEventTopic, TransactionLogsOnNetwork, - TransactionOnNetwork, } from "../networkProviders"; import { loadAbiRegistry } from "../testutils"; -import { TransactionEvent, findEventsByFirstTopic } from "./resources"; +import { TransactionEvent } from "../transactionEvents"; +import { TransactionOnNetwork } from "../transactions"; +import { findEventsByFirstTopic } from "./resources"; import { TransactionEventsParser } from "./transactionEventsParser"; describe("test transaction events parser", () => { @@ -26,7 +26,11 @@ describe("test transaction events parser", () => { events: [ new TransactionEvent({ identifier: "transferOverMaxAmount", - topics: [Buffer.from("transferOverMaxAmount"), Buffer.from([0x2a]), Buffer.from([0x2b])], + topics: [ + new TransactionEventTopic(Buffer.from("transferOverMaxAmount").toString("base64")), + new TransactionEventTopic(Buffer.from([0x2a]).toString("base64")), + new TransactionEventTopic(Buffer.from([0x2b]).toString("base64")), + ], }), ], }); @@ -44,7 +48,6 @@ describe("test transaction events parser", () => { abi: await loadAbiRegistry("src/testdata/esdt-safe.abi.json"), }); - const transactionsConverter = new TransactionsConverter(); const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, contractResults: new ContractResults([ @@ -60,7 +63,7 @@ describe("test transaction events parser", () => { new TransactionEventTopic("cmzC1LRt1r10pMhNAnFb+FyudjGMq4G8CefCYdQUmmc="), new TransactionEventTopic("AAAADFdFR0xELTAxZTQ5ZAAAAAAAAAAAAAAAAWQ="), ], - dataPayload: new TransactionEventData(Buffer.from("AAAAAAAAA9sAAAA=", "base64")), + additionalData: [new TransactionEventData(Buffer.from("AAAAAAAAA9sAAAA=", "base64"))], }), ], }), @@ -68,8 +71,7 @@ describe("test transaction events parser", () => { ]), }); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); - const events = findEventsByFirstTopic(transactionOutcome, "deposit"); + const events = findEventsByFirstTopic(transactionOnNetwork, "deposit"); const parsed = parser.parseEvents({ events }); assert.deepEqual(parsed, [ @@ -97,7 +99,6 @@ describe("test transaction events parser", () => { abi: await loadAbiRegistry("src/testdata/multisig-full.abi.json"), }); - const transactionsConverter = new TransactionsConverter(); const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, contractResults: new ContractResults([ @@ -111,19 +112,20 @@ describe("test transaction events parser", () => { new TransactionEventOnNetwork({ identifier: "performAction", topics: [new TransactionEventTopic("c3RhcnRQZXJmb3JtQWN0aW9u")], - dataPayload: new TransactionEventData( - Buffer.from( - "00000001000000000500000000000000000500d006f73c4221216fa679bc559005584c4f1160e569e1000000000000000003616464000000010000000107000000010139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1", - "hex", + additionalData: [ + new TransactionEventData( + Buffer.from( + "00000001000000000500000000000000000500d006f73c4221216fa679bc559005584c4f1160e569e1000000000000000003616464000000010000000107000000010139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1", + "hex", + ), ), - ), + ], }), ], }), }); - const transactionOutcome = transactionsConverter.transactionOnNetworkToOutcome(transactionOnNetwork); - const events = findEventsByFirstTopic(transactionOutcome, "startPerformAction"); + const events = findEventsByFirstTopic(transactionOnNetwork, "startPerformAction"); const parsed = parser.parseEvents({ events }); assert.deepEqual(parsed, [ @@ -161,7 +163,7 @@ describe("test transaction events parser", () => { events: [ new TransactionEvent({ identifier: "foobar", - topics: [Buffer.from("doFoobar")], + topics: [new TransactionEventTopic(Buffer.from("doFoobar").toString("base64"))], }), ], }); @@ -199,15 +201,15 @@ describe("test transaction events parser", () => { event: new TransactionEvent({ identifier: "foobar", topics: [ - Buffer.from("doFoobar"), - Buffer.from([42]), - Buffer.from("test"), - Buffer.from([43]), - Buffer.from("test"), - Buffer.from("test"), - Buffer.from([44]), + new TransactionEventTopic(Buffer.from("doFoobar").toString("base64")), + new TransactionEventTopic(Buffer.from([42]).toString("base64")), + new TransactionEventTopic(Buffer.from("test").toString("base64")), + new TransactionEventTopic(Buffer.from([43]).toString("base64")), + new TransactionEventTopic(Buffer.from("test").toString("base64")), + new TransactionEventTopic(Buffer.from("test").toString("base64")), + new TransactionEventTopic(Buffer.from([44]).toString("base64")), ], - dataItems: [Buffer.from([42])], + additionalData: [new TransactionEventData(Buffer.from([42]))], }), }); diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.ts b/src/transactionsOutcomeParsers/transactionEventsParser.ts index da4c0d316..c4c58d8aa 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.ts @@ -1,16 +1,12 @@ -import { EventDefinition, ResultsParser } from "../abi"; -import { TransactionEvent } from "./resources"; - -interface IAbi { - getEvent(name: string): EventDefinition; -} +import { AbiRegistry, ResultsParser } from "../abi"; +import { TransactionEvent } from "../transactionEvents"; export class TransactionEventsParser { private readonly legacyResultsParser: ResultsParser; - private readonly abi: IAbi; + private readonly abi: AbiRegistry; private readonly firstTopicIsIdentifier: boolean; - constructor(options: { abi: IAbi; firstTopicIsIdentifier?: boolean }) { + constructor(options: { abi: AbiRegistry; firstTopicIsIdentifier?: boolean }) { this.legacyResultsParser = new ResultsParser(); this.abi = options.abi; @@ -33,14 +29,14 @@ export class TransactionEventsParser { } parseEvent(options: { event: TransactionEvent }): any { - const topics = options.event.topics.map((topic) => Buffer.from(topic)); + const topics = options.event.topics.map((topic) => topic.valueOf()); const abiIdentifier = this.firstTopicIsIdentifier ? topics[0]?.toString() : options.event.identifier; if (this.firstTopicIsIdentifier) { topics.shift(); } - const dataItems = options.event.dataItems.map((dataItem) => Buffer.from(dataItem)); + const dataItems = options.event.additionalData.map((dataItem) => Buffer.from(dataItem)); const eventDefinition = this.abi.getEvent(abiIdentifier); const parsedEvent = this.legacyResultsParser.doParseEvent({ From 563b046caa6e1ec7ed6047f66c181c73ac42abd4 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 20 Nov 2024 15:51:22 +0200 Subject: [PATCH 039/214] Sync transactionEvent to specs --- src/abi/resultsParser.spec.ts | 85 +++--- src/abi/resultsParser.ts | 72 ++--- src/abi/smartContract.spec.ts | 2 +- src/converters/transactionsConverter.ts | 41 --- ...elegationTransactionsOutcomeParser.spec.ts | 47 +-- .../delegationTransactionsOutcomeParser.ts | 16 +- src/index.ts | 1 + src/networkProviders/apiNetworkProvider.ts | 2 +- src/networkProviders/index.ts | 7 - src/networkProviders/interface.ts | 2 +- .../providers.dev.net.spec.ts | 27 +- src/networkProviders/proxyNetworkProvider.ts | 2 +- ...TransactionsOutcomeParser.main.net.spec.ts | 17 -- ...tContractTransactionsOutcomeParser.spec.ts | 60 +--- .../smartContractTransactionsOutcomeParser.ts | 53 ++-- src/testutils/contractController.ts | 6 +- src/testutils/mockNetworkProvider.ts | 17 +- ...anagementTransactionsOutcomeParser.spec.ts | 267 ++++++------------ ...okenManagementTransactionsOutcomeParser.ts | 31 +- src/transaction.ts | 8 +- src/transactionEvents.ts | 60 +--- .../transactionStatus.ts | 0 src/transactionWatcher.spec.ts | 4 +- src/transactionWatcher.ts | 33 +-- src/transactions.ts | 20 +- .../resources.spec.ts | 25 +- src/transactionsOutcomeParsers/resources.ts | 14 +- .../transactionEventsParser.spec.ts | 91 +++--- .../transactionEventsParser.ts | 2 +- 29 files changed, 370 insertions(+), 642 deletions(-) rename src/{networkProviders => }/transactionStatus.ts (100%) diff --git a/src/abi/resultsParser.spec.ts b/src/abi/resultsParser.spec.ts index 6cc08e449..0a4141571 100644 --- a/src/abi/resultsParser.spec.ts +++ b/src/abi/resultsParser.spec.ts @@ -1,18 +1,12 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Address } from "../address"; -import { IAddress } from "../interface"; -import { - ContractQueryResponse, - ContractResultItem, - ContractResults, - TransactionEventData, - TransactionEventOnNetwork, - TransactionEventTopic, - TransactionLogsOnNetwork, -} from "../networkProviders"; -import { loadAbiRegistry } from "../testutils"; +import { ContractQueryResponse } from "../networkProviders"; +import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; +import { TransactionEvent } from "../transactionEvents"; +import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; +import { SmartContractResult } from "../transactionsOutcomeParsers"; import { ArgSerializer } from "./argSerializer"; import { ResultsParser } from "./resultsParser"; import { ReturnCode } from "./returnCode"; @@ -186,7 +180,7 @@ describe("test smart contract results parser", () => { let endpoint = new EndpointDefinition("foo", [], outputParameters, endpointModifiers); let transactionOnNetwork = new TransactionOnNetwork({ - contractResults: new ContractResults([new ContractResultItem({ nonce: 7, data: "@6f6b@2a@abba" })]), + smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b@2a@abba") })], }); let bundle = parser.parseOutcome(transactionOnNetwork, endpoint); @@ -199,13 +193,11 @@ describe("test smart contract results parser", () => { it("should parse contract outcome, on easily found result with return data", async () => { let transaction = new TransactionOnNetwork({ - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 42, - data: "@6f6b@03", - returnMessage: "foobar", + smartContractResults: [ + new SmartContractResult({ + data: Buffer.from("@6f6b@03"), }), - ]), + ], }); let bundle = parser.parseUntypedOutcome(transaction); @@ -216,12 +208,12 @@ describe("test smart contract results parser", () => { it("should parse contract outcome, on signal error", async () => { let transaction = new TransactionOnNetwork({ - logs: new TransactionLogsOnNetwork({ + logs: new TransactionLogs({ address: Address.empty(), events: [ - new TransactionEventOnNetwork({ + new TransactionEvent({ identifier: "signalError", - topics: [new TransactionEventTopic(Buffer.from("something happened").toString("base64"))], + topics: [Buffer.from("something happened")], data: `@${Buffer.from("user error").toString("hex")}@07`, }), ], @@ -236,14 +228,15 @@ describe("test smart contract results parser", () => { it("should parse contract outcome, on too much gas warning", async () => { let transaction = new TransactionOnNetwork({ - logs: new TransactionLogsOnNetwork({ + logs: new TransactionLogs({ address: Address.empty(), events: [ - new TransactionEventOnNetwork({ + new TransactionEvent({ identifier: "writeLog", topics: [ - new TransactionEventTopic( + Buffer.from( "QHRvbyBtdWNoIGdhcyBwcm92aWRlZCBmb3IgcHJvY2Vzc2luZzogZ2FzIHByb3ZpZGVkID0gNTk2Mzg0NTAwLCBnYXMgdXNlZCA9IDczMzAxMA==", + "base64", ), ], data: Buffer.from("QDZmNmI=", "base64").toString(), @@ -262,19 +255,19 @@ describe("test smart contract results parser", () => { const abiRegistry = await loadAbiRegistry("src/testdata/esdt-safe.abi.json"); const eventDefinition = abiRegistry.getEvent("deposit"); - const event = new TransactionEventOnNetwork({ + const event = new TransactionEvent({ topics: [ - new TransactionEventTopic("ZGVwb3NpdA=="), - new TransactionEventTopic("cmzC1LRt1r10pMhNAnFb+FyudjGMq4G8CefCYdQUmmc="), - new TransactionEventTopic("AAAADFdFR0xELTAxZTQ5ZAAAAAAAAAAAAAAAAWQ="), + Buffer.from("ZGVwb3NpdA==", "base64"), + Buffer.from("cmzC1LRt1r10pMhNAnFb+FyudjGMq4G8CefCYdQUmmc=", "base64"), + Buffer.from("AAAADFdFR0xELTAxZTQ5ZAAAAAAAAAAAAAAAAWQ=", "base64"), ], - dataPayload: new TransactionEventData(Buffer.from("AAAAAAAAA9sAAAA=", "base64")), + dataPayload: Buffer.from("AAAAAAAAA9sAAAA=", "base64"), }); const bundle = parser.parseEvent(event, eventDefinition); assert.equal( - (bundle.dest_address).bech32(), + (
bundle.dest_address).bech32(), "erd1wfkv9495dhtt6a9yepxsyu2mlpw2ua333j4cr0qfulpxr4q5nfnshgyqun", ); assert.equal(bundle.tokens[0].token_identifier, "WEGLD-01e49d"); @@ -315,16 +308,16 @@ describe("test smart contract results parser", () => { const eventDefinition = abiRegistry.getEvent("foobar"); const event = { - topics: [ - new TransactionEventTopic(Buffer.from("not used").toString("base64")), - new TransactionEventTopic(Buffer.from([42]).toString("base64")), - new TransactionEventTopic(Buffer.from("test").toString("base64")), - new TransactionEventTopic(Buffer.from([43]).toString("base64")), - new TransactionEventTopic(Buffer.from("test").toString("base64")), - new TransactionEventTopic(Buffer.from("test").toString("base64")), - new TransactionEventTopic(Buffer.from([44]).toString("base64")), - ], - dataPayload: new TransactionEventData(Buffer.from([42])), + topics: b64TopicsToBytes([ + Buffer.from("not used").toString("base64"), + Buffer.from([42]).toString("base64"), + Buffer.from("test").toString("base64"), + Buffer.from([43]).toString("base64"), + Buffer.from("test").toString("base64"), + Buffer.from("test").toString("base64"), + Buffer.from([44]).toString("base64"), + ]), + dataPayload: Buffer.from([42]), }; const bundle = parser.parseEvent(event, eventDefinition); @@ -362,13 +355,13 @@ describe("test smart contract results parser", () => { const eventDefinition = abiRegistry.getEvent("foobar"); const event = { - topics: [ - new TransactionEventTopic(Buffer.from("not used").toString("base64")), - new TransactionEventTopic(Buffer.from([42]).toString("base64")), - ], - additionalData: [new TransactionEventData(Buffer.from([43])), new TransactionEventData(Buffer.from([44]))], + topics: b64TopicsToBytes([ + Buffer.from("not used").toString("base64"), + Buffer.from([42]).toString("base64"), + ]), + additionalData: [Buffer.from([43]), Buffer.from([44])], // Will be ignored. - dataPayload: new TransactionEventData(Buffer.from([43])), + dataPayload: Buffer.from([43]), }; const bundle = parser.parseEvent(event, eventDefinition); diff --git a/src/abi/resultsParser.ts b/src/abi/resultsParser.ts index 4b4d71860..2304dc59c 100644 --- a/src/abi/resultsParser.ts +++ b/src/abi/resultsParser.ts @@ -4,14 +4,11 @@ import { } from "@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder"; import { Address } from "../address"; import { ErrCannotParseContractResults } from "../errors"; -import { IAddress } from "../interface"; -import { - IContractQueryResponse, - IContractResults, - ITransactionLogs, - ITransactionOnNetwork, -} from "../interfaceOfNetwork"; +import { IContractQueryResponse } from "../interfaceOfNetwork"; import { Logger } from "../logger"; +import { TransactionLogs } from "../transactionLogs"; +import { TransactionOnNetwork } from "../transactions"; +import { SmartContractResult } from "../transactionsOutcomeParsers"; import { ArgSerializer } from "./argSerializer"; import { TypedOutcomeBundle, UntypedOutcomeBundle } from "./interface"; import { ReturnCode } from "./returnCode"; @@ -113,7 +110,7 @@ export class ResultsParser { /** * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. */ - parseOutcome(transaction: ITransactionOnNetwork, endpoint: { output: IParameterDefinition[] }): TypedOutcomeBundle { + parseOutcome(transaction: TransactionOnNetwork, endpoint: { output: IParameterDefinition[] }): TypedOutcomeBundle { const untypedBundle = this.parseUntypedOutcome(transaction); const typedBundle = this.parseOutcomeFromUntypedBundle(untypedBundle, endpoint); return typedBundle; @@ -140,7 +137,7 @@ export class ResultsParser { /** * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. */ - parseUntypedOutcome(transaction: ITransactionOnNetwork): UntypedOutcomeBundle { + parseUntypedOutcome(transaction: TransactionOnNetwork): UntypedOutcomeBundle { let bundle: UntypedOutcomeBundle | null; let transactionMetadata = this.parseTransactionMetadata(transaction); @@ -151,13 +148,12 @@ export class ResultsParser { return bundle; } - bundle = this.createBundleOnInvalidTransaction(transaction); if (bundle) { Logger.trace("parseUntypedOutcome(): on invalid transaction"); return bundle; } - bundle = this.createBundleOnEasilyFoundResultWithReturnData(transaction.contractResults); + bundle = this.createBundleOnEasilyFoundResultWithReturnData(transaction.smartContractResults); if (bundle) { Logger.trace("parseUntypedOutcome(): on easily found result with return data"); return bundle; @@ -196,7 +192,7 @@ export class ResultsParser { throw new ErrCannotParseContractResults(`transaction ${transaction.hash.toString()}`); } - protected parseTransactionMetadata(transaction: ITransactionOnNetwork): TransactionMetadata { + protected parseTransactionMetadata(transaction: TransactionOnNetwork): TransactionMetadata { return new TransactionDecoder().getTransactionMetadata({ sender: transaction.sender.bech32(), receiver: transaction.receiver.bech32(), @@ -205,8 +201,8 @@ export class ResultsParser { }); } - protected createBundleOnSimpleMoveBalance(transaction: ITransactionOnNetwork): UntypedOutcomeBundle | null { - let noResults = transaction.contractResults.items.length == 0; + protected createBundleOnSimpleMoveBalance(transaction: TransactionOnNetwork): UntypedOutcomeBundle | null { + let noResults = transaction.smartContractResults.length == 0; let noLogs = transaction.logs.events.length == 0; if (noResults && noLogs) { @@ -220,32 +216,16 @@ export class ResultsParser { return null; } - protected createBundleOnInvalidTransaction(transaction: ITransactionOnNetwork): UntypedOutcomeBundle | null { - if (transaction.status.isInvalid()) { - if (transaction.receipt.data) { - return { - returnCode: ReturnCode.OutOfFunds, - returnMessage: transaction.receipt.data, - values: [], - }; - } - - // If there's no receipt message, let other heuristics to handle the outcome (most probably, a log with "signalError" is emitted). - } - - return null; - } - - protected createBundleOnEasilyFoundResultWithReturnData(results: IContractResults): UntypedOutcomeBundle | null { - let resultItemWithReturnData = results.items.find( - (item) => item.nonce.valueOf() != 0 && item.data.startsWith("@"), - ); + protected createBundleOnEasilyFoundResultWithReturnData( + results: SmartContractResult[], + ): UntypedOutcomeBundle | null { + let resultItemWithReturnData = results.find((item) => item.data.toString().startsWith("@")); if (!resultItemWithReturnData) { return null; } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(resultItemWithReturnData.data); - let returnMessage = resultItemWithReturnData.returnMessage || returnCode.toString(); + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(resultItemWithReturnData.data.toString()); + let returnMessage = resultItemWithReturnData.raw["prevTxHash"] || returnCode.toString(); return { returnCode: returnCode, @@ -254,7 +234,7 @@ export class ResultsParser { }; } - protected createBundleOnSignalError(logs: ITransactionLogs): UntypedOutcomeBundle | null { + protected createBundleOnSignalError(logs: TransactionLogs): UntypedOutcomeBundle | null { let eventSignalError = logs.findSingleOrNoneEvent(WellKnownEvents.OnSignalError); if (!eventSignalError) { return null; @@ -271,7 +251,7 @@ export class ResultsParser { }; } - protected createBundleOnTooMuchGasWarning(logs: ITransactionLogs): UntypedOutcomeBundle | null { + protected createBundleOnTooMuchGasWarning(logs: TransactionLogs): UntypedOutcomeBundle | null { let eventTooMuchGas = logs.findSingleOrNoneEvent( WellKnownEvents.OnWriteLog, (event) => @@ -293,14 +273,14 @@ export class ResultsParser { } protected createBundleOnWriteLogWhereFirstTopicEqualsAddress( - logs: ITransactionLogs, - address: IAddress, + logs: TransactionLogs, + address: Address, ): UntypedOutcomeBundle | null { let hexAddress = new Address(address.bech32()).hex(); let eventWriteLogWhereTopicIsSender = logs.findSingleOrNoneEvent( WellKnownEvents.OnWriteLog, - (event) => event.findFirstOrNoneTopic((topic) => topic.hex() == hexAddress) != undefined, + (event) => event.findFirstOrNoneTopic((topic) => topic.toString() == hexAddress) != undefined, ); if (!eventWriteLogWhereTopicIsSender) { @@ -321,23 +301,23 @@ export class ResultsParser { * Override this method (in a subclass of {@link ResultsParser}) if the basic heuristics of the parser are not sufficient. */ protected createBundleWithCustomHeuristics( - _transaction: ITransactionOnNetwork, + _transaction: TransactionOnNetwork, _transactionMetadata: TransactionMetadata, ): UntypedOutcomeBundle | null { return null; } protected createBundleWithFallbackHeuristics( - transaction: ITransactionOnNetwork, + transaction: TransactionOnNetwork, transactionMetadata: TransactionMetadata, ): UntypedOutcomeBundle | null { let contractAddress = new Address(transactionMetadata.receiver); // Search the nested logs for matching events (writeLog): - for (const resultItem of transaction.contractResults.items) { + for (const resultItem of transaction.smartContractResults) { let writeLogWithReturnData = resultItem.logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => { let addressIsSender = event.address.bech32() == transaction.sender.bech32(); - let firstTopicIsContract = event.topics[0]?.hex() == contractAddress.hex(); + let firstTopicIsContract = event.topics[0].toString() == contractAddress.hex(); return addressIsSender && firstTopicIsContract; }); @@ -354,7 +334,7 @@ export class ResultsParser { } // Additional fallback heuristics (alter search constraints): - for (const resultItem of transaction.contractResults.items) { + for (const resultItem of transaction.smartContractResults) { let writeLogWithReturnData = resultItem.logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => { const addressIsContract = event.address.bech32() == contractAddress.toBech32(); return addressIsContract; diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index bf5e2a132..abbcef788 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -1,4 +1,3 @@ -import { TransactionStatus } from "../networkProviders"; import { assert } from "chai"; import { Address } from "../address"; import { @@ -9,6 +8,7 @@ import { TestWallet, Wait, } from "../testutils"; +import { TransactionStatus } from "../transactionStatus"; import { TransactionWatcher } from "../transactionWatcher"; import { Code } from "./code"; import { ContractFunction } from "./function"; diff --git a/src/converters/transactionsConverter.ts b/src/converters/transactionsConverter.ts index 423f6026e..92cb6f757 100644 --- a/src/converters/transactionsConverter.ts +++ b/src/converters/transactionsConverter.ts @@ -1,9 +1,5 @@ import { IPlainTransactionObject, ITransaction } from "../interface"; -import { IContractResultItem, ITransactionEvent } from "../interfaceOfNetwork"; import { Transaction } from "../transaction"; -import { TransactionEvent, TransactionEventData, TransactionEventTopic } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { SmartContractResult } from "../transactionsOutcomeParsers/resources"; export class TransactionsConverter { public transactionToPlainObject(transaction: ITransaction): IPlainTransactionObject { @@ -65,41 +61,4 @@ export class TransactionsConverter { private bufferFromHex(value?: string) { return Buffer.from(value || "", "hex"); } - - private smartContractResultOnNetworkToSmartContractResult( - resultOnNetwork: IContractResultItem, - ): SmartContractResult { - return new SmartContractResult({ - sender: resultOnNetwork.sender.bech32(), - receiver: resultOnNetwork.receiver.bech32(), - data: Buffer.from(resultOnNetwork.data), - logs: new TransactionLogs({ - address: resultOnNetwork.logs.address, - events: resultOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)), - }), - }); - } - - private eventOnNetworkToEvent(eventOnNetwork: ITransactionEvent): TransactionEvent { - // Before Sirius, there was no "additionalData" field on transaction logs. - // After Sirius, the "additionalData" field includes the payload of the legacy "data" field, as well (as its first element): - // https://github.com/multiversx/mx-chain-go/blob/v1.6.18/process/transactionLog/process.go#L159 - const legacyData = eventOnNetwork.dataPayload?.valueOf() || Buffer.from(eventOnNetwork.data || ""); - const dataItems = - eventOnNetwork.additionalData?.map((data) => new TransactionEventData(Buffer.from(data.valueOf()))) || []; - - if (dataItems.length === 0) { - if (legacyData.length) { - dataItems.push(new TransactionEventData(Buffer.from(legacyData))); - } - } - - return new TransactionEvent({ - address: eventOnNetwork.address, - identifier: eventOnNetwork.identifier, - topics: eventOnNetwork.topics.map((topic) => new TransactionEventTopic(topic.hex())), - dataPayload: new TransactionEventData(Buffer.from(legacyData)), - additionalData: dataItems, - }); - } } diff --git a/src/delegation/delegationTransactionsOutcomeParser.spec.ts b/src/delegation/delegationTransactionsOutcomeParser.spec.ts index a5e6b33ab..b415aa747 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.spec.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.spec.ts @@ -1,9 +1,10 @@ import { assert } from "chai"; import { Address } from "../address"; -import { ContractResultItem, ContractResults } from "../networkProviders"; -import { TransactionEvent, TransactionEventTopic } from "../transactionEvents"; +import { b64TopicsToBytes } from "../testutils"; +import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; +import { SmartContractResult } from "../transactionsOutcomeParsers"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; describe("test delegation transactions outcome parser", () => { @@ -12,36 +13,36 @@ describe("test delegation transactions outcome parser", () => { it("should test parseCreateNewDelegationContract ", () => { const contractAddress = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqy8lllls62y8s5"); let encodedTopics = [ - new TransactionEventTopic("Q8M8GTdWSAAA"), - new TransactionEventTopic("Q8M8GTdWSAAA"), - new TransactionEventTopic("AQ=="), - new TransactionEventTopic("Q8M8GTdWSAAA"), - new TransactionEventTopic("AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABD///8="), + "Q8M8GTdWSAAA", + "Q8M8GTdWSAAA", + "AQ==", + "Q8M8GTdWSAAA", + "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABD///8=", ]; const delegateEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "delegate", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); encodedTopics = [ - new TransactionEventTopic("AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABD///8="), - new TransactionEventTopic("PDXX6ssamaSgzKpTfvDMCuEJ9B9sK0AiA+Yzv7sHH1w="), + "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAABD///8=", + "PDXX6ssamaSgzKpTfvDMCuEJ9B9sK0AiA+Yzv7sHH1w=", ]; const scDeployEvent = new TransactionEvent({ address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqy8lllls62y8s5"), identifier: "SCDeploy", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const logs = new TransactionLogs({ events: [delegateEvent, scDeployEvent] }); - encodedTopics = [new TransactionEventTopic("b2g6sUl6beG17FCUIkFwCOTGJjoJJi5SjkP2077e6xA=")]; + encodedTopics = ["b2g6sUl6beG17FCUIkFwCOTGJjoJJi5SjkP2077e6xA="]; const scResultEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "completedTxEvent", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const scResultLog = new TransactionLogs({ @@ -49,16 +50,16 @@ describe("test delegation transactions outcome parser", () => { events: [scResultEvent], }); - const scResult = new ContractResults([ - new ContractResultItem({ - sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"), - receiver: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), - data: "QDZmNmJAMDAwMDAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMGZmZmZmZg==", - logs: scResultLog, - }), - ]); - - const txOutcome = new TransactionOnNetwork({ contractResults: scResult, logs: logs }); + const scResult = new SmartContractResult({ + sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"), + receiver: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + data: Buffer.from( + "QDZmNmJAMDAwMDAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMGZmZmZmZg==", + "base64", + ), + logs: scResultLog, + }); + const txOutcome = new TransactionOnNetwork({ smartContractResults: [scResult], logs: logs }); const outcome = parser.parseCreateNewDelegationContract(txOutcome); diff --git a/src/delegation/delegationTransactionsOutcomeParser.ts b/src/delegation/delegationTransactionsOutcomeParser.ts index 402853f67..b35dfa1af 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.ts @@ -18,19 +18,25 @@ export class DelegationTransactionsOutcomeParser { private ensureNoError(transactionEvents: TransactionEvent[]) { for (const event of transactionEvents) { if (event.identifier == "signalError") { - const data = event.dataPayload.toString(); - const message = event.topics[1].toString(); + const data = Buffer.from(event.additionalData[0]?.toString().slice(1)).toString() || ""; + const message = this.decodeTopicAsString(event.topics[1]); - throw new ErrParseTransactionOutcome(`encountered signalError: ${message} (${data})`); + throw new ErrParseTransactionOutcome( + `encountered signalError: ${message} (${Buffer.from(data, "hex").toString()})`, + ); } } } private extractContractAddress(event: TransactionEvent): string { - if (!event.topics[0]?.toString().length) { + if (!event.topics[0]?.length) { return ""; } const address = Buffer.from(event.topics[0]); - return new Address(address).bech32(); + return Address.fromBuffer(address).bech32(); + } + + private decodeTopicAsString(topic: Uint8Array): string { + return Buffer.from(topic).toString(); } } diff --git a/src/index.ts b/src/index.ts index 9c411e776..6b83ed2e7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -37,6 +37,7 @@ export * from "./transactionComputer"; export * from "./transactionPayload"; export * from "./transactions"; export * from "./transactionsOutcomeParsers"; +export * from "./transactionStatus"; export * from "./transactionWatcher"; export * from "./transfers"; export * from "./utils"; diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 12653f90f..33e54af5e 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,5 +1,6 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactions"; +import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; import { numberToPaddedHex } from "../utils.codec"; import { AccountOnNetwork, GuardianData } from "./accounts"; @@ -17,7 +18,6 @@ import { PairOnNetwork } from "./pairs"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; -import { TransactionStatus } from "./transactionStatus"; import { extendUserAgentIfBackend } from "./userAgent"; // TODO: Find & remove duplicate code between "ProxyNetworkProvider" and "ApiNetworkProvider". diff --git a/src/networkProviders/index.ts b/src/networkProviders/index.ts index 1d0f5567a..c39640f9e 100644 --- a/src/networkProviders/index.ts +++ b/src/networkProviders/index.ts @@ -1,17 +1,10 @@ export { ApiNetworkProvider } from "./apiNetworkProvider"; export { ProxyNetworkProvider } from "./proxyNetworkProvider"; -export { - TransactionEventData, - TransactionEvent as TransactionEventOnNetwork, - TransactionEventTopic, -} from "../transactionEvents"; -export { TransactionLogs as TransactionLogsOnNetwork } from "../transactionLogs"; export { AccountOnNetwork } from "./accounts"; export { ContractQueryResponse } from "./contractQueryResponse"; export { ContractResultItem, ContractResults } from "./contractResults"; export { TransactionReceipt } from "./transactionReceipt"; -export { TransactionStatus } from "./transactionStatus"; export { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; export { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index c43fdb8dc..a763355c9 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,5 +1,6 @@ import { ITransaction as ITransactionAsInSpecs } from "../interface"; import { TransactionOnNetwork } from "../transactions"; +import { TransactionStatus } from "../transactionStatus"; import { AccountOnNetwork } from "./accounts"; import { ContractQueryResponse } from "./contractQueryResponse"; import { NetworkConfig } from "./networkConfig"; @@ -8,7 +9,6 @@ import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; -import { TransactionStatus } from "./transactionStatus"; /** * An interface that defines the endpoints of an HTTP API Provider. diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index d08e5b4f7..4627f5596 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -2,12 +2,11 @@ import { AxiosHeaders } from "axios"; import { assert } from "chai"; import { Address } from "../address"; import { MockQuery } from "../testutils/dummyQuery"; +import { TransactionOnNetwork } from "../transactions"; import { ApiNetworkProvider } from "./apiNetworkProvider"; import { INetworkProvider, ITransactionNext } from "./interface"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; import { NonFungibleTokenOfAccountOnNetwork } from "./tokens"; -import { TransactionEventData } from "./transactionEvents"; -import { TransactionOnNetwork } from "./transactions"; describe("test network providers on devnet: Proxy and API", function () { let alice = new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); @@ -296,18 +295,18 @@ describe("test network providers on devnet: Proxy and API", function () { assert.exists(proxyResponse.logs); assert.exists(apiResponse.logs.events); assert.exists(proxyResponse.logs.events); - assert.equal(apiResponse.logs.events[0].topics[0].hex(), "414c4943452d353632376631"); - assert.equal(apiResponse.logs.events[0].topics[1].hex(), ""); - assert.equal(apiResponse.logs.events[0].topics[2].hex(), "01"); + assert.equal(apiResponse.logs.events[0].topics[0].toString(), "414c4943452d353632376631"); + assert.equal(apiResponse.logs.events[0].topics[1].toString(), ""); + assert.equal(apiResponse.logs.events[0].topics[2].toString(), "01"); assert.equal( - apiResponse.logs.events[0].topics[3].hex(), + apiResponse.logs.events[0].topics[3].toString(), "0000000000000000050032e141d21536e2dfc3d64b9e7dd0c2c53f201dc469e1", ); - assert.equal(proxyResponse.logs.events[0].topics[0].hex(), "414c4943452d353632376631"); - assert.equal(proxyResponse.logs.events[0].topics[1].hex(), ""); - assert.equal(proxyResponse.logs.events[0].topics[2].hex(), "01"); + assert.equal(proxyResponse.logs.events[0].topics[0].toString(), "414c4943452d353632376631"); + assert.equal(proxyResponse.logs.events[0].topics[1].toString(), ""); + assert.equal(proxyResponse.logs.events[0].topics[2].toString(), "01"); assert.equal( - proxyResponse.logs.events[0].topics[3].hex(), + proxyResponse.logs.events[0].topics[3].toString(), "0000000000000000050032e141d21536e2dfc3d64b9e7dd0c2c53f201dc469e1", ); }); @@ -406,11 +405,11 @@ describe("test network providers on devnet: Proxy and API", function () { assert.equal(apiResponse.logs.events[0].data, Buffer.from("test").toString()); assert.equal(proxyResponse.logs.events[0].data, Buffer.from("test").toString()); - assert.deepEqual(apiResponse.logs.events[0].dataPayload, TransactionEventData.fromBase64("dGVzdA==")); - assert.deepEqual(proxyResponse.logs.events[0].dataPayload, TransactionEventData.fromBase64("dGVzdA==")); + assert.deepEqual(apiResponse.logs.events[0].dataPayload, Buffer.from("dGVzdA==")); + assert.deepEqual(proxyResponse.logs.events[0].dataPayload, Buffer.from("dGVzdA==")); - assert.deepEqual(apiResponse.logs.events[0].additionalData, [TransactionEventData.fromBase64("dGVzdA==")]); - assert.deepEqual(proxyResponse.logs.events[0].additionalData, [TransactionEventData.fromBase64("dGVzdA==")]); + assert.deepEqual(apiResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==")]); + assert.deepEqual(proxyResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==")]); }); it("should send both `Transaction` and `TransactionNext`", async function () { diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index a42915aef..5895c8867 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,5 +1,6 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactions"; +import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; @@ -14,7 +15,6 @@ import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; -import { TransactionStatus } from "./transactionStatus"; import { extendUserAgentIfBackend } from "./userAgent"; // TODO: Find & remove duplicate code between "ProxyNetworkProvider" and "ApiNetworkProvider". diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.main.net.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.main.net.spec.ts index 00ee27737..81bfe6b4e 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.main.net.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.main.net.spec.ts @@ -1,13 +1,11 @@ import { assert } from "chai"; import { promises } from "fs"; -import { TransactionsConverter } from "../converters/transactionsConverter"; import { createMainnetProvider } from "../testutils/networkProviders"; import { SmartContractTransactionsOutcomeParser } from "./smartContractTransactionsOutcomeParser"; describe("test smart contract transactions outcome parser on mainnet", () => { const networkProvider = createMainnetProvider(); const parser = new SmartContractTransactionsOutcomeParser(); - const converter = new TransactionsConverter(); it("should parse (execute_success)", async function () { this.timeout(3600000); @@ -19,11 +17,8 @@ describe("test smart contract transactions outcome parser on mainnet", () => { console.log(i, hash); const transactionOnNetwork = await networkProvider.getTransaction(hash); - const transactionOutcome = converter.transactionOnNetworkToOutcome(transactionOnNetwork); - const parsedOutcomeGivenTransactionOutcome = parser.parseExecute({ transactionOutcome }); const parsedOutcomeGivenTransactionOnNetwork = parser.parseExecute({ transactionOnNetwork }); - assert.deepEqual(parsedOutcomeGivenTransactionOutcome, parsedOutcomeGivenTransactionOnNetwork); assert.equal(parsedOutcomeGivenTransactionOnNetwork.returnCode, "ok"); assert.equal(parsedOutcomeGivenTransactionOnNetwork.returnMessage, "ok"); } @@ -39,11 +34,8 @@ describe("test smart contract transactions outcome parser on mainnet", () => { console.log(i, hash); const transactionOnNetwork = await networkProvider.getTransaction(hash); - const transactionOutcome = converter.transactionOnNetworkToOutcome(transactionOnNetwork); - const parsedOutcomeGivenTransactionOutcome = parser.parseExecute({ transactionOutcome }); const parsedOutcomeGivenTransactionOnNetwork = parser.parseExecute({ transactionOnNetwork }); - assert.deepEqual(parsedOutcomeGivenTransactionOutcome, parsedOutcomeGivenTransactionOnNetwork); assert.isTrue(parsedOutcomeGivenTransactionOnNetwork.returnCode.length > 0); assert.isTrue(parsedOutcomeGivenTransactionOnNetwork.returnMessage.length > 0); assert.lengthOf(parsedOutcomeGivenTransactionOnNetwork.values, 0); @@ -60,11 +52,8 @@ describe("test smart contract transactions outcome parser on mainnet", () => { console.log(i, hash); const transactionOnNetwork = await networkProvider.getTransaction(hash); - const transactionOutcome = converter.transactionOnNetworkToOutcome(transactionOnNetwork); - const parsedOutcomeGivenTransactionOutcome = parser.parseExecute({ transactionOutcome }); const parsedOutcomeGivenTransactionOnNetwork = parser.parseExecute({ transactionOnNetwork }); - assert.deepEqual(parsedOutcomeGivenTransactionOutcome, parsedOutcomeGivenTransactionOnNetwork); assert.equal(parsedOutcomeGivenTransactionOnNetwork.returnCode, "ok"); assert.equal(parsedOutcomeGivenTransactionOnNetwork.returnMessage, "ok"); } @@ -80,11 +69,8 @@ describe("test smart contract transactions outcome parser on mainnet", () => { console.log(i, hash); const transactionOnNetwork = await networkProvider.getTransaction(hash); - const transactionOutcome = converter.transactionOnNetworkToOutcome(transactionOnNetwork); - const parsedOutcomeGivenTransactionOutcome = parser.parseExecute({ transactionOutcome }); const parsedOutcomeGivenTransactionOnNetwork = parser.parseExecute({ transactionOnNetwork }); - assert.deepEqual(parsedOutcomeGivenTransactionOutcome, parsedOutcomeGivenTransactionOnNetwork); assert.isTrue(parsedOutcomeGivenTransactionOnNetwork.returnCode.length > 0); assert.isTrue(parsedOutcomeGivenTransactionOnNetwork.returnMessage.length > 0); assert.lengthOf(parsedOutcomeGivenTransactionOnNetwork.values, 0); @@ -136,11 +122,8 @@ describe("test smart contract transactions outcome parser on mainnet", () => { console.log(i, hash); const transactionOnNetwork = await networkProvider.getTransaction(hash); - const transactionOutcome = converter.transactionOnNetworkToOutcome(transactionOnNetwork); - const parsedOutcomeGivenTransactionOutcome = parser.parseExecute({ transactionOutcome }); const parsedOutcomeGivenTransactionOnNetwork = parser.parseExecute({ transactionOnNetwork }); - assert.deepEqual(parsedOutcomeGivenTransactionOutcome, parsedOutcomeGivenTransactionOnNetwork); assert.equal(parsedOutcomeGivenTransactionOnNetwork.returnCode, "ok"); assert.equal(parsedOutcomeGivenTransactionOnNetwork.returnMessage, "ok"); assert.lengthOf(parsedOutcomeGivenTransactionOnNetwork.values, 0); diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index 2c3fbaccf..1c596a33d 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -1,15 +1,11 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Address } from "../address"; -import { - ContractResultItem, - ContractResults, - TransactionEventOnNetwork, - TransactionEventTopic, - TransactionLogsOnNetwork, -} from "../networkProviders"; import { loadAbiRegistry } from "../testutils"; +import { TransactionEvent } from "../transactionEvents"; +import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; +import { SmartContractResult } from "../transactionsOutcomeParsers"; import { SmartContractTransactionsOutcomeParser } from "./smartContractTransactionsOutcomeParser"; describe("test smart contract transactions outcome parser", () => { @@ -22,24 +18,15 @@ describe("test smart contract transactions outcome parser", () => { const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, - logs: new TransactionLogsOnNetwork({ + logs: new TransactionLogs({ events: [ - new TransactionEventOnNetwork({ + new TransactionEvent({ identifier: "SCDeploy", - topics: [ - new TransactionEventTopic(contract.getPublicKey().toString("base64")), - new TransactionEventTopic(deployer.getPublicKey().toString("base64")), - new TransactionEventTopic(codeHash.toString("base64")), - ], + topics: [contract.getPublicKey(), deployer.getPublicKey(), codeHash], }), ], }), - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 8, - data: "@6f6b", - }), - ]), + smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b") })], }); const parsed = parser.parseDeploy({ transactionOnNetwork }); @@ -62,14 +49,11 @@ describe("test smart contract transactions outcome parser", () => { const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, - logs: new TransactionLogsOnNetwork({ + logs: new TransactionLogs({ events: [ - new TransactionEventOnNetwork({ + new TransactionEvent({ identifier: "signalError", - topics: [ - new TransactionEventTopic(deployer.getPublicKey().toString("base64")), - new TransactionEventTopic(Buffer.from("wrong number of arguments").toString("base64")), - ], + topics: [deployer.getPublicKey(), new Uint8Array(Buffer.from("wrong number of arguments"))], data: "@75736572206572726f72", }), ], @@ -87,12 +71,7 @@ describe("test smart contract transactions outcome parser", () => { const parser = new SmartContractTransactionsOutcomeParser(); const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 8, - data: "@6f6b@2a", - }), - ]), + smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b@2a") })], }); const parsed = parser.parseExecute({ transactionOnNetwork }); @@ -102,7 +81,7 @@ describe("test smart contract transactions outcome parser", () => { assert.equal(parsed.returnMessage, "ok"); }); - it.only("parses execute outcome, with ABI", async function () { + it("parses execute outcome, with ABI", async function () { const parser = new SmartContractTransactionsOutcomeParser({ abi: await loadAbiRegistry("src/testdata/answer.abi.json"), }); @@ -110,18 +89,12 @@ describe("test smart contract transactions outcome parser", () => { const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, function: "getUltimateAnswer", - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 8, - data: "@6f6b@2a", - }), - ]), + smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b@2a") })], }); const parsed = parser.parseExecute({ transactionOnNetwork }); // At this moment, U64Value.valueOf() returns a BigNumber. This might change in the future. - console.log(1111, parsed.values); assert.deepEqual(parsed.values, [new BigNumber("42")]); assert.equal(parsed.returnCode, "ok"); assert.equal(parsed.returnMessage, "ok"); @@ -134,12 +107,7 @@ describe("test smart contract transactions outcome parser", () => { const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 8, - data: "@6f6b@2a", - }), - ]), + smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b@2a") })], }); assert.throws(() => { diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 06f5a3f72..6bff67d64 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -2,9 +2,9 @@ import { ArgSerializer, EndpointDefinition, ResultsParser, Type, UntypedOutcomeB import { Address } from "../address"; import { ARGUMENTS_SEPARATOR } from "../constants"; import { Err } from "../errors"; -import { IContractResultItem, ITransactionEvent, ITransactionOnNetwork } from "../interfaceOfNetwork"; +import { TransactionEvent } from "../transactionEvents"; import { TransactionOnNetwork } from "../transactions"; -import { SmartContractCallOutcome } from "../transactionsOutcomeParsers/resources"; +import { SmartContractCallOutcome, SmartContractResult } from "../transactionsOutcomeParsers/resources"; enum Events { SCDeploy = "SCDeploy", @@ -64,12 +64,12 @@ export class SmartContractTransactionsOutcomeParser { const directCallOutcome = this.findDirectSmartContractCallOutcome(transactionOnNetwork); const events = transactionOnNetwork.logs.events - .concat(transactionOnNetwork.contractResults.items.flatMap((result) => result.logs.events)) + .concat(transactionOnNetwork.smartContractResults.flatMap((result) => result.logs.events)) .filter((event) => event.identifier === Events.SCDeploy); const contracts = events.map((event) => this.parseScDeployEvent({ - topics: event.topics.map((topic) => Buffer.from(topic.hex(), "hex")), + topics: event.topics.map((topic) => Buffer.from(topic)), }), ); @@ -85,7 +85,7 @@ export class SmartContractTransactionsOutcomeParser { ownerAddress: string; codeHash: Uint8Array; } { - const topicForAddress = event.topics[0]; + const topicForAddress = Buffer.from(event.topics[0]); const topicForOwnerAddress = event.topics[1]; const topicForCodeHash = event.topics[2]; @@ -109,14 +109,13 @@ export class SmartContractTransactionsOutcomeParser { } protected parseExecuteGivenTransactionOnNetwork( - transactionOnNetwork: ITransactionOnNetwork, + transactionOnNetwork: TransactionOnNetwork, functionName?: string, ): { values: any[]; returnCode: string; returnMessage: string; } { - console.log({ transactionOnNetwork, functionName }); const directCallOutcome = this.findDirectSmartContractCallOutcome(transactionOnNetwork); if (!this.abi) { @@ -143,13 +142,11 @@ export class SmartContractTransactionsOutcomeParser { return { returnCode: directCallOutcome.returnCode, returnMessage: directCallOutcome.returnMessage, - values: values, + values: values.map((value) => value.valueOf()), }; } - protected findDirectSmartContractCallOutcome( - transactionOnNetwork: ITransactionOnNetwork, - ): SmartContractCallOutcome { + protected findDirectSmartContractCallOutcome(transactionOnNetwork: TransactionOnNetwork): SmartContractCallOutcome { let outcome = this.findDirectSmartContractCallOutcomeWithinSmartContractResults(transactionOnNetwork); if (outcome) { return outcome; @@ -174,15 +171,15 @@ export class SmartContractTransactionsOutcomeParser { } protected findDirectSmartContractCallOutcomeWithinSmartContractResults( - transactionOnNetwork: ITransactionOnNetwork, + transactionOnNetwork: TransactionOnNetwork, ): SmartContractCallOutcome | null { const argSerializer = new ArgSerializer(); - const eligibleResults: IContractResultItem[] = []; + const eligibleResults: SmartContractResult[] = []; - for (const result of transactionOnNetwork.contractResults.items) { - const matchesCriteriaOnData = result.data.startsWith(ARGUMENTS_SEPARATOR); + for (const result of transactionOnNetwork.smartContractResults) { + const matchesCriteriaOnData = result.data.toString().startsWith(ARGUMENTS_SEPARATOR); const matchesCriteriaOnReceiver = result.receiver.bech32() === transactionOnNetwork.sender.bech32(); - const matchesCriteriaOnPreviousHash = result.previousHash === transactionOnNetwork.hash; + const matchesCriteriaOnPreviousHash = result; const matchesCriteria = matchesCriteriaOnData && matchesCriteriaOnReceiver && matchesCriteriaOnPreviousHash; if (matchesCriteria) { @@ -201,22 +198,22 @@ export class SmartContractTransactionsOutcomeParser { } const [result] = eligibleResults; - const [_ignored, returnCode, ...returnDataParts] = argSerializer.stringToBuffers(result.data); - + const [_ignored, returnCode, ...returnDataParts] = argSerializer.stringToBuffers(result.data.toString()); return new SmartContractCallOutcome({ function: transactionOnNetwork.function, returnCode: returnCode?.toString(), - returnMessage: result.returnMessage || returnCode?.toString(), + returnMessage: result.raw["returnMessage"] || returnCode?.toString(), returnDataParts: returnDataParts, }); } protected findDirectSmartContractCallOutcomeIfError( - transactionOnNetwork: ITransactionOnNetwork, + transactionOnNetwork: TransactionOnNetwork, ): SmartContractCallOutcome | null { + console.log("findDirectSmartContractCallOutcomeIfError"); const argSerializer = new ArgSerializer(); const eventIdentifier = Events.SignalError; - const eligibleEvents: ITransactionEvent[] = []; + const eligibleEvents: TransactionEvent[] = []; // First, look in "logs": eligibleEvents.push( @@ -224,8 +221,8 @@ export class SmartContractTransactionsOutcomeParser { ); // Then, look in "logs" of "contractResults": - for (const result of transactionOnNetwork.contractResults.items) { - if (result.previousHash != transactionOnNetwork.hash) { + for (const result of transactionOnNetwork.smartContractResults) { + if (result.raw["prevTxHash"] != transactionOnNetwork.hash) { continue; } @@ -248,7 +245,7 @@ export class SmartContractTransactionsOutcomeParser { const parts = argSerializer.stringToBuffers(data); // Assumption: the last part is the return code. const returnCode = parts[parts.length - 1]; - + console.log(11111111, returnCode, parts); return new SmartContractCallOutcome({ function: transactionOnNetwork.function, returnCode: returnCode?.toString() || eventIdentifier, @@ -258,11 +255,11 @@ export class SmartContractTransactionsOutcomeParser { } protected findDirectSmartContractCallOutcomeWithinWriteLogEvents( - transactionOnNetwork: ITransactionOnNetwork, + transactionOnNetwork: TransactionOnNetwork, ): SmartContractCallOutcome | null { const argSerializer = new ArgSerializer(); const eventIdentifier = Events.WriteLog; - const eligibleEvents: ITransactionEvent[] = []; + const eligibleEvents: TransactionEvent[] = []; // First, look in "logs": eligibleEvents.push( @@ -270,8 +267,8 @@ export class SmartContractTransactionsOutcomeParser { ); // Then, look in "logs" of "contractResults": - for (const result of transactionOnNetwork.contractResults.items) { - if (result.previousHash != transactionOnNetwork.hash) { + for (const result of transactionOnNetwork.smartContractResults) { + if (result.raw["prevTxHash"] != transactionOnNetwork.hash) { continue; } diff --git a/src/testutils/contractController.ts b/src/testutils/contractController.ts index b8643fcf3..fe2604239 100644 --- a/src/testutils/contractController.ts +++ b/src/testutils/contractController.ts @@ -1,7 +1,7 @@ import { Interaction, ResultsParser, TypedOutcomeBundle, UntypedOutcomeBundle } from "../abi"; -import { ITransactionOnNetwork } from "../interfaceOfNetwork"; import { Logger } from "../logger"; import { Transaction } from "../transaction"; +import { TransactionOnNetwork } from "../transactions"; import { TransactionWatcher } from "../transactionWatcher"; import { INetworkProvider } from "./networkProviders"; @@ -22,7 +22,7 @@ export class ContractController { async deploy( transaction: Transaction, - ): Promise<{ transactionOnNetwork: ITransactionOnNetwork; bundle: UntypedOutcomeBundle }> { + ): Promise<{ transactionOnNetwork: TransactionOnNetwork; bundle: UntypedOutcomeBundle }> { const txHash = await this.provider.sendTransaction(transaction); Logger.info(`ContractController.deploy [begin]: transaction = ${txHash}`); @@ -36,7 +36,7 @@ export class ContractController { async execute( interaction: Interaction, transaction: Transaction, - ): Promise<{ transactionOnNetwork: ITransactionOnNetwork; bundle: TypedOutcomeBundle }> { + ): Promise<{ transactionOnNetwork: TransactionOnNetwork; bundle: TypedOutcomeBundle }> { const txHash = await this.provider.sendTransaction(transaction); Logger.info( `ContractController.execute [begin]: function = ${interaction.getFunction()}, transaction = ${txHash}`, diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index ab44b1eea..e83810c04 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -4,16 +4,11 @@ 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 { ContractResultItem, ContractResults, TransactionStatus } from "../networkProviders"; +import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionStatus } from "../interfaceOfNetwork"; import { Transaction, TransactionHash } from "../transaction"; import { TransactionOnNetwork } from "../transactions"; +import { SmartContractResult } from "../transactionsOutcomeParsers"; +import { TransactionStatus } from "../transactionStatus"; import { createAccountBalance } from "./utils"; export class MockNetworkProvider { @@ -49,7 +44,7 @@ export class MockNetworkProvider { } } - mockUpdateTransaction(hash: TransactionHash, mutate: (item: ITransactionOnNetwork) => void) { + mockUpdateTransaction(hash: TransactionHash, mutate: (item: TransactionOnNetwork) => void) { let transaction = this.transactions.get(hash.toString()); if (transaction) { mutate(transaction); @@ -67,12 +62,12 @@ export class MockNetworkProvider { } mockGetTransactionWithAnyHashAsNotarizedWithOneResult(returnCodeAndData: string) { - let contractResult = new ContractResultItem({ nonce: 1, data: returnCodeAndData }); + let contractResult = new SmartContractResult({ data: Buffer.from(returnCodeAndData) }); let predicate = (_hash: string) => true; let response = new TransactionOnNetwork({ status: new TransactionStatus("executed"), - contractResults: new ContractResults([contractResult]), + smartContractResults: [contractResult], isCompleted: true, }); diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts index 25ee90ec9..9e508c8e2 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts @@ -1,25 +1,23 @@ import { assert } from "chai"; import { Address } from "../address"; import { ErrParseTransactionOutcome } from "../errors"; -import { ContractResultItem, ContractResults } from "../networkProviders"; -import { TransactionEvent, TransactionEventData, TransactionEventTopic } from "../transactionEvents"; +import { b64TopicsToBytes } from "../testutils"; +import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; +import { SmartContractResult } from "../transactionsOutcomeParsers"; import { TokenManagementTransactionsOutcomeParser } from "./tokenManagementTransactionsOutcomeParser"; describe("test token management transactions outcome parser", () => { const parser = new TokenManagementTransactionsOutcomeParser(); it("should test ensure error", () => { - const encodedTopics = [ - new TransactionEventTopic("Avk0jZ1kR+l9c76wQQoYcu4hvXPz+jxxTdqQeaCrbX8="), - new TransactionEventTopic("dGlja2VyIG5hbWUgaXMgbm90IHZhbGlk"), - ]; + const encodedTopics = ["Avk0jZ1kR+l9c76wQQoYcu4hvXPz+jxxTdqQeaCrbX8=", "dGlja2VyIG5hbWUgaXMgbm90IHZhbGlk"]; const event = new TransactionEvent({ address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), identifier: "signalError", - topics: encodedTopics, - dataPayload: new TransactionEventData(Buffer.from("QDc1NzM2NTcyMjA2NTcyNzI2Zjcy", "base64")), + topics: b64TopicsToBytes(encodedTopics), + additionalData: [Buffer.from("QDc1NzM2NTcyMjA2NTcyNzI2Zjcy", "base64")], }); const logs = new TransactionLogs({ events: [event] }); @@ -38,17 +36,11 @@ describe("test token management transactions outcome parser", () => { const identifier = "ZZZ-9ee87d"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic("U0VDT05E"), - new TransactionEventTopic("Wlpa"), - new TransactionEventTopic("RnVuZ2libGVFU0RU"), - new TransactionEventTopic("Ag=="), - ]; + const encodedTopics = [base64Identifier, "U0VDT05E", "Wlpa", "RnVuZ2libGVFU0RU", "Ag=="]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "issue", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const logs = new TransactionLogs({ @@ -68,41 +60,31 @@ describe("test token management transactions outcome parser", () => { const base64Identifier = Buffer.from(identifier).toString("base64"); let encodedTopics = [ - new TransactionEventTopic("TkZULWYwMWQxZQ=="), - new TransactionEventTopic(""), - new TransactionEventTopic("Y2FuVXBncmFkZQ=="), - new TransactionEventTopic("dHJ1ZQ=="), - new TransactionEventTopic("Y2FuQWRkU3BlY2lhbFJvbGVz"), - new TransactionEventTopic("dHJ1ZQ=="), + "TkZULWYwMWQxZQ==", + "", + "Y2FuVXBncmFkZQ==", + "dHJ1ZQ==", + "Y2FuQWRkU3BlY2lhbFJvbGVz", + "dHJ1ZQ==", ]; const firstEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "upgradeProperties", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); - encodedTopics = [ - new TransactionEventTopic("TkZULWYwMWQxZQ=="), - new TransactionEventTopic(""), - new TransactionEventTopic(""), - new TransactionEventTopic("RVNEVFJvbGVCdXJuRm9yQWxs"), - ]; + encodedTopics = ["TkZULWYwMWQxZQ==", "", "", "RVNEVFJvbGVCdXJuRm9yQWxs"]; const secondEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTSetBurnRoleForAll", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); - encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic("TkZURVNU"), - new TransactionEventTopic("TkZU"), - new TransactionEventTopic("Tm9uRnVuZ2libGVFU0RU"), - ]; + encodedTopics = [base64Identifier, "TkZURVNU", "TkZU", "Tm9uRnVuZ2libGVFU0RU"]; const thirdEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "issueNonFungible", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const logs = new TransactionLogs({ @@ -121,16 +103,11 @@ describe("test token management transactions outcome parser", () => { const identifier = "SEMIFNG-2c6d9f"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic("U0VNSQ=="), - new TransactionEventTopic("U0VNSUZORw=="), - new TransactionEventTopic("U2VtaUZ1bmdpYmxlRVNEVA=="), - ]; + const encodedTopics = [base64Identifier, "U0VNSQ==", "U0VNSUZORw==", "U2VtaUZ1bmdpYmxlRVNEVA=="]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "issueSemiFungible", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const logs = new TransactionLogs({ @@ -149,16 +126,11 @@ describe("test token management transactions outcome parser", () => { const identifier = "METATEST-e05d11"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic("TUVURVNU"), - new TransactionEventTopic("TUVUQVRFU1Q="), - new TransactionEventTopic("TWV0YUVTRFQ="), - ]; + const encodedTopics = [base64Identifier, "TUVURVNU", "TUVUQVRFU1Q=", "TWV0YUVTRFQ="]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "registerMetaESDT", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const logs = new TransactionLogs({ @@ -182,30 +154,18 @@ describe("test token management transactions outcome parser", () => { const roles = ["ESDTRoleLocalMint", "ESDTRoleLocalBurn"]; - let encodedTopics = [ - new TransactionEventTopic(firstBase64Identifier), - new TransactionEventTopic("TE1BTw=="), - new TransactionEventTopic("TE1BTw=="), - new TransactionEventTopic("RnVuZ2libGVFU0RU"), - new TransactionEventTopic("Ag=="), - ]; + let encodedTopics = [firstBase64Identifier, "TE1BTw==", "TE1BTw==", "RnVuZ2libGVFU0RU", "Ag=="]; const firstEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "registerAndSetAllRoles", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); - encodedTopics = [ - new TransactionEventTopic(secondBase64Identifier), - new TransactionEventTopic("TE1BTw=="), - new TransactionEventTopic("TE1BTw=="), - new TransactionEventTopic("RnVuZ2libGVFU0RU"), - new TransactionEventTopic("Ag=="), - ]; + encodedTopics = [secondBase64Identifier, "TE1BTw==", "TE1BTw==", "RnVuZ2libGVFU0RU", "Ag=="]; const secondEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "registerAndSetAllRoles", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -213,30 +173,18 @@ describe("test token management transactions outcome parser", () => { events: [firstEvent, secondEvent], }); - encodedTopics = [ - new TransactionEventTopic("TE1BTy1kOWY4OTI="), - new TransactionEventTopic(""), - new TransactionEventTopic(""), - new TransactionEventTopic("RVNEVFJvbGVMb2NhbE1pbnQ="), - new TransactionEventTopic("RVNEVFJvbGVMb2NhbEJ1cm4="), - ]; + encodedTopics = ["TE1BTy1kOWY4OTI=", "", "", "RVNEVFJvbGVMb2NhbE1pbnQ=", "RVNEVFJvbGVMb2NhbEJ1cm4="]; const firstResultEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTSetRole", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); - encodedTopics = [ - new TransactionEventTopic("VFNULTEyMzQ1Ng=="), - new TransactionEventTopic(""), - new TransactionEventTopic(""), - new TransactionEventTopic("RVNEVFJvbGVMb2NhbE1pbnQ="), - new TransactionEventTopic("RVNEVFJvbGVMb2NhbEJ1cm4="), - ]; + encodedTopics = ["VFNULTEyMzQ1Ng==", "", "", "RVNEVFJvbGVMb2NhbE1pbnQ=", "RVNEVFJvbGVMb2NhbEJ1cm4="]; const secondResultEvent = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTSetRole", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const resultLogs = new TransactionLogs({ @@ -244,17 +192,18 @@ describe("test token management transactions outcome parser", () => { events: [firstResultEvent, secondResultEvent], }); - const scResult = new ContractResults([ - new ContractResultItem({ - sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), - receiver: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), - data: "RVNEVFNldFJvbGVANGM0ZDQxNGYyZDY0Mzk2NjM4MzkzMkA0NTUzNDQ1NDUyNmY2YzY1NGM2ZjYzNjE2YzRkNjk2ZTc0QDQ1NTM0NDU0NTI2ZjZjNjU0YzZmNjM2MTZjNDI3NTcyNmU=", - logs: resultLogs, - }), - ]); + const scResult = new SmartContractResult({ + sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), + receiver: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + data: Buffer.from( + "RVNEVFNldFJvbGVANGM0ZDQxNGYyZDY0Mzk2NjM4MzkzMkA0NTUzNDQ1NDUyNmY2YzY1NGM2ZjYzNjE2YzRkNjk2ZTc0QDQ1NTM0NDU0NTI2ZjZjNjU0YzZmNjM2MTZjNDI3NTcyNmU=", + "base64", + ), + logs: resultLogs, + }); const txOutcome = new TransactionOnNetwork({ - contractResults: scResult, + smartContractResults: [scResult], logs: transactionLogs, }); @@ -274,17 +223,17 @@ describe("test token management transactions outcome parser", () => { const roles = ["ESDTRoleNFTCreate", "ESDTRoleNFTAddQuantity", "ESDTRoleNFTBurn"]; const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic(""), - new TransactionEventTopic(""), - new TransactionEventTopic("RVNEVFJvbGVORlRDcmVhdGU="), - new TransactionEventTopic("RVNEVFJvbGVORlRBZGRRdWFudGl0eQ=="), - new TransactionEventTopic("RVNEVFJvbGVORlRCdXJu"), + base64Identifier, + "", + "", + "RVNEVFJvbGVORlRDcmVhdGU=", + "RVNEVFJvbGVORlRBZGRRdWFudGl0eQ==", + "RVNEVFJvbGVORlRCdXJu", ]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTSetRole", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -313,17 +262,15 @@ describe("test token management transactions outcome parser", () => { const initialQuantity = BigInt(1); const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic("AQ=="), - new TransactionEventTopic("AQ=="), - new TransactionEventTopic( - "CAESAgABIuUBCAESCE5GVEZJUlNUGiA8NdfqyxqZpKDMqlN+8MwK4Qn0H2wrQCID5jO/uwcfXCDEEyouUW1ZM3ZKQ3NVcWpNM3hxeGR3VWczemJoVFNMUWZoN0szbW5aWXhyaGNRRFl4RzJDaHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1ZM3ZKQ3NVcWpNM3hxeGR3VWczemJoVFNMUWZoN0szbW5aWXhyaGNRRFl4Rzo9dGFnczo7bWV0YWRhdGE6UW1SY1A5NGtYcjV6WmpSR3ZpN21KNnVuN0xweFVoWVZSNFI0UnBpY3h6Z1lrdA==", - ), + base64Identifier, + "AQ==", + "AQ==", + "CAESAgABIuUBCAESCE5GVEZJUlNUGiA8NdfqyxqZpKDMqlN+8MwK4Qn0H2wrQCID5jO/uwcfXCDEEyouUW1ZM3ZKQ3NVcWpNM3hxeGR3VWczemJoVFNMUWZoN0szbW5aWXhyaGNRRFl4RzJDaHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1ZM3ZKQ3NVcWpNM3hxeGR3VWczemJoVFNMUWZoN0szbW5aWXhyaGNRRFl4Rzo9dGFnczo7bWV0YWRhdGE6UW1SY1A5NGtYcjV6WmpSR3ZpN21KNnVuN0xweFVoWVZSNFI0UnBpY3h6Z1lrdA==", ]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTNFTCreate", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -348,15 +295,11 @@ describe("test token management transactions outcome parser", () => { const nonce = BigInt(0); const mintedSupply = BigInt(100000); - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic(""), - new TransactionEventTopic("AYag"), - ]; + const encodedTopics = [base64Identifier, "", "AYag"]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTLocalMint", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -382,15 +325,11 @@ describe("test token management transactions outcome parser", () => { const nonce = BigInt(0); const burntSupply = BigInt(100000); - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic(""), - new TransactionEventTopic("AYag"), - ]; + const encodedTopics = [base64Identifier, "", "AYag"]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTLocalBurn", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -414,11 +353,11 @@ describe("test token management transactions outcome parser", () => { const identifier = "AAA-29c4c9"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [new TransactionEventTopic(base64Identifier)]; + const encodedTopics = [base64Identifier]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTPause", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -439,11 +378,11 @@ describe("test token management transactions outcome parser", () => { const identifier = "AAA-29c4c9"; const base64Identifier = Buffer.from(identifier).toString("base64"); - const encodedTopics = [new TransactionEventTopic(base64Identifier)]; + const encodedTopics = [base64Identifier]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTUnPause", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -467,16 +406,11 @@ describe("test token management transactions outcome parser", () => { const balance = BigInt(10000000); const address = "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"; - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic(""), - new TransactionEventTopic("mJaA"), - new TransactionEventTopic("ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="), - ]; + const encodedTopics = [base64Identifier, "", "mJaA", "ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="]; const event = new TransactionEvent({ address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), identifier: "ESDTFreeze", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -484,17 +418,17 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const scResult = new ContractResults([ - new ContractResultItem({ + const scResult = [ + new SmartContractResult({ sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), receiver: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), - data: "RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", + data: Buffer.from("RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ=="), logs: transactionLogs, }), - ]); + ]; const txOutcome = new TransactionOnNetwork({ - contractResults: scResult, + smartContractResults: scResult, }); const outcome = parser.parseFreeze(txOutcome); @@ -512,16 +446,11 @@ describe("test token management transactions outcome parser", () => { const balance = BigInt(10000000); const address = "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"; - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic(""), - new TransactionEventTopic("mJaA"), - new TransactionEventTopic("ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="), - ]; + const encodedTopics = [base64Identifier, "", "mJaA", "ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="]; const event = new TransactionEvent({ address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), identifier: "ESDTUnFreeze", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -529,17 +458,17 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const scResult = new ContractResults([ - new ContractResultItem({ + const scResult = [ + new SmartContractResult({ sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), receiver: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), - data: "RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", + data: Buffer.from("RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ=="), logs: transactionLogs, }), - ]); + ]; const txOutcome = new TransactionOnNetwork({ - contractResults: scResult, + smartContractResults: scResult, }); const outcome = parser.parseUnfreeze(txOutcome); @@ -557,16 +486,11 @@ describe("test token management transactions outcome parser", () => { const balance = BigInt(10000000); const address = "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"; - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic(""), - new TransactionEventTopic("mJaA"), - new TransactionEventTopic("ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="), - ]; + const encodedTopics = [base64Identifier, "", "mJaA", "ATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeE="]; const event = new TransactionEvent({ address: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), identifier: "ESDTWipe", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -574,18 +498,16 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const scResult = new ContractResults([ - new ContractResultItem({ + const scResult = [ + new SmartContractResult({ sender: new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), receiver: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), - data: "RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ==", + data: Buffer.from("RVNEVEZyZWV6ZUA0MTQxNDEyZDMyMzk2MzM0NjMzOQ=="), logs: transactionLogs, }), - ]); + ]; - const txOutcome = new TransactionOnNetwork({ - contractResults: scResult, - }); + const txOutcome = new TransactionOnNetwork({ smartContractResults: scResult }); const outcome = parser.parseWipe(txOutcome); assert.lengthOf(outcome, 1); @@ -602,16 +524,11 @@ describe("test token management transactions outcome parser", () => { const attributes = "metadata:ipfsCID/test.json;tags:tag1,tag2"; const base64Attributes = Buffer.from(attributes).toString("base64"); - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic("AQ=="), - new TransactionEventTopic(""), - new TransactionEventTopic(base64Attributes), - ]; + const encodedTopics = [base64Identifier, "AQ==", "", base64Attributes]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTNFTUpdateAttributes", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -636,15 +553,11 @@ describe("test token management transactions outcome parser", () => { const nonce = BigInt(1); const addedQuantity = BigInt(10); - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic("AQ=="), - new TransactionEventTopic("Cg=="), - ]; + const encodedTopics = [base64Identifier, "AQ==", "Cg=="]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTNFTAddQuantity", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ @@ -669,15 +582,11 @@ describe("test token management transactions outcome parser", () => { const nonce = BigInt(1); const burntQuantity = BigInt(16); - const encodedTopics = [ - new TransactionEventTopic(base64Identifier), - new TransactionEventTopic("AQ=="), - new TransactionEventTopic("EA=="), - ]; + const encodedTopics = [base64Identifier, "AQ==", "EA=="]; const event = new TransactionEvent({ address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), identifier: "ESDTNFTBurn", - topics: encodedTopics, + topics: b64TopicsToBytes(encodedTopics), }); const transactionLogs = new TransactionLogs({ diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index 44dd8f92e..bc12931a4 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -1,8 +1,7 @@ import { bufferToBigInt } from "../abi/codec/utils"; import { Address } from "../address"; import { ErrParseTransactionOutcome } from "../errors"; -import { ITransactionEvent } from "../interfaceOfNetwork"; -import { TransactionEvent, TransactionEventTopic } from "../transactionEvents"; +import { TransactionEvent } from "../transactionEvents"; import { TransactionOnNetwork } from "../transactions"; import { findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; import { MintNftOutput, SpecialRoleOutput } from "./resources"; @@ -52,7 +51,7 @@ export class TokenManagementTransactionsOutcomeParser { return registerEvents.map((registerEvent, index) => { const tokenIdentifier = this.extractTokenIdentifier(registerEvent); const encodedRoles = setRoleEvents[index].topics.slice(3); - const roles = encodedRoles.map((role) => role.toString()); + const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); return { tokenIdentifier, roles }; }); } @@ -76,7 +75,7 @@ export class TokenManagementTransactionsOutcomeParser { const userAddress = event.address; const tokenIdentifier = this.extractTokenIdentifier(event); const encodedRoles = event.topics.slice(3); - const roles = encodedRoles.map((role) => role.toString()); + const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); return { userAddress: userAddress, tokenIdentifier: tokenIdentifier, roles: roles }; } @@ -272,7 +271,7 @@ export class TokenManagementTransactionsOutcomeParser { parseUpdateAttributes(transaction: TransactionOnNetwork): { tokenIdentifier: string; nonce: bigint; - attributes: TransactionEventTopic; + attributes: Uint8Array; }[] { this.ensureNoError(transaction.logs.events); @@ -283,11 +282,11 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForUpdateAttributesEvent(event: TransactionEvent): { tokenIdentifier: string; nonce: bigint; - attributes: TransactionEventTopic; + attributes: Uint8Array; } { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const attributes = event.topics[3] ? event.topics[3] : new TransactionEventTopic(""); + const attributes = event.topics[3] ? event.topics[3] : Buffer.from(""); return { tokenIdentifier: tokenIdentifier, @@ -350,11 +349,11 @@ export class TokenManagementTransactionsOutcomeParser { }; } - private ensureNoError(transactionEvents: ITransactionEvent[]) { + private ensureNoError(transactionEvents: TransactionEvent[]) { for (const event of transactionEvents) { if (event.identifier == "signalError") { - const data = event.dataPayload?.toString().slice(1) || ""; - const message = event.topics[1].toString(); + const data = Buffer.from(event.additionalData[0]?.toString().slice(1)).toString() || ""; + const message = this.decodeTopicAsString(event.topics[1]); throw new ErrParseTransactionOutcome( `encountered signalError: ${message} (${Buffer.from(data, "hex").toString()})`, @@ -364,14 +363,14 @@ export class TokenManagementTransactionsOutcomeParser { } private extractTokenIdentifier(event: TransactionEvent): string { - if (!event.topics[0].toString()?.length) { + if (!event.topics[0]?.length) { return ""; } return event.topics[0].toString(); } private extractNonce(event: TransactionEvent): bigint { - if (!event.topics[1].toString()?.length) { + if (!event.topics[1]?.length) { return BigInt(0); } const nonce = Buffer.from(event.topics[1]); @@ -379,7 +378,7 @@ export class TokenManagementTransactionsOutcomeParser { } private extractAmount(event: TransactionEvent): bigint { - if (!event.topics[2].toString()?.length) { + if (!event.topics[2]?.length) { return BigInt(0); } const amount = Buffer.from(event.topics[2]); @@ -387,10 +386,14 @@ export class TokenManagementTransactionsOutcomeParser { } private extractAddress(event: TransactionEvent): string { - if (!event.topics[3].toString()?.length) { + if (!event.topics[3]?.length) { return ""; } const address = Buffer.from(event.topics[3]); return new Address(address).bech32(); } + + private decodeTopicAsString(topic: Uint8Array): string { + return Buffer.from(topic).toString(); + } } diff --git a/src/transaction.ts b/src/transaction.ts index d6911146f..0921bfcb7 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -177,21 +177,21 @@ export class Transaction { /** * Legacy method, use the "sender" property instead. */ - getSender(): IAddress { + getSender(): Address { return Address.fromBech32(this.sender); } /** * Legacy method, use the "sender" property instead. */ - setSender(sender: IAddress | string) { + setSender(sender: Address | string) { this.sender = typeof sender === "string" ? sender : sender.bech32(); } /** * Legacy method, use the "receiver" property instead. */ - getReceiver(): IAddress { + getReceiver(): Address { return Address.fromBech32(this.receiver); } @@ -226,7 +226,7 @@ export class Transaction { /** * Legacy method, use the "guardian" property instead. */ - getGuardian(): IAddress { + getGuardian(): Address { return new Address(this.guardian); } diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index 5650fd312..25cf07ee5 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -3,14 +3,14 @@ import { Address } from "./address"; export class TransactionEvent { address: Address = Address.empty(); identifier: string = ""; - topics: TransactionEventTopic[] = []; + topics: Uint8Array[] = []; /** * @deprecated Use "dataPayload" instead. */ data: string = ""; - dataPayload: TransactionEventData = new TransactionEventData(Buffer.from("", "utf8")); - additionalData: TransactionEventData[] = []; + dataPayload: Uint8Array = new Uint8Array(); + additionalData: Uint8Array[] = []; constructor(init?: Partial) { Object.assign(this, init); @@ -26,64 +26,20 @@ export class TransactionEvent { let result = new TransactionEvent(); result.address = new Address(responsePart.address); result.identifier = responsePart.identifier || ""; - result.topics = (responsePart.topics || []).map((topic) => new TransactionEventTopic(topic)); + result.topics = (responsePart.topics || []).map((topic) => Buffer.from(topic)); - result.dataPayload = TransactionEventData.fromBase64(responsePart.data); - result.additionalData = (responsePart.additionalData || []).map(TransactionEventData.fromBase64); + result.dataPayload = Buffer.from(responsePart.data); + result.additionalData = (responsePart.additionalData || []).map((data) => Buffer.from(data)); result.data = result.dataPayload.toString(); return result; } - findFirstOrNoneTopic(predicate: (topic: TransactionEventTopic) => boolean): TransactionEventTopic | undefined { + findFirstOrNoneTopic(predicate: (topic: Uint8Array) => boolean): Uint8Array | undefined { return this.topics.filter((topic) => predicate(topic))[0]; } - getLastTopic(): TransactionEventTopic { + getLastTopic(): Uint8Array { return this.topics[this.topics.length - 1]; } } - -export class TransactionEventData { - private readonly raw: Buffer; - - constructor(data: Buffer) { - this.raw = data; - } - - static fromBase64(str: string): TransactionEventData { - return new TransactionEventData(Buffer.from(str || "", "base64")); - } - - toString(): string { - return this.raw.toString("utf8"); - } - - hex(): string { - return this.raw.toString("hex"); - } - - valueOf(): Buffer { - return this.raw; - } -} - -export class TransactionEventTopic { - private readonly raw: Buffer; - - constructor(topic: string) { - this.raw = Buffer.from(topic || "", "base64"); - } - - toString(): string { - return this.raw.toString("utf8"); - } - - hex(): string { - return this.raw.toString("hex"); - } - - valueOf(): Buffer { - return this.raw; - } -} diff --git a/src/networkProviders/transactionStatus.ts b/src/transactionStatus.ts similarity index 100% rename from src/networkProviders/transactionStatus.ts rename to src/transactionStatus.ts diff --git a/src/transactionWatcher.spec.ts b/src/transactionWatcher.spec.ts index 0f2cc2cce..f459d7240 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/transactionWatcher.spec.ts @@ -1,9 +1,9 @@ import { assert } from "chai"; -import { TransactionStatus } from "./networkProviders"; import { MarkCompleted, MockNetworkProvider, Wait } from "./testutils"; import { TransactionHash } from "./transaction"; -import { TransactionWatcher } from "./transactionWatcher"; import { TransactionOnNetwork } from "./transactions"; +import { TransactionStatus } from "./transactionStatus"; +import { TransactionWatcher } from "./transactionWatcher"; describe("test transactionWatcher", () => { it("should await status == executed using hash", async () => { diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index f21b760c3..619093d30 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -7,8 +7,9 @@ import { ErrIsCompletedFieldIsMissingOnTransaction, } from "./errors"; import { ITransactionFetcher } from "./interface"; -import { ITransactionEvent, ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork"; +import { ITransactionStatus } from "./interfaceOfNetwork"; import { Logger } from "./logger"; +import { TransactionEvent } from "./transactionEvents"; import { TransactionOnNetwork } from "./transactions"; export type PredicateIsAwaitedStatus = (status: ITransactionStatus) => boolean; @@ -63,15 +64,15 @@ export class TransactionWatcher { * Waits until the transaction reaches the "pending" status. * @param txHash The hex-encoded transaction hash */ - public async awaitPending(transactionOrTxHash: ITransaction | string): Promise { - const isPending = (transaction: ITransactionOnNetwork) => transaction.status.isPending(); + public async awaitPending(transactionOrTxHash: ITransaction | string): Promise { + const isPending = (transaction: TransactionOnNetwork) => transaction.status.isPending(); const doFetch = async () => { const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); return await this.fetcher.getTransaction(hash); }; const errorProvider = () => new ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(isPending, doFetch, errorProvider); + return this.awaitConditionally(isPending, doFetch, errorProvider); } /** @@ -79,7 +80,7 @@ export class TransactionWatcher { * @param txHash The hex-encoded transaction hash */ public async awaitCompleted(transactionOrTxHash: ITransaction | string): Promise { - const isCompleted = (transactionOnNetwork: ITransactionOnNetwork) => { + const isCompleted = (transactionOnNetwork: TransactionOnNetwork) => { if (transactionOnNetwork.isCompleted === undefined) { throw new ErrIsCompletedFieldIsMissingOnTransaction(); } @@ -98,8 +99,8 @@ export class TransactionWatcher { public async awaitAllEvents( transactionOrTxHash: ITransaction | string, events: string[], - ): Promise { - const foundAllEvents = (transactionOnNetwork: ITransactionOnNetwork) => { + ): Promise { + const foundAllEvents = (transactionOnNetwork: TransactionOnNetwork) => { const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map( (event) => event.identifier, ); @@ -113,14 +114,14 @@ export class TransactionWatcher { }; const errorProvider = () => new ErrExpectedTransactionEventsNotFound(); - return this.awaitConditionally(foundAllEvents, doFetch, errorProvider); + return this.awaitConditionally(foundAllEvents, doFetch, errorProvider); } public async awaitAnyEvent( transactionOrTxHash: ITransaction | string, events: string[], - ): Promise { - const foundAnyEvent = (transactionOnNetwork: ITransactionOnNetwork) => { + ): Promise { + const foundAnyEvent = (transactionOnNetwork: TransactionOnNetwork) => { const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map( (event) => event.identifier, ); @@ -134,20 +135,20 @@ export class TransactionWatcher { }; const errorProvider = () => new ErrExpectedTransactionEventsNotFound(); - return this.awaitConditionally(foundAnyEvent, doFetch, errorProvider); + return this.awaitConditionally(foundAnyEvent, doFetch, errorProvider); } public async awaitOnCondition( transactionOrTxHash: ITransaction | string, - condition: (data: ITransactionOnNetwork) => boolean, - ): Promise { + condition: (data: TransactionOnNetwork) => boolean, + ): Promise { const doFetch = async () => { const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); return await this.fetcher.getTransaction(hash); }; const errorProvider = () => new ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(condition, doFetch, errorProvider); + return this.awaitConditionally(condition, doFetch, errorProvider); } private transactionOrTxHashToTxHash(transactionOrTxHash: ITransaction | string): string { @@ -219,10 +220,10 @@ export class TransactionWatcher { return fetchedData; } - protected getAllTransactionEvents(transaction: ITransactionOnNetwork): ITransactionEvent[] { + protected getAllTransactionEvents(transaction: TransactionOnNetwork): TransactionEvent[] { const result = [...transaction.logs.events]; - for (const resultItem of transaction.contractResults.items) { + for (const resultItem of transaction.smartContractResults) { result.push(...resultItem.logs.events); } diff --git a/src/transactions.ts b/src/transactions.ts index 7fac1c86e..da1cbe98d 100644 --- a/src/transactions.ts +++ b/src/transactions.ts @@ -1,9 +1,8 @@ import { Address } from "./address"; -import { ContractResults } from "./networkProviders/contractResults"; -import { IAddress, ITransaction, ITransactionNext } from "./networkProviders/interface"; -import { TransactionReceipt } from "./networkProviders/transactionReceipt"; -import { TransactionStatus } from "./networkProviders/transactionStatus"; +import { ITransaction, ITransactionNext } from "./networkProviders/interface"; import { TransactionLogs } from "./transactionLogs"; +import { SmartContractResult } from "./transactionsOutcomeParsers"; +import { TransactionStatus } from "./transactionStatus"; export function prepareTransactionForBroadcasting(transaction: ITransaction | ITransactionNext): any { if ("toSendable" in transaction) { @@ -44,8 +43,8 @@ export class TransactionOnNetwork { round: number = 0; epoch: number = 0; value: string = ""; - receiver: IAddress = Address.empty(); - sender: IAddress = Address.empty(); + receiver: Address = Address.empty(); + sender: Address = Address.empty(); gasLimit: number = 0; gasPrice: number = 0; function: string = ""; @@ -58,8 +57,7 @@ export class TransactionOnNetwork { hyperblockNonce: number = 0; hyperblockHash: string = ""; - receipt: TransactionReceipt = new TransactionReceipt(); - contractResults: ContractResults = new ContractResults([]); + smartContractResults: SmartContractResult[] = []; logs: TransactionLogs = new TransactionLogs(); constructor(init?: Partial) { @@ -72,8 +70,7 @@ export class TransactionOnNetwork { processStatus?: TransactionStatus | undefined, ): TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); - result.contractResults = ContractResults.fromProxyHttpResponse(response.smartContractResults || []); - + result.smartContractResults = response.smartContractResults; if (processStatus) { result.status = processStatus; result.isCompleted = result.status.isSuccessful() || result.status.isFailed(); @@ -84,7 +81,7 @@ export class TransactionOnNetwork { static fromApiHttpResponse(txHash: string, response: any): TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); - result.contractResults = ContractResults.fromApiHttpResponse(response.results || []); + result.smartContractResults = response.results; result.isCompleted = !result.status.isPending(); return result; } @@ -111,7 +108,6 @@ export class TransactionOnNetwork { result.hyperblockNonce = response.hyperblockNonce || 0; result.hyperblockHash = response.hyperblockHash || ""; - result.receipt = TransactionReceipt.fromHttpResponse(response.receipt || {}); result.logs = TransactionLogs.fromHttpResponse(response.logs || {}); return result; diff --git a/src/transactionsOutcomeParsers/resources.spec.ts b/src/transactionsOutcomeParsers/resources.spec.ts index 26967cf6d..c22903936 100644 --- a/src/transactionsOutcomeParsers/resources.spec.ts +++ b/src/transactionsOutcomeParsers/resources.spec.ts @@ -1,9 +1,8 @@ import { assert } from "chai"; -import { ContractResultItem, ContractResults } from "../networkProviders/contractResults"; -import { TransactionEvent, TransactionEventTopic } from "../transactionEvents"; +import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; -import { findEventsByFirstTopic, findEventsByIdentifier } from "./resources"; +import { findEventsByFirstTopic, findEventsByIdentifier, SmartContractResult } from "./resources"; describe("test resources", () => { it("finds events by identifier, by first topic", async function () { @@ -12,26 +11,26 @@ describe("test resources", () => { events: [ new TransactionEvent({ identifier: "foo", - topics: [new TransactionEventTopic("a")], + topics: [Buffer.from("a")], }), ], }), - contractResults: new ContractResults([ - new ContractResultItem({ + smartContractResults: [ + new SmartContractResult({ logs: new TransactionLogs({ events: [ new TransactionEvent({ identifier: "foo", - topics: [new TransactionEventTopic("b")], + topics: [Buffer.from("b")], }), new TransactionEvent({ identifier: "bar", - topics: [new TransactionEventTopic("c")], + topics: [Buffer.from("c")], }), ], }), }), - ]), + ], }); const foundByIdentifierFoo = findEventsByIdentifier(outcome, "foo"); @@ -41,25 +40,25 @@ describe("test resources", () => { assert.deepEqual(foundByIdentifierFoo, [ new TransactionEvent({ identifier: "foo", - topics: [new TransactionEventTopic("a")], + topics: [Buffer.from("a")], }), new TransactionEvent({ identifier: "foo", - topics: [new TransactionEventTopic("b")], + topics: [Buffer.from("b")], }), ]); assert.deepEqual(foundByIdentifierBar, [ new TransactionEvent({ identifier: "bar", - topics: [new TransactionEventTopic("c")], + topics: [Buffer.from("c")], }), ]); assert.deepEqual(foundByTopic, [ new TransactionEvent({ identifier: "foo", - topics: [new TransactionEventTopic("b")], + topics: [Buffer.from("b")], }), ]); }); diff --git a/src/transactionsOutcomeParsers/resources.ts b/src/transactionsOutcomeParsers/resources.ts index df9c4694d..0e0da28f3 100644 --- a/src/transactionsOutcomeParsers/resources.ts +++ b/src/transactionsOutcomeParsers/resources.ts @@ -1,18 +1,21 @@ +import { Address } from "../address"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; export class SmartContractResult { - sender: string; - receiver: string; + raw: Record; + sender: Address; + receiver: Address; data: Uint8Array; logs: TransactionLogs; constructor(init: Partial) { - this.sender = ""; - this.receiver = ""; + this.sender = Address.empty(); + this.receiver = Address.empty(); this.data = new Uint8Array(); this.logs = new TransactionLogs({}); + this.raw = {}; Object.assign(this, init); } @@ -57,9 +60,10 @@ export function gatherAllEvents(transactionOutcome: TransactionOnNetwork): Trans allEvents.push(...transactionOutcome.logs.events); - for (const item of transactionOutcome.contractResults.items) { + for (const item of transactionOutcome.smartContractResults) { allEvents.push(...item.logs.events); } + console.log({ allEvents: JSON.stringify(allEvents) }); return allEvents; } diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts index 18ee3309b..30bbe6749 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts @@ -2,18 +2,11 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { AbiRegistry } from "../abi"; import { Address } from "../address"; -import { - ContractResultItem, - ContractResults, - TransactionEventData, - TransactionEventOnNetwork, - TransactionEventTopic, - TransactionLogsOnNetwork, -} from "../networkProviders"; -import { loadAbiRegistry } from "../testutils"; +import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; import { TransactionEvent } from "../transactionEvents"; +import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; -import { findEventsByFirstTopic } from "./resources"; +import { findEventsByFirstTopic, SmartContractResult } from "./resources"; import { TransactionEventsParser } from "./transactionEventsParser"; describe("test transaction events parser", () => { @@ -26,11 +19,11 @@ describe("test transaction events parser", () => { events: [ new TransactionEvent({ identifier: "transferOverMaxAmount", - topics: [ - new TransactionEventTopic(Buffer.from("transferOverMaxAmount").toString("base64")), - new TransactionEventTopic(Buffer.from([0x2a]).toString("base64")), - new TransactionEventTopic(Buffer.from([0x2b]).toString("base64")), - ], + topics: b64TopicsToBytes([ + Buffer.from("transferOverMaxAmount").toString("base64"), + Buffer.from([42]).toString("base64"), + Buffer.from([43]).toString("base64"), + ]), }), ], }); @@ -50,25 +43,24 @@ describe("test transaction events parser", () => { const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 8, - data: "@6f6b", - logs: new TransactionLogsOnNetwork({ + smartContractResults: [ + new SmartContractResult({ + data: Buffer.from("@6f6b"), + logs: new TransactionLogs({ events: [ - new TransactionEventOnNetwork({ + new TransactionEvent({ identifier: "deposit", - topics: [ - new TransactionEventTopic("ZGVwb3NpdA=="), - new TransactionEventTopic("cmzC1LRt1r10pMhNAnFb+FyudjGMq4G8CefCYdQUmmc="), - new TransactionEventTopic("AAAADFdFR0xELTAxZTQ5ZAAAAAAAAAAAAAAAAWQ="), - ], - additionalData: [new TransactionEventData(Buffer.from("AAAAAAAAA9sAAAA=", "base64"))], + topics: b64TopicsToBytes([ + "ZGVwb3NpdA==", + "cmzC1LRt1r10pMhNAnFb+FyudjGMq4G8CefCYdQUmmc=", + "AAAADFdFR0xELTAxZTQ5ZAAAAAAAAAAAAAAAAWQ=", + ]), + additionalData: [Buffer.from("AAAAAAAAA9sAAAA=", "base64")], }), ], }), }), - ]), + ], }); const events = findEventsByFirstTopic(transactionOnNetwork, "deposit"); @@ -101,23 +93,16 @@ describe("test transaction events parser", () => { const transactionOnNetwork = new TransactionOnNetwork({ nonce: 7, - contractResults: new ContractResults([ - new ContractResultItem({ - nonce: 8, - data: "@6f6b", - }), - ]), - logs: new TransactionLogsOnNetwork({ + smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b") })], + logs: new TransactionLogs({ events: [ - new TransactionEventOnNetwork({ + new TransactionEvent({ identifier: "performAction", - topics: [new TransactionEventTopic("c3RhcnRQZXJmb3JtQWN0aW9u")], + topics: b64TopicsToBytes(["c3RhcnRQZXJmb3JtQWN0aW9u"]), additionalData: [ - new TransactionEventData( - Buffer.from( - "00000001000000000500000000000000000500d006f73c4221216fa679bc559005584c4f1160e569e1000000000000000003616464000000010000000107000000010139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1", - "hex", - ), + Buffer.from( + "00000001000000000500000000000000000500d006f73c4221216fa679bc559005584c4f1160e569e1000000000000000003616464000000010000000107000000010139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1", + "hex", ), ], }), @@ -163,7 +148,7 @@ describe("test transaction events parser", () => { events: [ new TransactionEvent({ identifier: "foobar", - topics: [new TransactionEventTopic(Buffer.from("doFoobar").toString("base64"))], + topics: b64TopicsToBytes([Buffer.from("doFoobar").toString("base64")]), }), ], }); @@ -200,16 +185,16 @@ describe("test transaction events parser", () => { const parsed = parser.parseEvent({ event: new TransactionEvent({ identifier: "foobar", - topics: [ - new TransactionEventTopic(Buffer.from("doFoobar").toString("base64")), - new TransactionEventTopic(Buffer.from([42]).toString("base64")), - new TransactionEventTopic(Buffer.from("test").toString("base64")), - new TransactionEventTopic(Buffer.from([43]).toString("base64")), - new TransactionEventTopic(Buffer.from("test").toString("base64")), - new TransactionEventTopic(Buffer.from("test").toString("base64")), - new TransactionEventTopic(Buffer.from([44]).toString("base64")), - ], - additionalData: [new TransactionEventData(Buffer.from([42]))], + topics: b64TopicsToBytes([ + Buffer.from("doFoobar").toString("base64"), + Buffer.from([42]).toString("base64"), + Buffer.from("test").toString("base64"), + Buffer.from([43]).toString("base64"), + Buffer.from("test").toString("base64"), + Buffer.from("test").toString("base64"), + Buffer.from([44]).toString("base64"), + ]), + additionalData: [Buffer.from([42])], }), }); diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.ts b/src/transactionsOutcomeParsers/transactionEventsParser.ts index c4c58d8aa..7eb0363fc 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.ts @@ -29,7 +29,7 @@ export class TransactionEventsParser { } parseEvent(options: { event: TransactionEvent }): any { - const topics = options.event.topics.map((topic) => topic.valueOf()); + const topics = options.event.topics.map((topic) => Buffer.from(topic)); const abiIdentifier = this.firstTopicIsIdentifier ? topics[0]?.toString() : options.event.identifier; if (this.firstTopicIsIdentifier) { From 53ecc8c9627fdf74ab83e25f1d38a38d3964d9de Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 20 Nov 2024 16:03:37 +0200 Subject: [PATCH 040/214] Remove deprecated files --- src/abi/typesystem/abiRegistry.ts | 1 - src/index.ts | 1 - .../smartContractTransactionsOutcomeParser.ts | 2 - .../tokenManagementController.ts | 15 +- src/tokenOperations/index.ts | 3 - .../tokenOperationsFactory.spec.ts | 190 ----- .../tokenOperationsFactory.test.net.spec.ts | 688 ----------------- src/tokenOperations/tokenOperationsFactory.ts | 693 ------------------ .../tokenOperationsFactoryConfig.ts | 34 - .../tokenOperationsOutcomeParser.spec.ts | 116 --- .../tokenOperationsOutcomeParser.ts | 335 --------- src/transactionsOutcomeParsers/resources.ts | 1 - 12 files changed, 7 insertions(+), 2072 deletions(-) delete mode 100644 src/tokenOperations/index.ts delete mode 100644 src/tokenOperations/tokenOperationsFactory.spec.ts delete mode 100644 src/tokenOperations/tokenOperationsFactory.test.net.spec.ts delete mode 100644 src/tokenOperations/tokenOperationsFactory.ts delete mode 100644 src/tokenOperations/tokenOperationsFactoryConfig.ts delete mode 100644 src/tokenOperations/tokenOperationsOutcomeParser.spec.ts delete mode 100644 src/tokenOperations/tokenOperationsOutcomeParser.ts diff --git a/src/abi/typesystem/abiRegistry.ts b/src/abi/typesystem/abiRegistry.ts index f57c52102..60a6c46ff 100644 --- a/src/abi/typesystem/abiRegistry.ts +++ b/src/abi/typesystem/abiRegistry.ts @@ -133,7 +133,6 @@ export class AbiRegistry { } getEvent(name: string): EventDefinition { - console.log({ name }); const result = this.events.find((e) => e.identifier == name); guardValueIsSetWithMessage(`event [${name}] not found`, result); return result!; diff --git a/src/index.ts b/src/index.ts index 6b83ed2e7..d6cddccb1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,7 +30,6 @@ export * from "./relayedTransactionV2Builder"; export * from "./signableMessage"; export * from "./smartContractQueriesController"; export * from "./tokenManagement"; -export * from "./tokenOperations"; export * from "./tokens"; export * from "./transaction"; export * from "./transactionComputer"; diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 6bff67d64..0ddcc0568 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -210,7 +210,6 @@ export class SmartContractTransactionsOutcomeParser { protected findDirectSmartContractCallOutcomeIfError( transactionOnNetwork: TransactionOnNetwork, ): SmartContractCallOutcome | null { - console.log("findDirectSmartContractCallOutcomeIfError"); const argSerializer = new ArgSerializer(); const eventIdentifier = Events.SignalError; const eligibleEvents: TransactionEvent[] = []; @@ -245,7 +244,6 @@ export class SmartContractTransactionsOutcomeParser { const parts = argSerializer.stringToBuffers(data); // Assumption: the last part is the return code. const returnCode = parts[parts.length - 1]; - console.log(11111111, returnCode, parts); return new SmartContractCallOutcome({ function: transactionOnNetwork.function, returnCode: returnCode?.toString() || eventIdentifier, diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index 60aea8a10..d648f46b5 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -1,6 +1,5 @@ import { IAccount } from "../accounts/interfaces"; import { INetworkProvider } from "../networkProviders/interface"; -import { IESDTIssueOutcome } from "../tokenOperations"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; import { TransactionOnNetwork } from "../transactions"; @@ -38,12 +37,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedIssueFungible(txHash: string): Promise { + async awaitCompletedIssueFungible(txHash: string): Promise<{ tokenIdentifier: string }[]> { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseIssueFungible(transaction); } - parseIssueFungible(transactionOnNetwork: TransactionOnNetwork): IESDTIssueOutcome[] { + parseIssueFungible(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { return this.parser.parseIssueFungible(transactionOnNetwork); } @@ -82,7 +81,7 @@ export class TokenManagementController { return transaction; } - async awaitCompletedIssueNonFungible(txHash: string): Promise { + async awaitCompletedIssueNonFungible(txHash: string): Promise<{ tokenIdentifier: string }[]> { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseIssueNonFungible(transaction); } @@ -104,12 +103,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedRegisterMetaEsdt(txHash: string): Promise { + async awaitCompletedRegisterMetaEsdt(txHash: string): Promise<{ tokenIdentifier: string }[]> { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseRegisterMetaEsdt(transaction); } - parseRegisterMetaEsdt(transactionOnNetwork: TransactionOnNetwork): IESDTIssueOutcome[] { + parseRegisterMetaEsdt(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { return this.parser.parseRegisterMetaEsdt(transactionOnNetwork); } @@ -126,12 +125,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedRegisterAndSettingRoles(txHash: string): Promise { + async awaitCompletedRegisterAndSettingRoles(txHash: string): Promise<{ tokenIdentifier: string }[]> { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseRegisterAndSetAllRoles(transaction); } - parseRegisterAndSetAllRoles(transactionOnNetwork: TransactionOnNetwork): IESDTIssueOutcome[] { + parseRegisterAndSetAllRoles(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { return this.parser.parseRegisterMetaEsdt(transactionOnNetwork); } diff --git a/src/tokenOperations/index.ts b/src/tokenOperations/index.ts deleted file mode 100644 index 561db6c7b..000000000 --- a/src/tokenOperations/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./tokenOperationsFactory"; -export * from "./tokenOperationsFactoryConfig"; -export * from "./tokenOperationsOutcomeParser"; diff --git a/src/tokenOperations/tokenOperationsFactory.spec.ts b/src/tokenOperations/tokenOperationsFactory.spec.ts deleted file mode 100644 index f4e97ac6c..000000000 --- a/src/tokenOperations/tokenOperationsFactory.spec.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { assert } from "chai"; -import { loadTestWallets, TestWallet } from "../testutils"; -import { TokenOperationsFactory } from "./tokenOperationsFactory"; -import { TokenOperationsFactoryConfig } from "./tokenOperationsFactoryConfig"; - -describe("test factory", () => { - let frank: TestWallet, grace: TestWallet; - let factory: TokenOperationsFactory; - - before(async function () { - ({ frank, grace } = await loadTestWallets()); - factory = new TokenOperationsFactory(new TokenOperationsFactoryConfig("T")); - }); - - it("should create ", () => { - const transaction = factory.registerAndSetAllRoles({ - issuer: frank.address, - tokenName: "TEST", - tokenTicker: "TEST", - tokenType: "FNG", - numDecimals: 2, - transactionNonce: 42, - }); - - assert.equal(transaction.getData().toString(), "registerAndSetAllRoles@54455354@54455354@464e47@02"); - assert.equal(transaction.getNonce(), 42); - assert.equal(transaction.getSender().toString(), frank.address.toString()); - assert.equal( - transaction.getReceiver().toString(), - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - ); - }); - - it("should create ", () => { - const transaction = factory.issueFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - initialSupply: 100, - numDecimals: 0, - canFreeze: true, - canWipe: true, - canPause: true, - canChangeOwner: true, - canUpgrade: false, - canAddSpecialRoles: false, - transactionNonce: 42, - }); - - assert.equal( - transaction.getData().toString(), - "issue@4652414e4b@4652414e4b@64@@63616e467265657a65@74727565@63616e57697065@74727565@63616e5061757365@74727565@63616e4368616e67654f776e6572@74727565@63616e55706772616465@66616c7365@63616e4164645370656369616c526f6c6573@66616c7365", - ); - assert.equal(transaction.getNonce(), 42); - assert.equal(transaction.getSender().toString(), frank.address.toString()); - assert.equal( - transaction.getReceiver().toString(), - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - ); - }); - - it("should create ", () => { - const transaction = factory.issueSemiFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - canFreeze: true, - canWipe: true, - canPause: true, - canTransferNFTCreateRole: true, - canChangeOwner: true, - canUpgrade: false, - canAddSpecialRoles: false, - transactionNonce: 42, - }); - - assert.equal( - transaction.getData().toString(), - "issueSemiFungible@4652414e4b@4652414e4b@63616e467265657a65@74727565@63616e57697065@74727565@63616e5061757365@74727565@63616e5472616e736665724e4654437265617465526f6c65@74727565@63616e4368616e67654f776e6572@74727565@63616e55706772616465@66616c7365@63616e4164645370656369616c526f6c6573@66616c7365", - ); - assert.equal(transaction.getNonce(), 42); - assert.equal(transaction.getSender().toString(), frank.address.toString()); - assert.equal( - transaction.getReceiver().toString(), - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - ); - }); - - it("should create ", () => { - const transaction = factory.issueNonFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - canFreeze: true, - canWipe: true, - canPause: true, - canTransferNFTCreateRole: true, - canChangeOwner: true, - canUpgrade: false, - canAddSpecialRoles: false, - transactionNonce: 42, - }); - - assert.equal( - transaction.getData().toString(), - "issueNonFungible@4652414e4b@4652414e4b@63616e467265657a65@74727565@63616e57697065@74727565@63616e5061757365@74727565@63616e5472616e736665724e4654437265617465526f6c65@74727565@63616e4368616e67654f776e6572@74727565@63616e55706772616465@66616c7365@63616e4164645370656369616c526f6c6573@66616c7365", - ); - assert.equal(transaction.getNonce(), 42); - assert.equal(transaction.getSender().toString(), frank.address.toString()); - assert.equal( - transaction.getReceiver().toString(), - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - ); - }); - - it("should create ", () => { - const transaction = factory.registerMetaESDT({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - numDecimals: 10, - canFreeze: true, - canWipe: true, - canPause: true, - canTransferNFTCreateRole: true, - canChangeOwner: true, - canUpgrade: false, - canAddSpecialRoles: false, - transactionNonce: 42, - }); - - assert.equal( - transaction.getData().toString(), - "registerMetaESDT@4652414e4b@4652414e4b@0a@63616e467265657a65@74727565@63616e57697065@74727565@63616e5061757365@74727565@63616e5472616e736665724e4654437265617465526f6c65@74727565@63616e4368616e67654f776e6572@74727565@63616e55706772616465@66616c7365@63616e4164645370656369616c526f6c6573@66616c7365", - ); - assert.equal(transaction.getNonce(), 42); - assert.equal(transaction.getSender().toString(), frank.address.toString()); - assert.equal( - transaction.getReceiver().toString(), - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - ); - }); - - it("should create ", () => { - const transaction = factory.setSpecialRoleOnNonFungible({ - manager: frank.address, - user: grace.address, - tokenIdentifier: "FRANK-11ce3e", - addRoleNFTCreate: true, - addRoleNFTBurn: false, - addRoleNFTUpdateAttributes: true, - addRoleNFTAddURI: true, - addRoleESDTTransferRole: false, - transactionNonce: 42, - }); - - assert.equal( - transaction.getData().toString(), - "setSpecialRole@4652414e4b2d313163653365@1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13@45534454526f6c654e4654437265617465@45534454526f6c654e465455706461746541747472696275746573@45534454526f6c654e4654416464555249", - ); - assert.equal(transaction.getNonce(), 42); - assert.equal(transaction.getSender().toString(), frank.address.toString()); - assert.equal( - transaction.getReceiver().toString(), - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - ); - }); - - it("should create ", () => { - const transaction = factory.nftCreate({ - creator: grace.address, - tokenIdentifier: "FRANK-aa9e8d", - initialQuantity: 1, - name: `test`, - royalties: 1000, - hash: "abba", - attributes: Buffer.from("test"), - uris: ["a", "b"], - transactionNonce: 42, - }); - - assert.equal( - transaction.getData().toString(), - "ESDTNFTCreate@4652414e4b2d616139653864@01@74657374@03e8@61626261@74657374@61@62", - ); - assert.equal(transaction.getNonce(), 42); - assert.equal(transaction.getSender().toString(), grace.address.toString()); - assert.equal(transaction.getReceiver().toString(), grace.address.toString()); - }); -}); diff --git a/src/tokenOperations/tokenOperationsFactory.test.net.spec.ts b/src/tokenOperations/tokenOperationsFactory.test.net.spec.ts deleted file mode 100644 index 2ae574fa8..000000000 --- a/src/tokenOperations/tokenOperationsFactory.test.net.spec.ts +++ /dev/null @@ -1,688 +0,0 @@ -import { assert } from "chai"; -import { GasEstimator } from "../gasEstimator"; -import { INetworkConfig, ITransactionOnNetwork } from "../interfaceOfNetwork"; -import { TestWallet, loadTestWallets } from "../testutils"; -import { INetworkProvider, createTestnetProvider } from "../testutils/networkProviders"; -import { TokenTransfer } from "../tokens"; -import { Transaction } from "../transaction"; -import { TransactionWatcher } from "../transactionWatcher"; -import { TransferTransactionsFactory } from "../transactionsFactories/transferTransactionsFactory"; -import { TokenOperationsFactory } from "./tokenOperationsFactory"; -import { TokenOperationsFactoryConfig } from "./tokenOperationsFactoryConfig"; -import { TokenOperationsOutcomeParser } from "./tokenOperationsOutcomeParser"; - -describe("test factory on testnet", function () { - let frank: TestWallet, grace: TestWallet; - let provider: INetworkProvider; - let watcher: TransactionWatcher; - let network: INetworkConfig; - let factory: TokenOperationsFactory; - let parser: TokenOperationsOutcomeParser; - let transferTransactionsFactory: TransferTransactionsFactory; - - before(async function () { - console.log(`> ${this.currentTest?.title} ...`); - - ({ frank, grace } = await loadTestWallets()); - - provider = createTestnetProvider(); - watcher = new TransactionWatcher(provider, { patienceMilliseconds: 8000 }); - network = await provider.getNetworkConfig(); - factory = new TokenOperationsFactory(new TokenOperationsFactoryConfig(network.ChainID)); - parser = new TokenOperationsOutcomeParser(); - transferTransactionsFactory = new TransferTransactionsFactory(new GasEstimator()); - }); - - it("should register and set all roles (FNG)", async function () { - this.timeout(120000); - await frank.sync(provider); - - const tx1 = factory.registerAndSetAllRoles({ - issuer: frank.address, - tokenName: "TEST", - tokenTicker: "TEST", - tokenType: "FNG", - numDecimals: 2, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseRegisterAndSetAllRoles(tx1OnNetwork); - - assert.isTrue(tx1Outcome.tokenIdentifier.includes("TEST")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleLocalMint")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleLocalBurn")); - }); - - it("should register and set all roles (NFT)", async function () { - this.timeout(120000); - await frank.sync(provider); - - const tx1 = factory.registerAndSetAllRoles({ - issuer: frank.address, - tokenName: "TEST", - tokenTicker: "TEST", - tokenType: "NFT", - numDecimals: 0, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseRegisterAndSetAllRoles(tx1OnNetwork); - - assert.isTrue(tx1Outcome.tokenIdentifier.includes("TEST")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTCreate")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTBurn")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTUpdateAttributes")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTAddURI")); - }); - - it("should register and set all roles (SFT)", async function () { - this.timeout(120000); - await frank.sync(provider); - - const tx1 = factory.registerAndSetAllRoles({ - issuer: frank.address, - tokenName: "TEST", - tokenTicker: "TEST", - tokenType: "SFT", - numDecimals: 0, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseRegisterAndSetAllRoles(tx1OnNetwork); - - assert.isTrue(tx1Outcome.tokenIdentifier.includes("TEST")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTCreate")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTBurn")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTAddQuantity")); - }); - - it("should register and set all roles (META)", async function () { - this.timeout(120000); - await frank.sync(provider); - - const tx1 = factory.registerAndSetAllRoles({ - issuer: frank.address, - tokenName: "TEST", - tokenTicker: "TEST", - tokenType: "META", - numDecimals: 2, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseRegisterAndSetAllRoles(tx1OnNetwork); - - assert.isTrue(tx1Outcome.tokenIdentifier.includes("TEST")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTCreate")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTBurn")); - assert.isTrue(tx1Outcome.roles.includes("ESDTRoleNFTAddQuantity")); - }); - - it("should issue fungible, then toggle global burn", async function () { - this.timeout(180000); - await frank.sync(provider); - - // Issue - const tx1 = factory.issueFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - initialSupply: 100, - numDecimals: 0, - canFreeze: true, - canWipe: true, - canPause: true, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseIssueFungible(tx1OnNetwork); - const tokenIdentifier = tx1Outcome.tokenIdentifier; - assert.isTrue(tokenIdentifier.includes("FRANK")); - - // Unset global burn - const tx2 = factory.unsetBurnRoleGlobally({ - manager: frank.address, - tokenIdentifier: tx1Outcome.tokenIdentifier, - transactionNonce: frank.account.nonce, - }); - - const tx2OnNetwork = await processTransaction(frank, tx2, "tx2"); - const _tx2Outcome = parser.parseUnsetBurnRoleGlobally(tx2OnNetwork); - - // Set global burn - const tx3 = factory.setBurnRoleGlobally({ - manager: frank.address, - tokenIdentifier: tx1Outcome.tokenIdentifier, - transactionNonce: frank.account.nonce, - }); - - const tx3OnNetwork = await processTransaction(frank, tx3, "tx3"); - const _tx3Outcome = parser.parseSetBurnRoleGlobally(tx3OnNetwork); - }); - - it("should issue fungible, mint, burn", async function () { - this.timeout(120000); - await frank.sync(provider); - await grace.sync(provider); - - // Issue - const tx1 = factory.issueFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - initialSupply: 100, - numDecimals: 0, - canFreeze: true, - canWipe: true, - canPause: true, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseIssueFungible(tx1OnNetwork); - const tokenIdentifier = tx1Outcome.tokenIdentifier; - assert.isTrue(tokenIdentifier.includes("FRANK")); - - // Set roles (give Grace the ability to mint and burn) - const tx2 = factory.setSpecialRoleOnFungible({ - manager: frank.address, - user: grace.address, - tokenIdentifier: tx1Outcome.tokenIdentifier, - addRoleLocalMint: true, - addRoleLocalBurn: true, - transactionNonce: frank.account.nonce, - }); - - const tx2OnNetwork = await processTransaction(frank, tx2, "tx2"); - const tx2Outcome = parser.parseSetSpecialRole(tx2OnNetwork); - assert.include(tx2Outcome.roles, "ESDTRoleLocalMint"); - assert.include(tx2Outcome.roles, "ESDTRoleLocalBurn"); - - // Mint (Grace mints for herself) - const tx3 = factory.localMint({ - manager: grace.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - supplyToMint: 200, - transactionNonce: grace.account.nonce, - }); - - const tx3OnNetwork = await processTransaction(grace, tx3, "tx3"); - const tx3Outcome = parser.parseLocalMint(tx3OnNetwork); - assert.equal(tx3Outcome.mintedSupply, "200"); - - // Burn (Grace burns 50 of her tokens) - const tx4 = factory.localBurn({ - manager: grace.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - supplyToBurn: 50, - transactionNonce: grace.account.nonce, - }); - - const tx4OnNetwork = await processTransaction(grace, tx4, "tx4"); - const tx4Outcome = parser.parseLocalBurn(tx4OnNetwork); - assert.equal(tx4Outcome.burntSupply, "50"); - }); - - it("should issue fungible, pause, unpause", async function () { - this.timeout(240000); - await frank.sync(provider); - - // Issue - const tx1 = factory.issueFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - initialSupply: 100, - numDecimals: 0, - canFreeze: true, - canWipe: true, - canPause: true, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseIssueFungible(tx1OnNetwork); - const tokenIdentifier = tx1Outcome.tokenIdentifier; - assert.isTrue(tokenIdentifier.includes("FRANK")); - - // Pause - const tx2 = factory.pause({ - manager: frank.address, - tokenIdentifier: tokenIdentifier, - transactionNonce: frank.account.nonce, - }); - - const tx2OnNetwork = await processTransaction(frank, tx2, "tx2"); - const _tx2Outcome = parser.parsePause(tx2OnNetwork); - - // Unpause - const tx3 = factory.unpause({ - manager: frank.address, - tokenIdentifier: tokenIdentifier, - transactionNonce: frank.account.nonce, - }); - - const tx3OnNetwork = await processTransaction(frank, tx3, "tx3"); - const _tx3Outcome = parser.parseUnpause(tx3OnNetwork); - - // Send some tokens to Grace - const tx4 = transferTransactionsFactory.createESDTTransfer({ - tokenTransfer: TokenTransfer.fungibleFromBigInteger(tokenIdentifier, 10), - sender: frank.account.address, - receiver: grace.account.address, - chainID: network.ChainID, - nonce: frank.account.nonce, - }); - - const _tx4OnNetwork = await processTransaction(frank, tx4, "tx4"); - }); - - it("should issue fungible, freeze, unfreeze", async function () { - this.timeout(240000); - await frank.sync(provider); - - // Issue - const tx1 = factory.issueFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - initialSupply: 100, - numDecimals: 0, - canFreeze: true, - canWipe: true, - canPause: true, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseIssueFungible(tx1OnNetwork); - const tokenIdentifier = tx1Outcome.tokenIdentifier; - assert.isTrue(tokenIdentifier.includes("FRANK")); - - // Send some tokens to Grace - const tx2 = transferTransactionsFactory.createESDTTransfer({ - tokenTransfer: TokenTransfer.fungibleFromBigInteger(tokenIdentifier, 10), - sender: frank.account.address, - receiver: grace.account.address, - chainID: network.ChainID, - nonce: frank.account.nonce, - }); - - const _tx2OnNetwork = await processTransaction(frank, tx2, "tx2"); - - // Freeze - const tx3 = factory.freeze({ - manager: frank.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - transactionNonce: frank.account.nonce, - }); - - const tx3OnNetwork = await processTransaction(frank, tx3, "tx3"); - const tx3Outcome = parser.parseFreeze(tx3OnNetwork); - assert.equal(tx3Outcome.userAddress, grace.address.bech32()); - assert.equal(tx3Outcome.tokenIdentifier, tokenIdentifier); - assert.equal(tx3Outcome.nonce, "0"); - assert.equal(tx3Outcome.balance, "10"); - - // Unfreeze - const tx4 = factory.unfreeze({ - manager: frank.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - transactionNonce: frank.account.nonce, - }); - - const tx4OnNetwork = await processTransaction(frank, tx4, "tx4"); - const tx4Outcome = parser.parseUnfreeze(tx4OnNetwork); - assert.equal(tx4Outcome.userAddress, grace.address.bech32()); - assert.equal(tx4Outcome.tokenIdentifier, tokenIdentifier); - assert.equal(tx4Outcome.nonce, "0"); - assert.equal(tx4Outcome.balance, "10"); - }); - - it("should issue fungible, freeze, wipe", async function () { - this.timeout(240000); - await frank.sync(provider); - - // Issue - const tx1 = factory.issueFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - initialSupply: "100", - numDecimals: 0, - canFreeze: true, - canWipe: true, - canPause: true, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseIssueFungible(tx1OnNetwork); - const tokenIdentifier = tx1Outcome.tokenIdentifier; - assert.isTrue(tokenIdentifier.includes("FRANK")); - - // Send some tokens to Grace - const tx2 = transferTransactionsFactory.createESDTTransfer({ - tokenTransfer: TokenTransfer.fungibleFromBigInteger(tokenIdentifier, 10), - sender: frank.account.address, - receiver: grace.account.address, - chainID: network.ChainID, - nonce: frank.account.nonce, - }); - - const _tx2OnNetwork = await processTransaction(frank, tx2, "tx2"); - - // Freeze - const tx3 = factory.freeze({ - manager: frank.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - transactionNonce: frank.account.nonce, - }); - - const tx3OnNetwork = await processTransaction(frank, tx3, "tx3"); - const tx3Outcome = parser.parseFreeze(tx3OnNetwork); - assert.equal(tx3Outcome.userAddress, grace.address.bech32()); - assert.equal(tx3Outcome.tokenIdentifier, tokenIdentifier); - assert.equal(tx3Outcome.nonce, "0"); - assert.equal(tx3Outcome.balance, "10"); - - // Wipe - const tx4 = factory.wipe({ - manager: frank.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - transactionNonce: frank.account.nonce, - }); - - const tx4OnNetwork = await processTransaction(frank, tx4, "tx4"); - const tx4Outcome = parser.parseWipe(tx4OnNetwork); - assert.equal(tx4Outcome.userAddress, grace.address.bech32()); - assert.equal(tx4Outcome.tokenIdentifier, tokenIdentifier); - assert.equal(tx4Outcome.nonce, "0"); - assert.equal(tx4Outcome.balance, "10"); - }); - - it("should issue and create NFT, then update attributes", async function () { - this.timeout(180000); - await frank.sync(provider); - await grace.sync(provider); - - // Issue NFT - const tx1 = factory.issueNonFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - canFreeze: true, - canWipe: true, - canPause: true, - canTransferNFTCreateRole: true, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseIssueNonFungible(tx1OnNetwork); - const tokenIdentifier = tx1Outcome.tokenIdentifier; - assert.isTrue(tokenIdentifier.includes("FRANK")); - - // Set roles (give Grace the ability to create NFTs) - const tx2 = factory.setSpecialRoleOnNonFungible({ - manager: frank.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - addRoleNFTCreate: true, - addRoleNFTBurn: false, - addRoleNFTUpdateAttributes: true, - addRoleNFTAddURI: true, - addRoleESDTTransferRole: false, - transactionNonce: frank.account.nonce, - }); - - const tx2OnNetwork = await processTransaction(frank, tx2, "tx2"); - const tx2Outcome = parser.parseSetSpecialRole(tx2OnNetwork); - assert.include(tx2Outcome.roles, "ESDTRoleNFTCreate"); - assert.include(tx2Outcome.roles, "ESDTRoleNFTUpdateAttributes"); - - // Create NFTs, then update their attributes - for (let i = 1; i <= 2; i++) { - // Create - const txCreate = factory.nftCreate({ - creator: grace.address, - tokenIdentifier: tokenIdentifier, - initialQuantity: "1", - name: `test-${i}`, - royalties: 1000, - hash: "abba", - attributes: Buffer.from("test"), - uris: ["a", "b"], - transactionNonce: grace.account.nonce, - }); - - const txCreateOnNetwork = await processTransaction(grace, txCreate, "txCreate"); - const txCreateOutcome = parser.parseNFTCreate(txCreateOnNetwork); - - assert.equal(txCreateOutcome.tokenIdentifier, tokenIdentifier); - assert.equal(txCreateOutcome.nonce, i.toString()); - assert.equal(txCreateOutcome.initialQuantity, "1"); - - // Update attributes - const txUpdate = factory.updateAttributes({ - manager: grace.address, - tokenIdentifier: txCreateOutcome.tokenIdentifier, - tokenNonce: txCreateOutcome.nonce, - attributes: Buffer.from("updated"), - transactionNonce: grace.account.nonce, - }); - - const txUpdateOnNetwork = await processTransaction(grace, txUpdate, "txUpdate"); - const txUpdateOutcome = parser.parseUpdateAttributes(txUpdateOnNetwork); - - assert.equal(txUpdateOutcome.tokenIdentifier, tokenIdentifier); - assert.equal(txUpdateOutcome.nonce, i.toString()); - assert.deepEqual(txUpdateOutcome.attributes, Buffer.from("updated")); - } - }); - - it("should issue and create SFT, add quantity, burn quantity", async function () { - this.timeout(200000); - await frank.sync(provider); - await grace.sync(provider); - - // Issue SFT - const tx1 = factory.issueSemiFungible({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - canFreeze: true, - canWipe: true, - canPause: true, - canTransferNFTCreateRole: true, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseIssueSemiFungible(tx1OnNetwork); - const tokenIdentifier = tx1Outcome.tokenIdentifier; - assert.isTrue(tokenIdentifier.includes("FRANK")); - - // Set roles (give Grace the ability to create SFTs) - const tx2 = factory.setSpecialRoleOnSemiFungible({ - manager: frank.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - addRoleNFTCreate: true, - addRoleNFTBurn: false, - addRoleNFTAddQuantity: true, - addRoleESDTTransferRole: false, - transactionNonce: frank.account.nonce, - }); - - const tx2OnNetwork = await processTransaction(frank, tx2, "tx2"); - const tx2Outcome = parser.parseSetSpecialRole(tx2OnNetwork); - assert.include(tx2Outcome.roles, "ESDTRoleNFTCreate"); - assert.include(tx2Outcome.roles, "ESDTRoleNFTAddQuantity"); - - for (let i = 1; i <= 2; i++) { - // Create SFT - const txCreate = factory.nftCreate({ - creator: grace.address, - tokenIdentifier: tokenIdentifier, - initialQuantity: i * 10, - name: `test-${i}`, - royalties: 1000, - hash: "abba", - attributes: Buffer.from("test"), - uris: ["a", "b"], - transactionNonce: grace.account.nonce, - }); - - const txCreateOnNetwork = await processTransaction(grace, txCreate, "txCreate"); - const txCreateOutcome = parser.parseNFTCreate(txCreateOnNetwork); - - assert.equal(txCreateOutcome.tokenIdentifier, tokenIdentifier); - assert.equal(txCreateOutcome.nonce, i.toString()); - assert.equal(txCreateOutcome.initialQuantity, (i * 10).toString()); - - // Add quantity - const txAddQuantity = factory.addQuantity({ - manager: grace.address, - tokenIdentifier: txCreateOutcome.tokenIdentifier, - tokenNonce: txCreateOutcome.nonce, - quantityToAdd: "3", - transactionNonce: grace.account.nonce, - }); - - const txAddQuantityOnNetwork = await processTransaction(grace, txAddQuantity, "txAddQuantity"); - const txAddQuantityOutcome = parser.parseAddQuantity(txAddQuantityOnNetwork); - - assert.equal(txAddQuantityOutcome.tokenIdentifier, tokenIdentifier); - assert.equal(txAddQuantityOutcome.nonce, i.toString()); - assert.equal(txAddQuantityOutcome.addedQuantity, "3"); - - // Burn quantity - const txBurnQuantity = factory.burnQuantity({ - manager: grace.address, - tokenIdentifier: txCreateOutcome.tokenIdentifier, - tokenNonce: txCreateOutcome.nonce, - quantityToBurn: "2", - transactionNonce: grace.account.nonce, - }); - - const txBurnQuantityOnNetwork = await processTransaction(grace, txBurnQuantity, "txBurnQuantity"); - const txBurnQuantityOutcome = parser.parseBurnQuantity(txBurnQuantityOnNetwork); - - assert.equal(txBurnQuantityOutcome.tokenIdentifier, tokenIdentifier); - assert.equal(txBurnQuantityOutcome.nonce, i.toString()); - assert.equal(txBurnQuantityOutcome.burntQuantity, "2"); - } - }); - - it("should register and create Meta ESDT", async function () { - this.timeout(180000); - await frank.sync(provider); - await grace.sync(provider); - - // Register Meta ESDT - const tx1 = factory.registerMetaESDT({ - issuer: frank.address, - tokenName: "FRANK", - tokenTicker: "FRANK", - numDecimals: 10, - canFreeze: true, - canWipe: true, - canPause: true, - canTransferNFTCreateRole: true, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - transactionNonce: frank.account.nonce, - }); - - const tx1OnNetwork = await processTransaction(frank, tx1, "tx1"); - const tx1Outcome = parser.parseRegisterMetaESDT(tx1OnNetwork); - const tokenIdentifier = tx1Outcome.tokenIdentifier; - assert.isTrue(tokenIdentifier.includes("FRANK")); - - // Set roles (give Grace the ability to create Meta ESDTs) - const tx2 = factory.setSpecialRoleOnMetaESDT({ - manager: frank.address, - user: grace.address, - tokenIdentifier: tokenIdentifier, - addRoleNFTCreate: true, - addRoleNFTBurn: false, - addRoleNFTAddQuantity: true, - addRoleESDTTransferRole: false, - transactionNonce: frank.account.nonce, - }); - - const tx2OnNetwork = await processTransaction(frank, tx2, "tx2"); - const tx2Outcome = parser.parseSetSpecialRole(tx2OnNetwork); - assert.include(tx2Outcome.roles, "ESDTRoleNFTCreate"); - assert.include(tx2Outcome.roles, "ESDTRoleNFTAddQuantity"); - - // Create tokens - for (let i = 1; i <= 3; i++) { - const tx = factory.nftCreate({ - creator: grace.address, - tokenIdentifier: tokenIdentifier, - initialQuantity: i * 10, - name: `test-${i}`, - royalties: 1000, - hash: "abba", - attributes: Buffer.from("test"), - uris: ["a", "b"], - transactionNonce: grace.account.nonce, - }); - - const txOnNetwork = await processTransaction(grace, tx, "tx"); - const txOutcome = parser.parseNFTCreate(txOnNetwork); - - assert.equal(txOutcome.tokenIdentifier, tokenIdentifier); - assert.equal(txOutcome.nonce, i.toString()); - assert.equal(txOutcome.initialQuantity, (i * 10).toString()); - } - }); - - async function processTransaction( - wallet: TestWallet, - transaction: Transaction, - tag: string, - ): Promise { - wallet.account.incrementNonce(); - transaction.applySignature(await wallet.signer.sign(transaction.serializeForSigning())); - await provider.sendTransaction(transaction); - console.log(`Sent transaction [${tag}]: ${transaction.getHash().hex()}`); - - const transactionOnNetwork = await watcher.awaitCompleted(transaction.getHash().hex()); - return transactionOnNetwork; - } -}); diff --git a/src/tokenOperations/tokenOperationsFactory.ts b/src/tokenOperations/tokenOperationsFactory.ts deleted file mode 100644 index a4a4ffc52..000000000 --- a/src/tokenOperations/tokenOperationsFactory.ts +++ /dev/null @@ -1,693 +0,0 @@ -import BigNumber from "bignumber.js"; -import { ARGUMENTS_SEPARATOR, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "../constants"; -import { IAddress, IChainID, IGasLimit, IGasPrice, INonce, ITransactionValue } from "../interface"; -import { Logger } from "../logger"; -import { TransactionOptions, TransactionVersion } from "../networkParams"; -import { Transaction } from "../transaction"; -import { TransactionPayload } from "../transactionPayload"; -import { addressToHex, bigIntToHex, bufferToHex, utf8ToHex } from "./codec"; - -interface IConfig { - chainID: IChainID; - minGasPrice: IGasPrice; - minGasLimit: IGasLimit; - gasLimitPerByte: IGasLimit; - gasLimitIssue: IGasLimit; - gasLimitToggleBurnRoleGlobally: IGasLimit; - gasLimitESDTLocalMint: IGasLimit; - gasLimitESDTLocalBurn: IGasLimit; - gasLimitSetSpecialRole: IGasLimit; - gasLimitPausing: IGasLimit; - gasLimitFreezing: IGasLimit; - gasLimitWiping: IGasLimit; - gasLimitESDTNFTCreate: IGasLimit; - gasLimitESDTNFTUpdateAttributes: IGasLimit; - gasLimitESDTNFTAddQuantity: IGasLimit; - gasLimitESDTNFTBurn: IGasLimit; - gasLimitStorePerByte: IGasLimit; - issueCost: BigNumber.Value; - esdtContractAddress: IAddress; -} - -interface IBaseArgs { - transactionNonce?: INonce; - value?: ITransactionValue; - gasPrice?: IGasPrice; - gasLimit?: IGasLimit; -} - -interface IIssueFungibleArgs extends IBaseArgs { - issuer: IAddress; - tokenName: string; - tokenTicker: string; - initialSupply: BigNumber.Value; - numDecimals: number; - canFreeze: boolean; - canWipe: boolean; - canPause: boolean; - canChangeOwner: boolean; - canUpgrade: boolean; - canAddSpecialRoles: boolean; -} - -interface IIssueSemiFungibleArgs extends IBaseArgs { - issuer: IAddress; - tokenName: string; - tokenTicker: string; - canFreeze: boolean; - canWipe: boolean; - canPause: boolean; - canTransferNFTCreateRole: boolean; - canChangeOwner: boolean; - canUpgrade: boolean; - canAddSpecialRoles: boolean; -} - -interface IIssueNonFungibleArgs extends IIssueSemiFungibleArgs {} - -interface IRegisterMetaESDT extends IIssueSemiFungibleArgs { - numDecimals: number; -} - -interface IRegisterAndSetAllRoles extends IBaseArgs { - issuer: IAddress; - tokenName: string; - tokenTicker: string; - tokenType: RegisterAndSetAllRolesTokenType; - numDecimals: number; -} - -type RegisterAndSetAllRolesTokenType = "NFT" | "SFT" | "META" | "FNG"; - -interface IToggleBurnRoleGloballyArgs extends IBaseArgs { - manager: IAddress; - tokenIdentifier: string; -} - -interface IFungibleSetSpecialRoleArgs extends IBaseArgs { - manager: IAddress; - user: IAddress; - tokenIdentifier: string; - addRoleLocalMint: boolean; - addRoleLocalBurn: boolean; -} - -interface ISemiFungibleSetSpecialRoleArgs extends IBaseArgs { - manager: IAddress; - user: IAddress; - tokenIdentifier: string; - addRoleNFTCreate: boolean; - addRoleNFTBurn: boolean; - addRoleNFTAddQuantity: boolean; - addRoleESDTTransferRole: boolean; -} - -interface INonFungibleSetSpecialRoleArgs extends IBaseArgs { - manager: IAddress; - user: IAddress; - tokenIdentifier: string; - addRoleNFTCreate: boolean; - addRoleNFTBurn: boolean; - addRoleNFTUpdateAttributes: boolean; - addRoleNFTAddURI: boolean; - addRoleESDTTransferRole: boolean; -} - -interface INFTCreateArgs extends IBaseArgs { - creator: IAddress; - tokenIdentifier: string; - initialQuantity: BigNumber.Value; - name: string; - royalties: number; - hash: string; - attributes: Buffer; - uris: string[]; -} - -interface IPausingArgs extends IBaseArgs { - manager: IAddress; - tokenIdentifier: string; -} - -interface IFreezingArgs extends IBaseArgs { - manager: IAddress; - user: IAddress; - tokenIdentifier: string; -} - -interface IWipingArgs extends IBaseArgs { - manager: IAddress; - user: IAddress; - tokenIdentifier: string; -} - -interface ILocalMintArgs extends IBaseArgs { - manager: IAddress; - user: IAddress; - tokenIdentifier: string; - supplyToMint: BigNumber.Value; -} - -interface ILocalBurnArgs extends IBaseArgs { - manager: IAddress; - user: IAddress; - tokenIdentifier: string; - supplyToBurn: BigNumber.Value; -} - -interface IUpdateAttributesArgs extends IBaseArgs { - manager: IAddress; - tokenIdentifier: string; - tokenNonce: BigNumber.Value; - attributes: Buffer; -} - -interface IAddQuantityArgs extends IBaseArgs { - manager: IAddress; - tokenIdentifier: string; - tokenNonce: BigNumber.Value; - quantityToAdd: BigNumber.Value; -} - -interface IBurnQuantityArgs extends IBaseArgs { - manager: IAddress; - tokenIdentifier: string; - tokenNonce: BigNumber.Value; - quantityToBurn: BigNumber.Value; -} - -/** - * @deprecated Use {@link TokenManagementTransactionsFactory} instead. - */ -export class TokenOperationsFactory { - private readonly config: IConfig; - private readonly trueAsHex; - private readonly falseAsHex; - - constructor(config: IConfig) { - this.config = config; - this.trueAsHex = utf8ToHex("true"); - this.falseAsHex = utf8ToHex("false"); - } - - issueFungible(args: IIssueFungibleArgs): Transaction { - this.notifyAboutUnsettingBurnRoleGlobally(); - - const parts = [ - "issue", - utf8ToHex(args.tokenName), - utf8ToHex(args.tokenTicker), - bigIntToHex(args.initialSupply), - bigIntToHex(args.numDecimals), - utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex, - ]; - - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts, - }); - } - - private notifyAboutUnsettingBurnRoleGlobally() { - Logger.info(` -========== -IMPORTANT! -========== -You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); - } - - issueSemiFungible(args: IIssueSemiFungibleArgs): Transaction { - this.notifyAboutUnsettingBurnRoleGlobally(); - - const parts = [ - "issueSemiFungible", - utf8ToHex(args.tokenName), - utf8ToHex(args.tokenTicker), - utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex, - ]; - - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts, - }); - } - - issueNonFungible(args: IIssueNonFungibleArgs): Transaction { - this.notifyAboutUnsettingBurnRoleGlobally(); - - const parts = [ - "issueNonFungible", - utf8ToHex(args.tokenName), - utf8ToHex(args.tokenTicker), - utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex, - ]; - - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts, - }); - } - - registerMetaESDT(args: IRegisterMetaESDT): Transaction { - this.notifyAboutUnsettingBurnRoleGlobally(); - - const parts = [ - "registerMetaESDT", - utf8ToHex(args.tokenName), - utf8ToHex(args.tokenTicker), - bigIntToHex(args.numDecimals), - utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex, - ]; - - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts, - }); - } - - registerAndSetAllRoles(args: IRegisterAndSetAllRoles): Transaction { - this.notifyAboutUnsettingBurnRoleGlobally(); - - const parts = [ - "registerAndSetAllRoles", - utf8ToHex(args.tokenName), - utf8ToHex(args.tokenTicker), - utf8ToHex(args.tokenType), - bigIntToHex(args.numDecimals), - ]; - - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts, - }); - } - - setBurnRoleGlobally(args: IToggleBurnRoleGloballyArgs): Transaction { - const parts = ["setBurnRoleGlobally", utf8ToHex(args.tokenIdentifier)]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, - dataParts: parts, - }); - } - - unsetBurnRoleGlobally(args: IToggleBurnRoleGloballyArgs): Transaction { - const parts = ["unsetBurnRoleGlobally", utf8ToHex(args.tokenIdentifier)]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, - dataParts: parts, - }); - } - - setSpecialRoleOnFungible(args: IFungibleSetSpecialRoleArgs): Transaction { - const parts = [ - "setSpecialRole", - utf8ToHex(args.tokenIdentifier), - addressToHex(args.user), - ...(args.addRoleLocalMint ? [utf8ToHex("ESDTRoleLocalMint")] : []), - ...(args.addRoleLocalBurn ? [utf8ToHex("ESDTRoleLocalBurn")] : []), - ]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts, - }); - } - - setSpecialRoleOnSemiFungible(args: ISemiFungibleSetSpecialRoleArgs): Transaction { - const parts = [ - "setSpecialRole", - utf8ToHex(args.tokenIdentifier), - addressToHex(args.user), - ...(args.addRoleNFTCreate ? [utf8ToHex("ESDTRoleNFTCreate")] : []), - ...(args.addRoleNFTBurn ? [utf8ToHex("ESDTRoleNFTBurn")] : []), - ...(args.addRoleNFTAddQuantity ? [utf8ToHex("ESDTRoleNFTAddQuantity")] : []), - ...(args.addRoleESDTTransferRole ? [utf8ToHex("ESDTTransferRole")] : []), - ]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts, - }); - } - - setSpecialRoleOnMetaESDT(args: ISemiFungibleSetSpecialRoleArgs): Transaction { - return this.setSpecialRoleOnSemiFungible(args); - } - - setSpecialRoleOnNonFungible(args: INonFungibleSetSpecialRoleArgs): Transaction { - const parts = [ - "setSpecialRole", - utf8ToHex(args.tokenIdentifier), - addressToHex(args.user), - ...(args.addRoleNFTCreate ? [utf8ToHex("ESDTRoleNFTCreate")] : []), - ...(args.addRoleNFTBurn ? [utf8ToHex("ESDTRoleNFTBurn")] : []), - ...(args.addRoleNFTUpdateAttributes ? [utf8ToHex("ESDTRoleNFTUpdateAttributes")] : []), - ...(args.addRoleNFTAddURI ? [utf8ToHex("ESDTRoleNFTAddURI")] : []), - ...(args.addRoleESDTTransferRole ? [utf8ToHex("ESDTTransferRole")] : []), - ]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts, - }); - } - - nftCreate(args: INFTCreateArgs): Transaction { - const parts = [ - "ESDTNFTCreate", - utf8ToHex(args.tokenIdentifier), - bigIntToHex(args.initialQuantity), - utf8ToHex(args.name), - bigIntToHex(args.royalties), - utf8ToHex(args.hash), - bufferToHex(args.attributes), - ...args.uris.map(utf8ToHex), - ]; - - // Note that the following is an approximation (a reasonable one): - const nftData = args.name + args.hash + args.attributes + args.uris.join(""); - const storageGasLimit = nftData.length * this.config.gasLimitStorePerByte.valueOf(); - - return this.createTransaction({ - sender: args.creator, - receiver: args.creator, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTCreate.valueOf() + storageGasLimit.valueOf(), - dataParts: parts, - }); - } - - pause(args: IPausingArgs): Transaction { - const parts = ["pause", utf8ToHex(args.tokenIdentifier)]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitPausing, - dataParts: parts, - }); - } - - unpause(args: IPausingArgs): Transaction { - const parts = ["unPause", utf8ToHex(args.tokenIdentifier)]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitPausing, - dataParts: parts, - }); - } - - freeze(args: IFreezingArgs): Transaction { - const parts = ["freeze", utf8ToHex(args.tokenIdentifier), addressToHex(args.user)]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitFreezing, - dataParts: parts, - }); - } - - unfreeze(args: IFreezingArgs): Transaction { - const parts = ["unFreeze", utf8ToHex(args.tokenIdentifier), addressToHex(args.user)]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitFreezing, - dataParts: parts, - }); - } - - wipe(args: IWipingArgs): Transaction { - const parts = ["wipe", utf8ToHex(args.tokenIdentifier), addressToHex(args.user)]; - - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitWiping, - dataParts: parts, - }); - } - - localMint(args: ILocalMintArgs): Transaction { - const parts = ["ESDTLocalMint", utf8ToHex(args.tokenIdentifier), bigIntToHex(args.supplyToMint)]; - - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTLocalMint, - dataParts: parts, - }); - } - - localBurn(args: ILocalBurnArgs): Transaction { - const parts = ["ESDTLocalBurn", utf8ToHex(args.tokenIdentifier), bigIntToHex(args.supplyToBurn)]; - - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTLocalBurn, - dataParts: parts, - }); - } - - updateAttributes(args: IUpdateAttributesArgs): Transaction { - const parts = [ - "ESDTNFTUpdateAttributes", - utf8ToHex(args.tokenIdentifier), - bigIntToHex(args.tokenNonce), - bufferToHex(args.attributes), - ]; - - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTUpdateAttributes, - dataParts: parts, - }); - } - - addQuantity(args: IAddQuantityArgs): Transaction { - const parts = [ - "ESDTNFTAddQuantity", - utf8ToHex(args.tokenIdentifier), - bigIntToHex(args.tokenNonce), - bigIntToHex(args.quantityToAdd), - ]; - - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTAddQuantity, - dataParts: parts, - }); - } - - burnQuantity(args: IBurnQuantityArgs): Transaction { - const parts = [ - "ESDTNFTBurn", - utf8ToHex(args.tokenIdentifier), - bigIntToHex(args.tokenNonce), - bigIntToHex(args.quantityToBurn), - ]; - - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTBurn, - dataParts: parts, - }); - } - - private createTransaction({ - sender, - receiver, - nonce, - value, - gasPrice, - gasLimitHint, - executionGasLimit, - dataParts, - }: { - sender: IAddress; - receiver: IAddress; - nonce?: INonce; - value?: ITransactionValue; - gasPrice?: IGasPrice; - gasLimitHint?: IGasLimit; - executionGasLimit: IGasLimit; - dataParts: string[]; - }): Transaction { - const payload = this.buildTransactionPayload(dataParts); - const gasLimit = gasLimitHint || this.computeGasLimit(payload, executionGasLimit); - const version = new TransactionVersion(TRANSACTION_VERSION_DEFAULT); - const options = new TransactionOptions(TRANSACTION_OPTIONS_DEFAULT); - - return new Transaction({ - chainID: this.config.chainID, - sender: sender, - receiver: receiver, - gasLimit: gasLimit, - gasPrice: gasPrice, - nonce: nonce || 0, - value: value || 0, - data: payload, - version: version, - options: options, - }); - } - - private buildTransactionPayload(parts: string[]): TransactionPayload { - const data = parts.join(ARGUMENTS_SEPARATOR); - return new TransactionPayload(data); - } - - private computeGasLimit(payload: TransactionPayload, executionGas: IGasLimit): IGasLimit { - const dataMovementGas = - this.config.minGasLimit.valueOf() + this.config.gasLimitPerByte.valueOf() * payload.length(); - return dataMovementGas + executionGas.valueOf(); - } -} diff --git a/src/tokenOperations/tokenOperationsFactoryConfig.ts b/src/tokenOperations/tokenOperationsFactoryConfig.ts deleted file mode 100644 index 5a3466859..000000000 --- a/src/tokenOperations/tokenOperationsFactoryConfig.ts +++ /dev/null @@ -1,34 +0,0 @@ -import BigNumber from "bignumber.js"; -import { Address } from "../address"; -import { IAddress, IChainID, IGasLimit, IGasPrice } from "../interface"; - -/** - * @deprecated Use {@link TransactionsFactoryConfig} instead. - */ -export class TokenOperationsFactoryConfig { - chainID: IChainID; - minGasPrice: IGasPrice = 1000000000; - minGasLimit = 50000; - gasLimitPerByte = 1500; - gasLimitIssue: IGasLimit = 60000000; - gasLimitToggleBurnRoleGlobally: IGasLimit = 60000000; - gasLimitESDTLocalMint: IGasLimit = 300000; - gasLimitESDTLocalBurn: IGasLimit = 300000; - gasLimitSetSpecialRole: IGasLimit = 60000000; - gasLimitPausing: IGasLimit = 60000000; - gasLimitFreezing: IGasLimit = 60000000; - gasLimitWiping: IGasLimit = 60000000; - gasLimitESDTNFTCreate: IGasLimit = 3000000; - gasLimitESDTNFTUpdateAttributes: IGasLimit = 1000000; - gasLimitESDTNFTAddQuantity: IGasLimit = 1000000; - gasLimitESDTNFTBurn: IGasLimit = 1000000; - gasLimitStorePerByte: IGasLimit = 50000; - issueCost: BigNumber.Value = "50000000000000000"; - esdtContractAddress: IAddress = Address.fromBech32( - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", - ); - - constructor(chainID: IChainID) { - this.chainID = chainID; - } -} diff --git a/src/tokenOperations/tokenOperationsOutcomeParser.spec.ts b/src/tokenOperations/tokenOperationsOutcomeParser.spec.ts deleted file mode 100644 index ec3c5077f..000000000 --- a/src/tokenOperations/tokenOperationsOutcomeParser.spec.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { assert } from "chai"; -import { loadTestWallets, TestWallet } from "../testutils"; -import { bigIntToBuffer } from "./codec"; -import { TokenOperationsOutcomeParser } from "./tokenOperationsOutcomeParser"; - -describe("test parsers", () => { - const parser = new TokenOperationsOutcomeParser(); - let frank: TestWallet, grace: TestWallet; - - before(async function () { - ({ frank, grace } = await loadTestWallets()); - }); - - it("should parse outcome of issueFungible", () => { - const outcome = parser.parseIssueFungible({ - hash: "hash", - contractResults: { items: [] }, - logs: { - events: [ - { - address: frank.address, - identifier: "issue", - topics: [createTopic(Buffer.from("FOOBAR"))], - data: "", - }, - ], - }, - }); - - assert.equal(outcome.tokenIdentifier, "FOOBAR"); - }); - - it("should parse outcome of setSpecialRole", () => { - const outcome = parser.parseSetSpecialRole({ - hash: "hash", - contractResults: { items: [] }, - logs: { - events: [ - { - address: grace.address, - identifier: "ESDTSetRole", - topics: [ - createTopic(Buffer.from("FOOBAR")), - createTopic(Buffer.from("")), - createTopic(Buffer.from("")), - createTopic(Buffer.from("ESDTRoleLocalMint")), - createTopic(Buffer.from("ESDTRoleLocalBurn")), - ], - data: "", - }, - ], - }, - }); - - assert.equal(outcome.tokenIdentifier, "FOOBAR"); - assert.deepEqual(outcome.roles, ["ESDTRoleLocalMint", "ESDTRoleLocalBurn"]); - assert.equal(outcome.userAddress, grace.address.toString()); - }); - - it("should parse outcome of localMint", () => { - const outcome = parser.parseLocalMint({ - hash: "hash", - contractResults: { items: [] }, - logs: { - events: [ - { - address: grace.address, - identifier: "ESDTLocalMint", - topics: [ - createTopic(Buffer.from("FOOBAR")), - createTopic(Buffer.from("")), - createTopic(bigIntToBuffer("200")), - ], - data: "", - }, - ], - }, - }); - - assert.equal(outcome.tokenIdentifier, "FOOBAR"); - assert.equal(outcome.nonce, "0"); - assert.equal(outcome.mintedSupply, "200"); - assert.equal(outcome.userAddress, grace.address.toString()); - }); - - it("should parse outcome of nftCreate", () => { - const outcome = parser.parseNFTCreate({ - hash: "hash", - contractResults: { items: [] }, - logs: { - events: [ - { - address: grace.address, - identifier: "ESDTNFTCreate", - topics: [ - createTopic(Buffer.from("FOOBAR")), - createTopic(bigIntToBuffer("42")), - createTopic(bigIntToBuffer("1")), - ], - data: "", - }, - ], - }, - }); - - assert.equal(outcome.tokenIdentifier, "FOOBAR"); - assert.equal(outcome.nonce, "42"); - assert.equal(outcome.initialQuantity, "1"); - }); - - function createTopic(value: Buffer): any { - return { - valueOf: () => value, - }; - } -}); diff --git a/src/tokenOperations/tokenOperationsOutcomeParser.ts b/src/tokenOperations/tokenOperationsOutcomeParser.ts deleted file mode 100644 index 8fc489f3c..000000000 --- a/src/tokenOperations/tokenOperationsOutcomeParser.ts +++ /dev/null @@ -1,335 +0,0 @@ -import { Address } from "../address"; -import { ErrCannotParseTransactionOutcome } from "../errors"; -import { IAddress } from "../interface"; -import { bufferToBigInt } from "./codec"; - -interface ITransactionOnNetwork { - hash: string; - contractResults: IContractResults; - logs: ITransactionLogs; -} - -interface IContractResults { - items: IContractResultItem[]; -} - -interface IContractResultItem { - logs: ITransactionLogs; -} - -interface ITransactionLogs { - events: ITransactionEvent[]; -} - -interface ITransactionEvent { - readonly address: IAddress; - readonly identifier: string; - readonly topics: ITransactionEventTopic[]; - readonly data: string; -} - -interface ITransactionEventTopic { - valueOf(): any; -} - -export interface IESDTIssueOutcome { - tokenIdentifier: string; -} - -export interface IRegisterAndSetAllRolesOutcome { - tokenIdentifier: string; - roles: string[]; -} - -export interface IToggleBurnRoleGloballyOutcome {} - -export interface ISetSpecialRoleOutcome { - userAddress: string; - tokenIdentifier: string; - roles: string[]; -} - -export interface INFTCreateOutcome { - tokenIdentifier: string; - nonce: string; - initialQuantity: string; -} - -export interface IMintOutcome { - userAddress: string; - tokenIdentifier: string; - nonce: string; - mintedSupply: string; -} - -export interface IBurnOutcome { - userAddress: string; - tokenIdentifier: string; - nonce: string; - burntSupply: string; -} - -export interface IPausingOutcome {} - -export interface IFreezingOutcome { - userAddress: string; - tokenIdentifier: string; - nonce: string; - balance: string; -} - -export interface IWipingOutcome { - userAddress: string; - tokenIdentifier: string; - nonce: string; - balance: string; -} - -export interface IUpdateAttributesOutcome { - tokenIdentifier: string; - nonce: string; - attributes: Buffer; -} - -export interface IAddQuantityOutcome { - tokenIdentifier: string; - nonce: string; - addedQuantity: string; -} - -export interface IBurnQuantityOutcome { - tokenIdentifier: string; - nonce: string; - burntQuantity: string; -} - -/** - * @deprecated Use {@link TokenManagementTransactionsOutcomeParser} - */ -export class TokenOperationsOutcomeParser { - parseIssueFungible(transaction: ITransactionOnNetwork): IESDTIssueOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "issue"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier: tokenIdentifier }; - } - - parseIssueNonFungible(transaction: ITransactionOnNetwork): IESDTIssueOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "issueNonFungible"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier: tokenIdentifier }; - } - - parseIssueSemiFungible(transaction: ITransactionOnNetwork): IESDTIssueOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "issueSemiFungible"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier: tokenIdentifier }; - } - - parseRegisterMetaESDT(transaction: ITransactionOnNetwork): IESDTIssueOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "registerMetaESDT"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier: tokenIdentifier }; - } - - parseRegisterAndSetAllRoles(transaction: ITransactionOnNetwork): IRegisterAndSetAllRolesOutcome { - this.ensureNoError(transaction); - - const eventRegister = this.findSingleEventByIdentifier(transaction, "registerAndSetAllRoles"); - const tokenIdentifier = this.extractTokenIdentifier(eventRegister); - - const eventSetRole = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); - const roles = eventSetRole.topics.slice(3).map((topic) => topic.valueOf().toString()); - - return { tokenIdentifier, roles }; - } - - parseSetBurnRoleGlobally(transaction: ITransactionOnNetwork): IToggleBurnRoleGloballyOutcome { - this.ensureNoError(transaction); - return {}; - } - - parseUnsetBurnRoleGlobally(transaction: ITransactionOnNetwork): IToggleBurnRoleGloballyOutcome { - this.ensureNoError(transaction); - return {}; - } - - parseSetSpecialRole(transaction: ITransactionOnNetwork): ISetSpecialRoleOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const roles = event.topics.slice(3).map((topic) => topic.valueOf().toString()); - return { userAddress, tokenIdentifier, roles }; - } - - parseNFTCreate(transaction: ITransactionOnNetwork): INFTCreateOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTCreate"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const initialQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, initialQuantity }; - } - - parseLocalMint(transaction: ITransactionOnNetwork): IMintOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalMint"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const mintedSupply = this.extractAmount(event); - return { userAddress, tokenIdentifier, nonce, mintedSupply }; - } - - parseLocalBurn(transaction: ITransactionOnNetwork): IBurnOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalBurn"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntSupply = this.extractAmount(event); - return { userAddress, tokenIdentifier, nonce, burntSupply }; - } - - parsePause(transaction: ITransactionOnNetwork): IPausingOutcome { - this.ensureNoError(transaction); - const _ = this.findSingleEventByIdentifier(transaction, "ESDTPause"); - return {}; - } - - parseUnpause(transaction: ITransactionOnNetwork): IPausingOutcome { - this.ensureNoError(transaction); - const _ = this.findSingleEventByIdentifier(transaction, "ESDTUnPause"); - return {}; - } - - parseFreeze(transaction: ITransactionOnNetwork): IFreezingOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTFreeze"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - - parseUnfreeze(transaction: ITransactionOnNetwork): IFreezingOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTUnFreeze"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - - parseWipe(transaction: ITransactionOnNetwork): IWipingOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTWipe"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - - parseUpdateAttributes(transaction: ITransactionOnNetwork): IUpdateAttributesOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTUpdateAttributes"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const attributes = event.topics[3]?.valueOf(); - return { tokenIdentifier, nonce, attributes }; - } - - parseAddQuantity(transaction: ITransactionOnNetwork): IAddQuantityOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTAddQuantity"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const addedQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, addedQuantity }; - } - - parseBurnQuantity(transaction: ITransactionOnNetwork): IBurnQuantityOutcome { - this.ensureNoError(transaction); - - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTBurn"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, burntQuantity }; - } - - private ensureNoError(transaction: ITransactionOnNetwork) { - for (const event of transaction.logs.events) { - if (event.identifier == "signalError") { - const data = Buffer.from(event.data.substring(1), "hex").toString(); - const message = event.topics[1]?.valueOf().toString(); - - throw new ErrCannotParseTransactionOutcome( - transaction.hash, - `encountered signalError: ${message} (${data})`, - ); - } - } - } - - private findSingleEventByIdentifier(transaction: ITransactionOnNetwork, identifier: string): ITransactionEvent { - const events = this.gatherAllEvents(transaction).filter((event) => event.identifier == identifier); - - if (events.length == 0) { - throw new ErrCannotParseTransactionOutcome(transaction.hash, `cannot find event of type ${identifier}`); - } - if (events.length > 1) { - throw new ErrCannotParseTransactionOutcome(transaction.hash, `more than one event of type ${identifier}`); - } - - return events[0]; - } - - private gatherAllEvents(transaction: ITransactionOnNetwork): ITransactionEvent[] { - const allEvents = []; - - allEvents.push(...transaction.logs.events); - - for (const item of transaction.contractResults.items) { - allEvents.push(...item.logs.events); - } - - return allEvents; - } - - private extractTokenIdentifier(event: ITransactionEvent): string { - return event.topics[0]?.valueOf().toString(); - } - - private extractNonce(event: ITransactionEvent): string { - return bufferToBigInt(event.topics[1]?.valueOf()).toFixed(0); - } - - private extractAmount(event: ITransactionEvent): string { - return bufferToBigInt(event.topics[2]?.valueOf()).toFixed(0); - } - - private extractAddress(event: ITransactionEvent): string { - return Address.fromBuffer(event.topics[3]?.valueOf()).toString(); - } -} diff --git a/src/transactionsOutcomeParsers/resources.ts b/src/transactionsOutcomeParsers/resources.ts index 0e0da28f3..fad5ed713 100644 --- a/src/transactionsOutcomeParsers/resources.ts +++ b/src/transactionsOutcomeParsers/resources.ts @@ -64,6 +64,5 @@ export function gatherAllEvents(transactionOutcome: TransactionOnNetwork): Trans allEvents.push(...item.logs.events); } - console.log({ allEvents: JSON.stringify(allEvents) }); return allEvents; } From 4df53370e0e6afca0a39a1b94a11321fcb833341 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 20 Nov 2024 16:17:22 +0200 Subject: [PATCH 041/214] Fix test --- src/abi/resultsParser.spec.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/abi/resultsParser.spec.ts b/src/abi/resultsParser.spec.ts index 0a4141571..d1df26229 100644 --- a/src/abi/resultsParser.spec.ts +++ b/src/abi/resultsParser.spec.ts @@ -202,7 +202,6 @@ describe("test smart contract results parser", () => { let bundle = parser.parseUntypedOutcome(transaction); assert.deepEqual(bundle.returnCode, ReturnCode.Ok); - assert.equal(bundle.returnMessage, "foobar"); assert.deepEqual(bundle.values, [Buffer.from("03", "hex")]); }); From 8b16458ef9e7a000839fc9f93749ce6d4d8ffe2b Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 20 Nov 2024 16:20:38 +0200 Subject: [PATCH 042/214] Add logging --- src/entrypoints/entrypoints.spec.ts | 1 + src/transactionEvents.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 42b2241e6..af553405a 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -58,6 +58,7 @@ describe("TestEntrypoint", () => { }, ); + console.log({ transaction }); const txHash = await entrypoint.sendTransaction(transaction); const outcome = await controller.awaitCompletedDeploy(txHash); diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index 25cf07ee5..a471683e7 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -23,6 +23,7 @@ export class TransactionEvent { data: string; additionalData?: string[]; }): TransactionEvent { + console.log({ responsePart }); let result = new TransactionEvent(); result.address = new Address(responsePart.address); result.identifier = responsePart.identifier || ""; From 3c8a02efc796fd509e4fa6c94b26b4e9283b3b25 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 21 Nov 2024 10:37:26 +0200 Subject: [PATCH 043/214] More logging --- src/transactionEvents.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index a471683e7..11c8a249b 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -29,9 +29,10 @@ export class TransactionEvent { result.identifier = responsePart.identifier || ""; result.topics = (responsePart.topics || []).map((topic) => Buffer.from(topic)); + console.log(22222, { responsePart }, 333, responsePart.additionalData); result.dataPayload = Buffer.from(responsePart.data); result.additionalData = (responsePart.additionalData || []).map((data) => Buffer.from(data)); - result.data = result.dataPayload.toString(); + result.data = result.dataPayload?.toString(); return result; } From 74213b1629088de2462b26afeccefc0954c5f496 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 21 Nov 2024 10:45:43 +0200 Subject: [PATCH 044/214] More logging --- src/networkProviders/apiNetworkProvider.ts | 1 + src/transactionLogs.ts | 1 + src/transactions.ts | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 33e54af5e..1eaab7263 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -136,6 +136,7 @@ export class ApiNetworkProvider implements INetworkProvider { async getTransaction(txHash: string): Promise { const response = await this.doGetGeneric(`transactions/${txHash}`); + console.log({ response: JSON.stringify(response) }); const transaction = TransactionOnNetwork.fromApiHttpResponse(txHash, response); return transaction; } diff --git a/src/transactionLogs.ts b/src/transactionLogs.ts index 081770f69..0ea40774b 100644 --- a/src/transactionLogs.ts +++ b/src/transactionLogs.ts @@ -13,6 +13,7 @@ export class TransactionLogs { static fromHttpResponse(logs: any): TransactionLogs { let result = new TransactionLogs(); result.address = new Address(logs.address); + console.log({ events: JSON.stringify(logs.events) }); result.events = (logs.events || []).map((event: any) => TransactionEvent.fromHttpResponse(event)); return result; diff --git a/src/transactions.ts b/src/transactions.ts index da1cbe98d..40909614f 100644 --- a/src/transactions.ts +++ b/src/transactions.ts @@ -107,7 +107,7 @@ export class TransactionOnNetwork { result.blockNonce = response.blockNonce || 0; result.hyperblockNonce = response.hyperblockNonce || 0; result.hyperblockHash = response.hyperblockHash || ""; - + console.log({ logs: JSON.stringify(response.logs) }); result.logs = TransactionLogs.fromHttpResponse(response.logs || {}); return result; From 2b68d3a2ee0dac2f1c7942a19c88596461c97439 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 21 Nov 2024 11:30:08 +0200 Subject: [PATCH 045/214] Fix tests and remove console logs --- src/delegation/delegationTransactionsFactory.ts | 1 - src/delegation/delegationTransactionsOutcomeParser.ts | 2 +- src/entrypoints/entrypoints.spec.ts | 1 - src/networkProviders/apiNetworkProvider.ts | 1 - .../smartContractTransactionsOutcomeParser.spec.ts | 11 +++++++++-- .../smartContractTransactionsOutcomeParser.ts | 5 ++--- src/transactionEvents.ts | 5 +---- src/transactionLogs.ts | 1 - src/transactions.ts | 3 +-- 9 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/delegation/delegationTransactionsFactory.ts b/src/delegation/delegationTransactionsFactory.ts index 2c5f94374..8aa26e38f 100644 --- a/src/delegation/delegationTransactionsFactory.ts +++ b/src/delegation/delegationTransactionsFactory.ts @@ -108,7 +108,6 @@ export class DelegationTransactionsFactory { createTransactionForStakingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { let dataParts = ["stakeNodes"]; - console.log(options.publicKeys); for (const key of options.publicKeys) { dataParts = dataParts.concat(key.hex()); diff --git a/src/delegation/delegationTransactionsOutcomeParser.ts b/src/delegation/delegationTransactionsOutcomeParser.ts index b35dfa1af..9a8caecfa 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.ts @@ -33,7 +33,7 @@ export class DelegationTransactionsOutcomeParser { return ""; } const address = Buffer.from(event.topics[0]); - return Address.fromBuffer(address).bech32(); + return new Address(address).bech32(); } private decodeTopicAsString(topic: Uint8Array): string { diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index af553405a..42b2241e6 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -58,7 +58,6 @@ describe("TestEntrypoint", () => { }, ); - console.log({ transaction }); const txHash = await entrypoint.sendTransaction(transaction); const outcome = await controller.awaitCompletedDeploy(txHash); diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 1eaab7263..33e54af5e 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -136,7 +136,6 @@ export class ApiNetworkProvider implements INetworkProvider { async getTransaction(txHash: string): Promise { const response = await this.doGetGeneric(`transactions/${txHash}`); - console.log({ response: JSON.stringify(response) }); const transaction = TransactionOnNetwork.fromApiHttpResponse(txHash, response); return transaction; } diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index 1c596a33d..5b5b7d44b 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -22,7 +22,11 @@ describe("test smart contract transactions outcome parser", () => { events: [ new TransactionEvent({ identifier: "SCDeploy", - topics: [contract.getPublicKey(), deployer.getPublicKey(), codeHash], + topics: [ + new Uint8Array(Buffer.from(contract.getPublicKey().toString("base64"))), + new Uint8Array(Buffer.from(deployer.getPublicKey().toString("base64"))), + codeHash, + ], }), ], }), @@ -53,7 +57,10 @@ describe("test smart contract transactions outcome parser", () => { events: [ new TransactionEvent({ identifier: "signalError", - topics: [deployer.getPublicKey(), new Uint8Array(Buffer.from("wrong number of arguments"))], + topics: [ + new Uint8Array(Buffer.from(deployer.getPublicKey().toString("base64"))), + new Uint8Array(Buffer.from("wrong number of arguments")), + ], data: "@75736572206572726f72", }), ], diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 0ddcc0568..a4d503028 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -85,10 +85,9 @@ export class SmartContractTransactionsOutcomeParser { ownerAddress: string; codeHash: Uint8Array; } { - const topicForAddress = Buffer.from(event.topics[0]); - const topicForOwnerAddress = event.topics[1]; + const topicForAddress = Buffer.from(event.topics[0].toString(), "base64").toString("hex"); + const topicForOwnerAddress = Buffer.from(event.topics[1].toString(), "base64").toString("hex"); const topicForCodeHash = event.topics[2]; - const address = topicForAddress?.length ? new Address(topicForAddress).toBech32() : ""; const ownerAddress = topicForOwnerAddress?.length ? new Address(topicForOwnerAddress).toBech32() : ""; const codeHash = topicForCodeHash; diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index 11c8a249b..3231f3179 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -23,16 +23,13 @@ export class TransactionEvent { data: string; additionalData?: string[]; }): TransactionEvent { - console.log({ responsePart }); let result = new TransactionEvent(); result.address = new Address(responsePart.address); result.identifier = responsePart.identifier || ""; result.topics = (responsePart.topics || []).map((topic) => Buffer.from(topic)); - console.log(22222, { responsePart }, 333, responsePart.additionalData); - result.dataPayload = Buffer.from(responsePart.data); + result.dataPayload = Buffer.from(responsePart.data ?? ""); result.additionalData = (responsePart.additionalData || []).map((data) => Buffer.from(data)); - result.data = result.dataPayload?.toString(); return result; } diff --git a/src/transactionLogs.ts b/src/transactionLogs.ts index 0ea40774b..081770f69 100644 --- a/src/transactionLogs.ts +++ b/src/transactionLogs.ts @@ -13,7 +13,6 @@ export class TransactionLogs { static fromHttpResponse(logs: any): TransactionLogs { let result = new TransactionLogs(); result.address = new Address(logs.address); - console.log({ events: JSON.stringify(logs.events) }); result.events = (logs.events || []).map((event: any) => TransactionEvent.fromHttpResponse(event)); return result; diff --git a/src/transactions.ts b/src/transactions.ts index 40909614f..7c14308da 100644 --- a/src/transactions.ts +++ b/src/transactions.ts @@ -81,7 +81,7 @@ export class TransactionOnNetwork { static fromApiHttpResponse(txHash: string, response: any): TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); - result.smartContractResults = response.results; + result.smartContractResults = response.results ?? []; result.isCompleted = !result.status.isPending(); return result; } @@ -107,7 +107,6 @@ export class TransactionOnNetwork { result.blockNonce = response.blockNonce || 0; result.hyperblockNonce = response.hyperblockNonce || 0; result.hyperblockHash = response.hyperblockHash || ""; - console.log({ logs: JSON.stringify(response.logs) }); result.logs = TransactionLogs.fromHttpResponse(response.logs || {}); return result; From 5fb3f56cb0000a300411c02cf77781f3381b5844 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 21 Nov 2024 11:55:57 +0200 Subject: [PATCH 046/214] Fix smart contract test --- .../smartContractTransactionsOutcomeParser.spec.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index 5b5b7d44b..0902a3be9 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -1,7 +1,7 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Address } from "../address"; -import { loadAbiRegistry } from "../testutils"; +import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; @@ -57,11 +57,11 @@ describe("test smart contract transactions outcome parser", () => { events: [ new TransactionEvent({ identifier: "signalError", - topics: [ - new Uint8Array(Buffer.from(deployer.getPublicKey().toString("base64"))), - new Uint8Array(Buffer.from("wrong number of arguments")), - ], - data: "@75736572206572726f72", + topics: b64TopicsToBytes([ + deployer.getPublicKey().toString("base64"), + Buffer.from("wrong number of arguments").toString("base64"), + ]), + dataPayload: Buffer.from("@75736572206572726f72"), }), ], }), From 16ce836b2a594d52cf2da842c8643c0c7ada177a Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 21 Nov 2024 12:11:37 +0200 Subject: [PATCH 047/214] Fix tests --- src/testutils/networkProviders.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 7e5f49ea0..288a2ba78 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,9 +1,10 @@ import { Query } from "../abi"; import { IAddress } from "../interface"; import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionStatus } from "../interfaceOfNetwork"; -import { ApiNetworkProvider, ProxyNetworkProvider, TransactionOnNetwork } from "../networkProviders"; +import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { Transaction } from "../transaction"; +import { TransactionOnNetwork } from "../transactions"; export function createLocalnetProvider(): INetworkProvider { return new ProxyNetworkProvider("http://localhost:7950", { timeout: 5000 }); From 90e2959d08ee2d218062da2ed55c386ffc43649b Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 21 Nov 2024 12:14:22 +0200 Subject: [PATCH 048/214] decrease integration waiting time --- .github/workflows/test-localnet.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test-localnet.yml b/.github/workflows/test-localnet.yml index 61cdae4c0..d324b54d1 100644 --- a/.github/workflows/test-localnet.yml +++ b/.github/workflows/test-localnet.yml @@ -42,7 +42,7 @@ jobs: mkdir -p ~/localnet && cd ~/localnet mxpy localnet setup --configfile=${GITHUB_WORKSPACE}/localnet.toml nohup mxpy localnet start --configfile=${GITHUB_WORKSPACE}/localnet.toml > localnet.log 2>&1 & echo $! > localnet.pid - sleep 120 # Allow time for the testnet to fully start + sleep 10 # Allow time for the testnet to fully start # Step 6: Install Node.js and dependencies - name: Set up Node.js environment From afbccc81d6331d89fb985d0061a6520dc600c1db Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 21 Nov 2024 16:14:41 +0200 Subject: [PATCH 049/214] Fix tests --- src/abi/resultsParser.spec.ts | 18 +++++----- src/abi/resultsParser.ts | 34 +++++++++--------- .../providers.dev.net.spec.ts | 24 ++++++------- ...tContractTransactionsOutcomeParser.spec.ts | 4 +-- .../smartContractTransactionsOutcomeParser.ts | 35 +++++-------------- src/testutils/utils.ts | 4 +++ src/transactionEvents.ts | 9 ++--- src/transactions.ts | 2 +- 8 files changed, 54 insertions(+), 76 deletions(-) diff --git a/src/abi/resultsParser.spec.ts b/src/abi/resultsParser.spec.ts index d1df26229..fb5c9c114 100644 --- a/src/abi/resultsParser.spec.ts +++ b/src/abi/resultsParser.spec.ts @@ -213,7 +213,7 @@ describe("test smart contract results parser", () => { new TransactionEvent({ identifier: "signalError", topics: [Buffer.from("something happened")], - data: `@${Buffer.from("user error").toString("hex")}@07`, + data: Buffer.from("QDc1NzM2NTcyMjA2NTcyNzI2ZjcyQDA3", "base64"), }), ], }), @@ -238,7 +238,7 @@ describe("test smart contract results parser", () => { "base64", ), ], - data: Buffer.from("QDZmNmI=", "base64").toString(), + data: Buffer.from("QDZmNmI=", "base64"), }), ], }), @@ -260,7 +260,7 @@ describe("test smart contract results parser", () => { Buffer.from("cmzC1LRt1r10pMhNAnFb+FyudjGMq4G8CefCYdQUmmc=", "base64"), Buffer.from("AAAADFdFR0xELTAxZTQ5ZAAAAAAAAAAAAAAAAWQ=", "base64"), ], - dataPayload: Buffer.from("AAAAAAAAA9sAAAA=", "base64"), + data: Buffer.from("AAAAAAAAA9sAAAA=", "base64"), }); const bundle = parser.parseEvent(event, eventDefinition); @@ -306,7 +306,7 @@ describe("test smart contract results parser", () => { const eventDefinition = abiRegistry.getEvent("foobar"); - const event = { + const event = new TransactionEvent({ topics: b64TopicsToBytes([ Buffer.from("not used").toString("base64"), Buffer.from([42]).toString("base64"), @@ -316,8 +316,8 @@ describe("test smart contract results parser", () => { Buffer.from("test").toString("base64"), Buffer.from([44]).toString("base64"), ]), - dataPayload: Buffer.from([42]), - }; + data: Buffer.from([42]), + }); const bundle = parser.parseEvent(event, eventDefinition); assert.deepEqual(bundle.a, [new BigNumber(42), "test", new BigNumber(43), "test"]); @@ -353,15 +353,15 @@ describe("test smart contract results parser", () => { const eventDefinition = abiRegistry.getEvent("foobar"); - const event = { + const event = new TransactionEvent({ topics: b64TopicsToBytes([ Buffer.from("not used").toString("base64"), Buffer.from([42]).toString("base64"), ]), additionalData: [Buffer.from([43]), Buffer.from([44])], // Will be ignored. - dataPayload: Buffer.from([43]), - }; + data: new Uint8Array(Buffer.from([43])), + }); const bundle = parser.parseEvent(event, eventDefinition); assert.deepEqual(bundle.a, new BigNumber(42)); diff --git a/src/abi/resultsParser.ts b/src/abi/resultsParser.ts index 2304dc59c..4b7508672 100644 --- a/src/abi/resultsParser.ts +++ b/src/abi/resultsParser.ts @@ -6,6 +6,7 @@ import { Address } from "../address"; import { ErrCannotParseContractResults } from "../errors"; import { IContractQueryResponse } from "../interfaceOfNetwork"; import { Logger } from "../logger"; +import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; import { TransactionOnNetwork } from "../transactions"; import { SmartContractResult } from "../transactionsOutcomeParsers"; @@ -38,12 +39,6 @@ interface IEventInputDefinition { indexed: boolean; } -interface ITransactionEvent { - readonly topics: { valueOf(): Uint8Array }[]; - readonly dataPayload?: { valueOf(): Uint8Array }; - readonly additionalData?: { valueOf(): Uint8Array }[]; -} - interface IArgsSerializer { buffersToValues(buffers: Buffer[], parameters: IParameterDefinition[]): TypedValue[]; stringToBuffers(joinedString: string): Buffer[]; @@ -240,7 +235,7 @@ export class ResultsParser { return null; } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventSignalError.data); + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(Buffer.from(eventSignalError.data).toString()); let lastTopic = eventSignalError.getLastTopic(); let returnMessage = lastTopic?.toString() || returnCode.toString(); @@ -263,7 +258,7 @@ export class ResultsParser { return null; } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventTooMuchGas.data); + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventTooMuchGas.data.toString()); return { returnCode: returnCode, @@ -287,7 +282,9 @@ export class ResultsParser { return null; } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventWriteLogWhereTopicIsSender.data); + let { returnCode, returnDataParts } = this.sliceDataFieldInParts( + eventWriteLogWhereTopicIsSender.data.toString(), + ); let returnMessage = returnCode.toString(); return { @@ -322,7 +319,9 @@ export class ResultsParser { }); if (writeLogWithReturnData) { - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(writeLogWithReturnData.data); + let { returnCode, returnDataParts } = this.sliceDataFieldInParts( + writeLogWithReturnData.data.toString(), + ); let returnMessage = returnCode.toString(); return { @@ -341,7 +340,9 @@ export class ResultsParser { }); if (writeLogWithReturnData) { - const { returnCode, returnDataParts } = this.sliceDataFieldInParts(writeLogWithReturnData.data); + const { returnCode, returnDataParts } = this.sliceDataFieldInParts( + writeLogWithReturnData.data.toString(), + ); const returnMessage = returnCode.toString(); return { @@ -382,7 +383,7 @@ export class ResultsParser { /** * Legacy method, use "TransactionEventsParser.parseEvent()" instead. */ - parseEvent(transactionEvent: ITransactionEvent, eventDefinition: { inputs: IEventInputDefinition[] }): any { + parseEvent(transactionEvent: TransactionEvent, eventDefinition: { inputs: IEventInputDefinition[] }): any { // We skip the first topic, because, for log entries emitted by smart contracts, that's the same as the event identifier. See: // https://github.com/multiversx/mx-chain-vm-go/blob/v1.5.27/vmhost/contexts/output.go#L283 const topics = transactionEvent.topics.map((topic) => Buffer.from(topic.valueOf())).slice(1); @@ -391,9 +392,8 @@ export class ResultsParser { // After Sirius, the "additionalData" field includes the "data" field, as well (as the first element): // https://github.com/multiversx/mx-chain-go/blob/v1.6.18/process/transactionLog/process.go#L159 // Right now, the logic below is duplicated (see "TransactionsConverter"). However, "ResultsParser" will be deprecated & removed at a later time. - const legacyData = transactionEvent.dataPayload?.valueOf() || Buffer.from([]); - const dataItems = transactionEvent.additionalData?.map((data) => Buffer.from(data.valueOf())) || []; - + const legacyData = transactionEvent.data?.valueOf() || Buffer.from([]); + const dataItems = transactionEvent.additionalData?.map((data) => Buffer.from(data)) || []; if (dataItems.length === 0) { if (legacyData.length) { dataItems.push(Buffer.from(legacyData)); @@ -419,7 +419,6 @@ export class ResultsParser { // "Indexed" ABI "event.inputs" correspond to "event.topics[1:]": const indexedInputs = options.eventDefinition.inputs.filter((input) => input.indexed); const decodedTopics = this.argsSerializer.buffersToValues(options.topics, indexedInputs); - for (let i = 0; i < indexedInputs.length; i++) { result[indexedInputs[i].name] = decodedTopics[i].valueOf(); } @@ -427,9 +426,8 @@ export class ResultsParser { // "Non-indexed" ABI "event.inputs" correspond to "event.data": const nonIndexedInputs = options.eventDefinition.inputs.filter((input) => !input.indexed); const decodedDataParts = this.argsSerializer.buffersToValues(options.dataItems, nonIndexedInputs); - for (let i = 0; i < nonIndexedInputs.length; i++) { - result[nonIndexedInputs[i].name] = decodedDataParts[i].valueOf(); + result[nonIndexedInputs[i].name] = decodedDataParts[i]?.valueOf(); } return result; diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 4627f5596..7a46ed468 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -1,6 +1,7 @@ import { AxiosHeaders } from "axios"; import { assert } from "chai"; import { Address } from "../address"; +import { b64ToHex } from "../testutils"; import { MockQuery } from "../testutils/dummyQuery"; import { TransactionOnNetwork } from "../transactions"; import { ApiNetworkProvider } from "./apiNetworkProvider"; @@ -295,18 +296,18 @@ describe("test network providers on devnet: Proxy and API", function () { assert.exists(proxyResponse.logs); assert.exists(apiResponse.logs.events); assert.exists(proxyResponse.logs.events); - assert.equal(apiResponse.logs.events[0].topics[0].toString(), "414c4943452d353632376631"); - assert.equal(apiResponse.logs.events[0].topics[1].toString(), ""); - assert.equal(apiResponse.logs.events[0].topics[2].toString(), "01"); + assert.equal(b64ToHex(apiResponse.logs.events[0].topics[0].toString()), "414c4943452d353632376631"); + assert.equal(b64ToHex(apiResponse.logs.events[0].topics[1].toString()), ""); + assert.equal(b64ToHex(apiResponse.logs.events[0].topics[2].toString()), "01"); assert.equal( - apiResponse.logs.events[0].topics[3].toString(), + b64ToHex(apiResponse.logs.events[0].topics[3].toString()), "0000000000000000050032e141d21536e2dfc3d64b9e7dd0c2c53f201dc469e1", ); - assert.equal(proxyResponse.logs.events[0].topics[0].toString(), "414c4943452d353632376631"); - assert.equal(proxyResponse.logs.events[0].topics[1].toString(), ""); - assert.equal(proxyResponse.logs.events[0].topics[2].toString(), "01"); + assert.equal(b64ToHex(proxyResponse.logs.events[0].topics[0].toString()), "414c4943452d353632376631"); + assert.equal(b64ToHex(proxyResponse.logs.events[0].topics[1].toString()), ""); + assert.equal(b64ToHex(proxyResponse.logs.events[0].topics[2].toString()), "01"); assert.equal( - proxyResponse.logs.events[0].topics[3].toString(), + b64ToHex(proxyResponse.logs.events[0].topics[3].toString()), "0000000000000000050032e141d21536e2dfc3d64b9e7dd0c2c53f201dc469e1", ); }); @@ -402,11 +403,8 @@ describe("test network providers on devnet: Proxy and API", function () { "a419271407a2ec217739811805e3a751e30dbc72ae0777e3b4c825f036995184", ); - assert.equal(apiResponse.logs.events[0].data, Buffer.from("test").toString()); - assert.equal(proxyResponse.logs.events[0].data, Buffer.from("test").toString()); - - assert.deepEqual(apiResponse.logs.events[0].dataPayload, Buffer.from("dGVzdA==")); - assert.deepEqual(proxyResponse.logs.events[0].dataPayload, Buffer.from("dGVzdA==")); + assert.deepEqual(apiResponse.logs.events[0].data, Buffer.from("dGVzdA==")); + assert.deepEqual(proxyResponse.logs.events[0].data, Buffer.from("dGVzdA==")); assert.deepEqual(apiResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==")]); assert.deepEqual(proxyResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==")]); diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index 0902a3be9..87f341140 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -25,7 +25,7 @@ describe("test smart contract transactions outcome parser", () => { topics: [ new Uint8Array(Buffer.from(contract.getPublicKey().toString("base64"))), new Uint8Array(Buffer.from(deployer.getPublicKey().toString("base64"))), - codeHash, + new Uint8Array(Buffer.from(codeHash.toString("base64"))), ], }), ], @@ -61,7 +61,7 @@ describe("test smart contract transactions outcome parser", () => { deployer.getPublicKey().toString("base64"), Buffer.from("wrong number of arguments").toString("base64"), ]), - dataPayload: Buffer.from("@75736572206572726f72"), + data: Buffer.from("QDc1NzM2NTcyMjA2NTcyNzI2Zjcy", "base64"), }), ], }), diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index a4d503028..234b4db25 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -1,4 +1,4 @@ -import { ArgSerializer, EndpointDefinition, ResultsParser, Type, UntypedOutcomeBundle } from "../abi"; +import { AbiRegistry, ArgSerializer } from "../abi"; import { Address } from "../address"; import { ARGUMENTS_SEPARATOR } from "../constants"; import { Err } from "../errors"; @@ -12,32 +12,11 @@ enum Events { WriteLog = "writeLog", } -interface IAbi { - getEndpoint(name: string): EndpointDefinition; -} - -interface IParameterDefinition { - type: Type; -} - -interface ILegacyResultsParser { - parseOutcomeFromUntypedBundle( - bundle: UntypedOutcomeBundle, - endpoint: { output: IParameterDefinition[] }, - ): { - values: any[]; - returnCode: { valueOf(): string }; - returnMessage: string; - }; -} - export class SmartContractTransactionsOutcomeParser { - private readonly abi?: IAbi; - private readonly legacyResultsParser: ILegacyResultsParser; + private readonly abi?: AbiRegistry; - constructor(options?: { abi?: IAbi; legacyResultsParser?: ILegacyResultsParser }) { + constructor(options?: { abi?: AbiRegistry }) { this.abi = options?.abi; - this.legacyResultsParser = options?.legacyResultsParser || new ResultsParser(); } parseDeploy(options: { transactionOnNetwork: TransactionOnNetwork }): { @@ -87,7 +66,7 @@ export class SmartContractTransactionsOutcomeParser { } { const topicForAddress = Buffer.from(event.topics[0].toString(), "base64").toString("hex"); const topicForOwnerAddress = Buffer.from(event.topics[1].toString(), "base64").toString("hex"); - const topicForCodeHash = event.topics[2]; + const topicForCodeHash = Buffer.from(event.topics[2].toString(), "base64"); const address = topicForAddress?.length ? new Address(topicForAddress).toBech32() : ""; const ownerAddress = topicForOwnerAddress?.length ? new Address(topicForOwnerAddress).toBech32() : ""; const codeHash = topicForCodeHash; @@ -152,11 +131,13 @@ export class SmartContractTransactionsOutcomeParser { } outcome = this.findDirectSmartContractCallOutcomeIfError(transactionOnNetwork); + if (outcome) { return outcome; } outcome = this.findDirectSmartContractCallOutcomeWithinWriteLogEvents(transactionOnNetwork); + if (outcome) { return outcome; } @@ -238,7 +219,7 @@ export class SmartContractTransactionsOutcomeParser { } const [event] = eligibleEvents; - const data = event.dataPayload?.valueOf().toString() || ""; + const data = Buffer.from(event.data).toString(); const lastTopic = event.getLastTopic()?.toString(); const parts = argSerializer.stringToBuffers(data); // Assumption: the last part is the return code. @@ -283,7 +264,7 @@ export class SmartContractTransactionsOutcomeParser { } const [event] = eligibleEvents; - const data = event.dataPayload?.valueOf().toString() || ""; + const data = Buffer.from(event.data).toString(); const [_ignored, returnCode, ...returnDataParts] = argSerializer.stringToBuffers(data); return new SmartContractCallOutcome({ diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index 0b19c55a7..b6d90eac1 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -94,3 +94,7 @@ export function createAccountBalance(egld: number): BigNumber { export function b64TopicsToBytes(topics: string[]): Uint8Array[] { return topics.map((topic) => Buffer.from(topic, "base64")); } + +export function b64ToHex(value: string): string { + return Buffer.from(value, "base64").toString("hex"); +} diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index 3231f3179..1f735af8e 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -5,11 +5,7 @@ export class TransactionEvent { identifier: string = ""; topics: Uint8Array[] = []; - /** - * @deprecated Use "dataPayload" instead. - */ - data: string = ""; - dataPayload: Uint8Array = new Uint8Array(); + data: Uint8Array = new Uint8Array(); additionalData: Uint8Array[] = []; constructor(init?: Partial) { @@ -28,7 +24,8 @@ export class TransactionEvent { result.identifier = responsePart.identifier || ""; result.topics = (responsePart.topics || []).map((topic) => Buffer.from(topic)); - result.dataPayload = Buffer.from(responsePart.data ?? ""); + result.data = Buffer.from(responsePart.data ?? "", "base64"); + result.additionalData = (responsePart.additionalData || []).map((data) => Buffer.from(data)); return result; diff --git a/src/transactions.ts b/src/transactions.ts index 7c14308da..e30a0d6bc 100644 --- a/src/transactions.ts +++ b/src/transactions.ts @@ -70,7 +70,7 @@ export class TransactionOnNetwork { processStatus?: TransactionStatus | undefined, ): TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); - result.smartContractResults = response.smartContractResults; + result.smartContractResults = response.smartContractResults ?? []; if (processStatus) { result.status = processStatus; result.isCompleted = result.status.isSuccessful() || result.status.isFailed(); From 19233520d71fbddc92e792c5cfe848be54feefad Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 21 Nov 2024 16:20:34 +0200 Subject: [PATCH 050/214] Fix additional data field --- src/networkProviders/providers.dev.net.spec.ts | 8 ++++---- src/transactionEvents.ts | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 7a46ed468..d42805416 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -403,11 +403,11 @@ describe("test network providers on devnet: Proxy and API", function () { "a419271407a2ec217739811805e3a751e30dbc72ae0777e3b4c825f036995184", ); - assert.deepEqual(apiResponse.logs.events[0].data, Buffer.from("dGVzdA==")); - assert.deepEqual(proxyResponse.logs.events[0].data, Buffer.from("dGVzdA==")); + assert.deepEqual(apiResponse.logs.events[0].data, Buffer.from("dGVzdA==", "base64")); + assert.deepEqual(proxyResponse.logs.events[0].data, Buffer.from("dGVzdA==", "base64")); - assert.deepEqual(apiResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==")]); - assert.deepEqual(proxyResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==")]); + assert.deepEqual(apiResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==", "base64")]); + assert.deepEqual(proxyResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==", "base64")]); }); it("should send both `Transaction` and `TransactionNext`", async function () { diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index 1f735af8e..feafb1e75 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -26,7 +26,7 @@ export class TransactionEvent { result.data = Buffer.from(responsePart.data ?? "", "base64"); - result.additionalData = (responsePart.additionalData || []).map((data) => Buffer.from(data)); + result.additionalData = (responsePart.additionalData || []).map((data) => Buffer.from(data, "base64")); return result; } From 981b6c6e1b5788ec21fc251c548ac7e7e613150d Mon Sep 17 00:00:00 2001 From: danielailie Date: Fri, 22 Nov 2024 11:20:43 +0200 Subject: [PATCH 051/214] Update mapping for sc results --- src/transactions.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/transactions.ts b/src/transactions.ts index e30a0d6bc..10d1389ac 100644 --- a/src/transactions.ts +++ b/src/transactions.ts @@ -70,7 +70,11 @@ export class TransactionOnNetwork { processStatus?: TransactionStatus | undefined, ): TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); - result.smartContractResults = response.smartContractResults ?? []; + result.smartContractResults = + response.smartContractResults?.map( + (result: Partial) => new SmartContractResult({ ...result, raw: result }), + ) ?? []; + if (processStatus) { result.status = processStatus; result.isCompleted = result.status.isSuccessful() || result.status.isFailed(); @@ -81,7 +85,10 @@ export class TransactionOnNetwork { static fromApiHttpResponse(txHash: string, response: any): TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); - result.smartContractResults = response.results ?? []; + result.smartContractResults = + response.smartContractResults?.map( + (result: Partial) => new SmartContractResult({ ...result, raw: result }), + ) ?? []; result.isCompleted = !result.status.isPending(); return result; } From d6cdcfee746f678e4469f2f7effb786f6229f73d Mon Sep 17 00:00:00 2001 From: danielailie Date: Fri, 22 Nov 2024 11:22:58 +0200 Subject: [PATCH 052/214] Fix api Mapping --- src/transactions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transactions.ts b/src/transactions.ts index 10d1389ac..5b33fa992 100644 --- a/src/transactions.ts +++ b/src/transactions.ts @@ -86,7 +86,7 @@ export class TransactionOnNetwork { static fromApiHttpResponse(txHash: string, response: any): TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); result.smartContractResults = - response.smartContractResults?.map( + response.results?.map( (result: Partial) => new SmartContractResult({ ...result, raw: result }), ) ?? []; result.isCompleted = !result.status.isPending(); From 2d08f19f71e856d759bb9f2bcb8c87e630e5a999 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 25 Nov 2024 10:36:32 +0200 Subject: [PATCH 053/214] Code review follow up --- src/abi/resultsParser.ts | 2 +- src/delegation/delegationController.ts | 2 +- ...elegationTransactionsOutcomeParser.spec.ts | 6 +- .../delegationTransactionsOutcomeParser.ts | 4 +- src/entrypoints/entrypoints.ts | 2 +- src/index.ts | 2 +- src/interface.ts | 2 +- src/networkProviders/apiNetworkProvider.ts | 2 +- src/networkProviders/interface.ts | 2 +- src/networkProviders/proxyNetworkProvider.ts | 2 +- src/smartContracts/smartContractController.ts | 2 +- .../smartContractTransactionsOutcomeParser.ts | 2 +- src/testutils/mockNetworkProvider.ts | 2 +- src/tokenManagement/resources.ts | 2 + .../tokenManagementController.ts | 62 ++++++++-------- ...anagementTransactionsOutcomeParser.spec.ts | 74 +++++++++---------- ...okenManagementTransactionsOutcomeParser.ts | 4 +- src/transactionEvents.ts | 2 +- ...ransactions.ts => transactionOnNetwork.ts} | 0 src/transactionWatcher.ts | 4 +- src/transactionsOutcomeParsers/resources.ts | 2 +- 21 files changed, 92 insertions(+), 90 deletions(-) rename src/{transactions.ts => transactionOnNetwork.ts} (100%) diff --git a/src/abi/resultsParser.ts b/src/abi/resultsParser.ts index 4b7508672..fda7147ac 100644 --- a/src/abi/resultsParser.ts +++ b/src/abi/resultsParser.ts @@ -8,7 +8,7 @@ import { IContractQueryResponse } from "../interfaceOfNetwork"; import { Logger } from "../logger"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { ArgSerializer } from "./argSerializer"; import { TypedOutcomeBundle, UntypedOutcomeBundle } from "./interface"; diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index a37fabec5..868cbc554 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -2,7 +2,7 @@ import { IAccount } from "../accounts/interfaces"; import { INetworkProvider } from "../networkProviders/interface"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; diff --git a/src/delegation/delegationTransactionsOutcomeParser.spec.ts b/src/delegation/delegationTransactionsOutcomeParser.spec.ts index b415aa747..bdbcc7694 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.spec.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.spec.ts @@ -3,7 +3,7 @@ import { Address } from "../address"; import { b64TopicsToBytes } from "../testutils"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; @@ -59,9 +59,9 @@ describe("test delegation transactions outcome parser", () => { ), logs: scResultLog, }); - const txOutcome = new TransactionOnNetwork({ smartContractResults: [scResult], logs: logs }); + const transaction = new TransactionOnNetwork({ smartContractResults: [scResult], logs: logs }); - const outcome = parser.parseCreateNewDelegationContract(txOutcome); + const outcome = parser.parseCreateNewDelegationContract(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].contractAddress, contractAddress.toBech32()); diff --git a/src/delegation/delegationTransactionsOutcomeParser.ts b/src/delegation/delegationTransactionsOutcomeParser.ts index 9a8caecfa..ec7a51442 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.ts @@ -1,7 +1,7 @@ import { Address } from "../address"; import { ErrParseTransactionOutcome } from "../errors"; import { TransactionEvent } from "../transactionEvents"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; export class DelegationTransactionsOutcomeParser { @@ -33,7 +33,7 @@ export class DelegationTransactionsOutcomeParser { return ""; } const address = Buffer.from(event.topics[0]); - return new Address(address).bech32(); + return new Address(address).toBech32(); } private decodeTopicAsString(topic: Uint8Array): string { diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index b3a3167b5..713779c54 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -11,7 +11,7 @@ import { SmartContractController } from "../smartContracts/smartContractControll import { TokenManagementController } from "../tokenManagement"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionWatcher } from "../transactionWatcher"; import { TransfersController } from "../transfers/transfersControllers"; import { UserVerifier } from "../wallet"; diff --git a/src/index.ts b/src/index.ts index d6cddccb1..88e182683 100644 --- a/src/index.ts +++ b/src/index.ts @@ -33,8 +33,8 @@ export * from "./tokenManagement"; export * from "./tokens"; export * from "./transaction"; export * from "./transactionComputer"; +export * from "./transactionOnNetwork"; export * from "./transactionPayload"; -export * from "./transactions"; export * from "./transactionsOutcomeParsers"; export * from "./transactionStatus"; export * from "./transactionWatcher"; diff --git a/src/interface.ts b/src/interface.ts index 46a22c3c4..a1e7fe422 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import { TransactionOnNetwork } from "./transactions"; +import { TransactionOnNetwork } from "./transactionOnNetwork"; export interface ITransactionFetcher { /** diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 33e54af5e..807f1640e 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,5 +1,5 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; -import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactions"; +import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; import { numberToPaddedHex } from "../utils.codec"; diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index a763355c9..b2045ecbc 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,5 +1,5 @@ import { ITransaction as ITransactionAsInSpecs } from "../interface"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { AccountOnNetwork } from "./accounts"; import { ContractQueryResponse } from "./contractQueryResponse"; diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 5895c8867..a9989b62b 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,5 +1,5 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; -import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactions"; +import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; import { AccountOnNetwork, GuardianData } from "./accounts"; diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index 1b0b64f1e..e62955fb6 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -6,7 +6,7 @@ import { INetworkProvider } from "../networkProviders/interface"; import { SmartContractQueriesController } from "../smartContractQueriesController"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { SmartContractTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; import { TransactionWatcher } from "../transactionWatcher"; diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 234b4db25..ead68f6d3 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -3,7 +3,7 @@ import { Address } from "../address"; import { ARGUMENTS_SEPARATOR } from "../constants"; import { Err } from "../errors"; import { TransactionEvent } from "../transactionEvents"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractCallOutcome, SmartContractResult } from "../transactionsOutcomeParsers/resources"; enum Events { diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index e83810c04..1e6efc012 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -6,7 +6,7 @@ import { ErrMock } from "../errors"; import { IAddress } from "../interface"; import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionStatus } from "../interfaceOfNetwork"; import { Transaction, TransactionHash } from "../transaction"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { TransactionStatus } from "../transactionStatus"; import { createAccountBalance } from "./utils"; diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index c68295a2f..1297652e6 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -116,3 +116,5 @@ export type MintNftOutput = { nonce: bigint; initialQuantity: bigint; }; + +export type EsdtOutput = { tokenIdentifier: string }; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index d648f46b5..45d99ed62 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -2,7 +2,7 @@ import { IAccount } from "../accounts/interfaces"; import { INetworkProvider } from "../networkProviders/interface"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TokenManagementTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; import { TransactionWatcher } from "../transactionWatcher"; @@ -37,12 +37,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedIssueFungible(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedIssueFungible(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseIssueFungible(transaction); } - parseIssueFungible(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseIssueFungible(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseIssueFungible(transactionOnNetwork); } @@ -59,12 +59,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedIssueSemiFungible(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedIssueSemiFungible(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseIssueSemiFungible(transaction); } - parseIssueSemiFungible(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseIssueSemiFungible(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseIssueSemiFungible(transactionOnNetwork); } @@ -81,12 +81,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedIssueNonFungible(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedIssueNonFungible(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseIssueNonFungible(transaction); } - parseIssueNonFungible(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseIssueNonFungible(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseIssueNonFungible(transactionOnNetwork); } @@ -103,12 +103,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedRegisterMetaEsdt(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedRegisterMetaEsdt(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseRegisterMetaEsdt(transaction); } - parseRegisterMetaEsdt(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseRegisterMetaEsdt(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseRegisterMetaEsdt(transactionOnNetwork); } @@ -125,12 +125,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedRegisterAndSettingRoles(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedRegisterAndSettingRoles(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseRegisterAndSetAllRoles(transaction); } - parseRegisterAndSetAllRoles(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseRegisterAndSetAllRoles(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseRegisterMetaEsdt(transactionOnNetwork); } @@ -285,12 +285,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedPause(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedPause(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parsePause(transaction); } - parsePause(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parsePause(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parsePause(transactionOnNetwork); } @@ -307,12 +307,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedUnpause(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedUnpause(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseUnpause(transaction); } - parseUnpause(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseUnpause(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseUnpause(transactionOnNetwork); } @@ -329,12 +329,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedFreeze(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedFreeze(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseFreeze(transaction); } - parseFreeze(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseFreeze(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseFreeze(transactionOnNetwork); } @@ -351,12 +351,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedUnfreeze(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedUnfreeze(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseUnfreeze(transaction); } - parseUnfreeze(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseUnfreeze(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseUnfreeze(transactionOnNetwork); } @@ -373,12 +373,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedWipe(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedWipe(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parser.parseWipe(transaction); } - parseWipe(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseWipe(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseWipe(transactionOnNetwork); } @@ -395,12 +395,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedLocalMint(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedLocalMint(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseLocalMint(transaction); } - parseLocalMint(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseLocalMint(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseLocalMint(transactionOnNetwork); } @@ -417,12 +417,12 @@ export class TokenManagementController { return transaction; } - async awaitCompleteLocalBurn(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompleteLocalBurn(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseLocalBurn(transaction); } - parseLocalBurn(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseLocalBurn(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseLocalBurn(transactionOnNetwork); } @@ -439,12 +439,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedUpdateAttributes(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedUpdateAttributes(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseUpdateAttributes(transaction); } - parseUpdateAttributes(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseUpdateAttributes(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseUpdateAttributes(transactionOnNetwork); } @@ -461,12 +461,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedAddQuantity(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedAddQuantity(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseAddQuantity(transaction); } - parseAddQuantity(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseAddQuantity(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseAddQuantity(transactionOnNetwork); } @@ -483,12 +483,12 @@ export class TokenManagementController { return transaction; } - async awaitCompletedBurnQuantity(txHash: string): Promise<{ tokenIdentifier: string }[]> { + async awaitCompletedBurnQuantity(txHash: string): Promise { const transaction = await this.transactionAwaiter.awaitCompleted(txHash); return this.parseBurnQuantity(transaction); } - parseBurnQuantity(transactionOnNetwork: TransactionOnNetwork): { tokenIdentifier: string }[] { + parseBurnQuantity(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseBurnQuantity(transactionOnNetwork); } } diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts index 9e508c8e2..d1749dbf6 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts @@ -4,7 +4,7 @@ import { ErrParseTransactionOutcome } from "../errors"; import { b64TopicsToBytes } from "../testutils"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { TokenManagementTransactionsOutcomeParser } from "./tokenManagementTransactionsOutcomeParser"; @@ -21,11 +21,11 @@ describe("test token management transactions outcome parser", () => { }); const logs = new TransactionLogs({ events: [event] }); - const txOutcome = new TransactionOnNetwork({ logs: logs }); + const transaction = new TransactionOnNetwork({ logs: logs }); assert.throws( () => { - parser.parseIssueFungible(txOutcome); + parser.parseIssueFungible(transaction); }, ErrParseTransactionOutcome, "encountered signalError: ticker name is not valid (user error)", @@ -48,9 +48,9 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ logs: logs }); + const transaction = new TransactionOnNetwork({ logs: logs }); - const outcome = parser.parseIssueFungible(txOutcome); + const outcome = parser.parseIssueFungible(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); }); @@ -92,9 +92,9 @@ describe("test token management transactions outcome parser", () => { events: [firstEvent, secondEvent, thirdEvent], }); - const txOutcome = new TransactionOnNetwork({ logs: logs }); + const transaction = new TransactionOnNetwork({ logs: logs }); - const outcome = parser.parseIssueNonFungible(txOutcome); + const outcome = parser.parseIssueNonFungible(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); }); @@ -115,9 +115,9 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ logs: logs }); + const transaction = new TransactionOnNetwork({ logs: logs }); - const outcome = parser.parseIssueSemiFungible(txOutcome); + const outcome = parser.parseIssueSemiFungible(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); }); @@ -138,9 +138,9 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ logs: logs }); + const transaction = new TransactionOnNetwork({ logs: logs }); - const outcome = parser.parseRegisterMetaEsdt(txOutcome); + const outcome = parser.parseRegisterMetaEsdt(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); }); @@ -202,12 +202,12 @@ describe("test token management transactions outcome parser", () => { logs: resultLogs, }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ smartContractResults: [scResult], logs: transactionLogs, }); - const outcome = parser.parseRegisterAndSetAllRoles(txOutcome); + const outcome = parser.parseRegisterAndSetAllRoles(transaction); assert.lengthOf(outcome, 2); assert.equal(outcome[0].tokenIdentifier, firstIdentifier); @@ -241,11 +241,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parseSetSpecialRole(txOutcome); + const outcome = parser.parseSetSpecialRole(transaction); assert.lengthOf(outcome, 1); assert.deepEqual( outcome[0].userAddress, @@ -278,11 +278,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parseNftCreate(txOutcome); + const outcome = parser.parseNftCreate(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); assert.equal(outcome[0].nonce, nonce); @@ -307,11 +307,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parseLocalMint(txOutcome); + const outcome = parser.parseLocalMint(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].userAddress, event.address); assert.equal(outcome[0].tokenIdentifier, identifier); @@ -337,11 +337,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parseLocalBurn(txOutcome); + const outcome = parser.parseLocalBurn(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].userAddress, event.address); assert.equal(outcome[0].tokenIdentifier, identifier); @@ -365,11 +365,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parsePause(txOutcome); + const outcome = parser.parsePause(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); }); @@ -390,11 +390,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parseUnpause(txOutcome); + const outcome = parser.parseUnpause(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); }); @@ -427,11 +427,11 @@ describe("test token management transactions outcome parser", () => { }), ]; - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ smartContractResults: scResult, }); - const outcome = parser.parseFreeze(txOutcome); + const outcome = parser.parseFreeze(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].userAddress, address); assert.equal(outcome[0].tokenIdentifier, identifier); @@ -467,11 +467,11 @@ describe("test token management transactions outcome parser", () => { }), ]; - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ smartContractResults: scResult, }); - const outcome = parser.parseUnfreeze(txOutcome); + const outcome = parser.parseUnfreeze(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].userAddress, address); assert.equal(outcome[0].tokenIdentifier, identifier); @@ -507,9 +507,9 @@ describe("test token management transactions outcome parser", () => { }), ]; - const txOutcome = new TransactionOnNetwork({ smartContractResults: scResult }); + const transaction = new TransactionOnNetwork({ smartContractResults: scResult }); - const outcome = parser.parseWipe(txOutcome); + const outcome = parser.parseWipe(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].userAddress, address); assert.equal(outcome[0].tokenIdentifier, identifier); @@ -536,11 +536,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parseUpdateAttributes(txOutcome); + const outcome = parser.parseUpdateAttributes(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); assert.equal(outcome[0].nonce, nonce); @@ -565,11 +565,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parseAddQuantity(txOutcome); + const outcome = parser.parseAddQuantity(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); assert.equal(outcome[0].nonce, nonce); @@ -594,11 +594,11 @@ describe("test token management transactions outcome parser", () => { events: [event], }); - const txOutcome = new TransactionOnNetwork({ + const transaction = new TransactionOnNetwork({ logs: transactionLogs, }); - const outcome = parser.parseBurnQuantity(txOutcome); + const outcome = parser.parseBurnQuantity(transaction); assert.lengthOf(outcome, 1); assert.equal(outcome[0].tokenIdentifier, identifier); assert.equal(outcome[0].nonce, nonce); diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index bc12931a4..8f9770706 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -2,7 +2,7 @@ import { bufferToBigInt } from "../abi/codec/utils"; import { Address } from "../address"; import { ErrParseTransactionOutcome } from "../errors"; import { TransactionEvent } from "../transactionEvents"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; import { MintNftOutput, SpecialRoleOutput } from "./resources"; @@ -390,7 +390,7 @@ export class TokenManagementTransactionsOutcomeParser { return ""; } const address = Buffer.from(event.topics[3]); - return new Address(address).bech32(); + return new Address(address).toBech32(); } private decodeTopicAsString(topic: Uint8Array): string { diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index feafb1e75..725f92009 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -22,7 +22,7 @@ export class TransactionEvent { let result = new TransactionEvent(); result.address = new Address(responsePart.address); result.identifier = responsePart.identifier || ""; - result.topics = (responsePart.topics || []).map((topic) => Buffer.from(topic)); + result.topics = (responsePart.topics || []).map((topic) => Buffer.from(topic, "base64")); result.data = Buffer.from(responsePart.data ?? "", "base64"); diff --git a/src/transactions.ts b/src/transactionOnNetwork.ts similarity index 100% rename from src/transactions.ts rename to src/transactionOnNetwork.ts diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index 619093d30..d0483105f 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -10,7 +10,7 @@ import { ITransactionFetcher } from "./interface"; import { ITransactionStatus } from "./interfaceOfNetwork"; import { Logger } from "./logger"; import { TransactionEvent } from "./transactionEvents"; -import { TransactionOnNetwork } from "./transactions"; +import { TransactionOnNetwork } from "./transactionOnNetwork"; export type PredicateIsAwaitedStatus = (status: ITransactionStatus) => boolean; @@ -224,7 +224,7 @@ export class TransactionWatcher { const result = [...transaction.logs.events]; for (const resultItem of transaction.smartContractResults) { - result.push(...resultItem.logs.events); + result.push(...resultItem.logs?.events); } return result; diff --git a/src/transactionsOutcomeParsers/resources.ts b/src/transactionsOutcomeParsers/resources.ts index fad5ed713..8bbfadcf2 100644 --- a/src/transactionsOutcomeParsers/resources.ts +++ b/src/transactionsOutcomeParsers/resources.ts @@ -1,7 +1,7 @@ import { Address } from "../address"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; export class SmartContractResult { raw: Record; From 03ab27bdfc165271081a967d35e747fbe9ae13a8 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 25 Nov 2024 10:40:22 +0200 Subject: [PATCH 054/214] Fix tests --- src/abi/resultsParser.spec.ts | 2 +- src/networkProviders/providers.dev.net.spec.ts | 2 +- .../smartContractTransactionsOutcomeParser.spec.ts | 2 +- src/testutils/contractController.ts | 2 +- src/testutils/networkProviders.ts | 2 +- src/transactionWatcher.spec.ts | 2 +- src/transactionsOutcomeParsers/resources.spec.ts | 2 +- src/transactionsOutcomeParsers/transactionEventsParser.spec.ts | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/abi/resultsParser.spec.ts b/src/abi/resultsParser.spec.ts index fb5c9c114..7ce441301 100644 --- a/src/abi/resultsParser.spec.ts +++ b/src/abi/resultsParser.spec.ts @@ -5,7 +5,7 @@ import { ContractQueryResponse } from "../networkProviders"; import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { ArgSerializer } from "./argSerializer"; import { ResultsParser } from "./resultsParser"; diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index d42805416..56a2f654f 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -3,7 +3,7 @@ import { assert } from "chai"; import { Address } from "../address"; import { b64ToHex } from "../testutils"; import { MockQuery } from "../testutils/dummyQuery"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { ApiNetworkProvider } from "./apiNetworkProvider"; import { INetworkProvider, ITransactionNext } from "./interface"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index 87f341140..e49e1083d 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -4,7 +4,7 @@ import { Address } from "../address"; import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { SmartContractTransactionsOutcomeParser } from "./smartContractTransactionsOutcomeParser"; diff --git a/src/testutils/contractController.ts b/src/testutils/contractController.ts index fe2604239..18f3f9e46 100644 --- a/src/testutils/contractController.ts +++ b/src/testutils/contractController.ts @@ -1,7 +1,7 @@ import { Interaction, ResultsParser, TypedOutcomeBundle, UntypedOutcomeBundle } from "../abi"; import { Logger } from "../logger"; import { Transaction } from "../transaction"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionWatcher } from "../transactionWatcher"; import { INetworkProvider } from "./networkProviders"; diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 288a2ba78..e75ffa19b 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -4,7 +4,7 @@ import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransaction import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { Transaction } from "../transaction"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; export function createLocalnetProvider(): INetworkProvider { return new ProxyNetworkProvider("http://localhost:7950", { timeout: 5000 }); diff --git a/src/transactionWatcher.spec.ts b/src/transactionWatcher.spec.ts index f459d7240..f5161f4a8 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/transactionWatcher.spec.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import { MarkCompleted, MockNetworkProvider, Wait } from "./testutils"; import { TransactionHash } from "./transaction"; -import { TransactionOnNetwork } from "./transactions"; +import { TransactionOnNetwork } from "./transactionOnNetwork"; import { TransactionStatus } from "./transactionStatus"; import { TransactionWatcher } from "./transactionWatcher"; diff --git a/src/transactionsOutcomeParsers/resources.spec.ts b/src/transactionsOutcomeParsers/resources.spec.ts index c22903936..8aa37074e 100644 --- a/src/transactionsOutcomeParsers/resources.spec.ts +++ b/src/transactionsOutcomeParsers/resources.spec.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { findEventsByFirstTopic, findEventsByIdentifier, SmartContractResult } from "./resources"; describe("test resources", () => { diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts index 30bbe6749..d5fb21d24 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts @@ -5,7 +5,7 @@ import { Address } from "../address"; import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; import { TransactionEvent } from "../transactionEvents"; import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactions"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; import { findEventsByFirstTopic, SmartContractResult } from "./resources"; import { TransactionEventsParser } from "./transactionEventsParser"; From 8d90e986f50dc0843b941a0eb3a22835eba90b0f Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 25 Nov 2024 11:10:49 +0200 Subject: [PATCH 055/214] FIx tests --- .../providers.dev.net.spec.ts | 20 ++++++++++--------- .../smartContractTransactionsOutcomeParser.ts | 6 +++--- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 56a2f654f..0e24a89bf 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -1,7 +1,6 @@ import { AxiosHeaders } from "axios"; import { assert } from "chai"; import { Address } from "../address"; -import { b64ToHex } from "../testutils"; import { MockQuery } from "../testutils/dummyQuery"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { ApiNetworkProvider } from "./apiNetworkProvider"; @@ -296,18 +295,21 @@ describe("test network providers on devnet: Proxy and API", function () { assert.exists(proxyResponse.logs); assert.exists(apiResponse.logs.events); assert.exists(proxyResponse.logs.events); - assert.equal(b64ToHex(apiResponse.logs.events[0].topics[0].toString()), "414c4943452d353632376631"); - assert.equal(b64ToHex(apiResponse.logs.events[0].topics[1].toString()), ""); - assert.equal(b64ToHex(apiResponse.logs.events[0].topics[2].toString()), "01"); + assert.equal(Buffer.from(apiResponse.logs.events[0].topics[0]).toString("hex"), "414c4943452d353632376631"); + assert.equal(Buffer.from(apiResponse.logs.events[0].topics[1]).toString("hex"), ""); + assert.equal(Buffer.from(apiResponse.logs.events[0].topics[2]).toString("hex"), "01"); assert.equal( - b64ToHex(apiResponse.logs.events[0].topics[3].toString()), + Buffer.from(apiResponse.logs.events[0].topics[3]).toString("hex"), "0000000000000000050032e141d21536e2dfc3d64b9e7dd0c2c53f201dc469e1", ); - assert.equal(b64ToHex(proxyResponse.logs.events[0].topics[0].toString()), "414c4943452d353632376631"); - assert.equal(b64ToHex(proxyResponse.logs.events[0].topics[1].toString()), ""); - assert.equal(b64ToHex(proxyResponse.logs.events[0].topics[2].toString()), "01"); assert.equal( - b64ToHex(proxyResponse.logs.events[0].topics[3].toString()), + Buffer.from(proxyResponse.logs.events[0].topics[0].toString()).toString("hex"), + "414c4943452d353632376631", + ); + assert.equal(Buffer.from(proxyResponse.logs.events[0].topics[1].toString()).toString("hex"), ""); + assert.equal(Buffer.from(proxyResponse.logs.events[0].topics[2].toString()).toString("hex"), "01"); + assert.equal( + Buffer.from(proxyResponse.logs.events[0].topics[3]).toString("hex"), "0000000000000000050032e141d21536e2dfc3d64b9e7dd0c2c53f201dc469e1", ); }); diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index ead68f6d3..72923d428 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -64,9 +64,9 @@ export class SmartContractTransactionsOutcomeParser { ownerAddress: string; codeHash: Uint8Array; } { - const topicForAddress = Buffer.from(event.topics[0].toString(), "base64").toString("hex"); - const topicForOwnerAddress = Buffer.from(event.topics[1].toString(), "base64").toString("hex"); - const topicForCodeHash = Buffer.from(event.topics[2].toString(), "base64"); + const topicForAddress = Buffer.from(event.topics[0]).toString("hex"); + const topicForOwnerAddress = Buffer.from(event.topics[1]).toString("hex"); + const topicForCodeHash = Buffer.from(event.topics[2]); const address = topicForAddress?.length ? new Address(topicForAddress).toBech32() : ""; const ownerAddress = topicForOwnerAddress?.length ? new Address(topicForOwnerAddress).toBech32() : ""; const codeHash = topicForCodeHash; From 9a7ed4c7b197e5192eacc57d8c70172440acc7fa Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 25 Nov 2024 11:49:50 +0200 Subject: [PATCH 056/214] Fix test encoding --- .../smartContractTransactionsOutcomeParser.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index e49e1083d..1f1b151dd 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -23,9 +23,9 @@ describe("test smart contract transactions outcome parser", () => { new TransactionEvent({ identifier: "SCDeploy", topics: [ - new Uint8Array(Buffer.from(contract.getPublicKey().toString("base64"))), - new Uint8Array(Buffer.from(deployer.getPublicKey().toString("base64"))), - new Uint8Array(Buffer.from(codeHash.toString("base64"))), + new Uint8Array(Buffer.from(contract.getPublicKey().toString("base64"), "base64")), + new Uint8Array(Buffer.from(deployer.getPublicKey().toString("base64"), "base64")), + new Uint8Array(Buffer.from(codeHash.toString("base64"), "base64")), ], }), ], From c8000bed6529b0fb412f93f1d0d92bb01da68072 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 27 Nov 2024 11:23:57 +0200 Subject: [PATCH 057/214] Remove result parser and smart contract querties --- src/abi/index.ts | 1 - src/abi/interaction.spec.ts | 143 +++--- src/abi/interaction.ts | 4 +- src/abi/query.ts | 12 +- src/abi/resultsParser.spec.ts | 371 --------------- src/abi/resultsParser.ts | 435 ------------------ src/abi/smartContract.local.net.spec.ts | 2 - .../smartContractResults.local.net.spec.ts | 3 - src/adapters/queryRunnerAdapter.ts | 5 +- src/entrypoints/entrypoints.spec.ts | 2 +- src/index.ts | 1 - src/networkProviders/apiNetworkProvider.ts | 8 +- src/networkProviders/contractQueryRequest.ts | 16 +- src/networkProviders/interface.ts | 4 +- .../providers.dev.net.spec.ts | 14 +- src/networkProviders/proxyNetworkProvider.ts | 21 +- src/smartContractQueriesController.ts | 120 ----- src/smartContractQuery.ts | 43 +- src/smartContracts/resources.ts | 5 + .../smartContractController.spec.ts} | 108 ++--- src/smartContracts/smartContractController.ts | 122 ++++- .../smartContractTransactionsOutcomeParser.ts | 20 +- src/testutils/contractController.ts | 69 --- src/testutils/mockNetworkProvider.ts | 120 ++++- src/testutils/networkProviders.ts | 6 +- src/transactionEvents.ts | 8 - .../transactionEventsParser.ts | 27 +- 27 files changed, 441 insertions(+), 1249 deletions(-) delete mode 100644 src/abi/resultsParser.spec.ts delete mode 100644 src/abi/resultsParser.ts delete mode 100644 src/smartContractQueriesController.ts rename src/{smartContractQueriesController.spec.ts => smartContracts/smartContractController.spec.ts} (67%) delete mode 100644 src/testutils/contractController.ts diff --git a/src/abi/index.ts b/src/abi/index.ts index 58f299694..58a6a1f79 100644 --- a/src/abi/index.ts +++ b/src/abi/index.ts @@ -8,7 +8,6 @@ export * from "./interactionChecker"; export * from "./interface"; export * from "./nativeSerializer"; export * from "./query"; -export * from "./resultsParser"; export * from "./returnCode"; export * from "./smartContract"; export * from "./transactionPayloadBuilders"; diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 3e1f5b808..099013157 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -1,7 +1,8 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Address } from "../address"; -import { ContractQueryResponse } from "../networkProviders"; +import { SmartContractQueryInput, SmartContractQueryResponse } from "../smartContractQuery"; +import { SmartContractController } from "../smartContracts"; import { loadAbiRegistry, loadTestWallets, @@ -9,12 +10,10 @@ import { setupUnitTestWatcherTimeouts, TestWallet, } from "../testutils"; -import { ContractController } from "../testutils/contractController"; import { Token, TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; -import { ReturnCode } from "./returnCode"; import { SmartContract } from "./smartContract"; import { BigUIntValue, BytesValue, OptionalValue, OptionValue, TokenIdentifierValue, U32Value } from "./typesystem"; @@ -173,8 +172,8 @@ describe("test smart contract interactor", function () { }); it("should create transaction, with ABI, with transfer & execute", async function () { - const abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); - const contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); + const abi = await loadAbiRegistry("src/testdata/answer.abi.json"); + const contract = new SmartContract({ address: dummyAddress, abi: abi }); const alice = new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const token = new Token({ identifier: "FOO-abcdef", nonce: 0n }); @@ -207,7 +206,7 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); - let controller = new ContractController(provider); + let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry }); let interaction = contract.methods.getUltimateAnswer().withGasLimit(543210).withChainID("T"); @@ -218,18 +217,29 @@ describe("test smart contract interactor", function () { provider.mockQueryContractOnFunction( "getUltimateAnswer", - new ContractQueryResponse({ returnData: [Buffer.from([42]).toString("base64")], returnCode: "ok" }), + new SmartContractQueryResponse({ + returnDataParts: [Buffer.from([42])], + returnCode: "ok", + returnMessage: "msg", + function: "getUltimateAnswer", + }), ); - // Query - let { - values: queryValues, - firstValue: queryAnwser, - returnCode: queryCode, - } = await controller.query(interaction); - assert.lengthOf(queryValues, 1); - assert.deepEqual(queryAnwser!.valueOf(), new BigNumber(42)); - assert.isTrue(queryCode.equals(ReturnCode.Ok)); + // Query; + + const interactionQuery = interaction.buildQuery(); + let response = await controller.query( + new SmartContractQueryInput({ + contract: interactionQuery.address, + arguments: interactionQuery.getEncodedArguments(), + function: interactionQuery.func.toString(), + caller: interactionQuery.caller, + value: BigInt(interactionQuery.value.toString()), + }), + ); + console.log(22222, response); + assert.isTrue(response.length == 1); + assert.deepEqual(response[0], new BigNumber(42)); // Execute, do not wait for execution let transaction = interaction.withSender(alice.address).withNonce(0).buildTransaction(); @@ -257,20 +267,22 @@ describe("test smart contract interactor", function () { transaction = interaction.withNonce(2).buildTransaction(); transaction.setSender(alice.address); transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); - provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs"); - let { bundle } = await controller.execute(interaction, transaction); - - assert.lengthOf(bundle.values, 1); - assert.deepEqual(bundle.firstValue!.valueOf(), new BigNumber(43)); - assert.isTrue(bundle.returnCode.equals(ReturnCode.Ok)); + provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs", "getUltimateAnswer"); + let hash = await provider.sendTransaction(transaction); + let responseExecute = await controller.awaitCompletedExecute(hash); + + console.log(responseExecute, responseExecute.values[0]!.valueOf()); + assert.isTrue(responseExecute.values.length == 1); + assert.deepEqual(responseExecute.values[0], new BigNumber(43)); + assert.isTrue(responseExecute.returnCode == "ok"); }); it("should interact with 'counter'", async function () { setupUnitTestWatcherTimeouts(); - let abiRegistry = await loadAbiRegistry("src/testdata/counter.abi.json"); - let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); - let controller = new ContractController(provider); + let abi = await loadAbiRegistry("src/testdata/counter.abi.json"); + let contract = new SmartContract({ address: dummyAddress, abi: abi }); + let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abi }); let getInteraction = contract.methodsExplicit.get().check(); let incrementInteraction = (contract.methods.increment()).withGasLimit(543210); @@ -279,13 +291,26 @@ describe("test smart contract interactor", function () { // For "get()", return fake 7 provider.mockQueryContractOnFunction( "get", - new ContractQueryResponse({ returnData: [Buffer.from([7]).toString("base64")], returnCode: "ok" }), + new SmartContractQueryResponse({ + returnDataParts: [Buffer.from([7])], + returnCode: "ok", + function: "get", + returnMessage: "", + }), ); // Query "get()" - let { firstValue: counterValue } = await controller.query(getInteraction); - - assert.deepEqual(counterValue!.valueOf(), new BigNumber(7)); + const interactionQuery = getInteraction.buildQuery(); + let response = await controller.query( + new SmartContractQueryInput({ + contract: interactionQuery.address, + arguments: interactionQuery.getEncodedArguments(), + function: interactionQuery.func.toString(), + caller: interactionQuery.caller, + value: BigInt(interactionQuery.value.toString()), + }), + ); + assert.deepEqual(response[0], new BigNumber(7)); let incrementTransaction = incrementInteraction .withSender(alice.address) @@ -294,11 +319,10 @@ describe("test smart contract interactor", function () { .buildTransaction(); incrementTransaction.applySignature(await alice.signer.sign(incrementTransaction.serializeForSigning())); - provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@08"); - let { - bundle: { firstValue: valueAfterIncrement }, - } = await controller.execute(incrementInteraction, incrementTransaction); - assert.deepEqual(valueAfterIncrement!.valueOf(), new BigNumber(8)); + provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@08", "increment"); + let hash = await provider.sendTransaction(incrementTransaction); + let responseExecute = await controller.awaitCompletedExecute(hash); + assert.deepEqual(responseExecute.values[0], new BigNumber(8)); // Decrement three times (simulate three parallel broadcasts). Wait for execution of the latter (third transaction). Return fake "5". // Decrement #1 @@ -318,11 +342,10 @@ describe("test smart contract interactor", function () { decrementTransaction = decrementInteraction.withNonce(17).buildTransaction(); decrementTransaction.applySignature(await alice.signer.sign(decrementTransaction.serializeForSigning())); - provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@05"); - let { - bundle: { firstValue: valueAfterDecrement }, - } = await controller.execute(decrementInteraction, decrementTransaction); - assert.deepEqual(valueAfterDecrement!.valueOf(), new BigNumber(5)); + provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@05", "decrement"); + hash = await provider.sendTransaction(decrementTransaction); + responseExecute = await controller.awaitCompletedExecute(hash); + assert.deepEqual(responseExecute.values[0], new BigNumber(5)); }); it("should interact with 'lottery-esdt'", async function () { @@ -330,7 +353,7 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); - let controller = new ContractController(provider); + let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry }); let startInteraction = contract.methodsExplicit .start([ @@ -359,17 +382,17 @@ describe("test smart contract interactor", function () { .buildTransaction(); startTransaction.applySignature(await alice.signer.sign(startTransaction.serializeForSigning())); - provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b"); - let { - bundle: { returnCode: startReturnCode, values: startReturnValues }, - } = await controller.execute(startInteraction, startTransaction); + + provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b", "start"); + let hash = await provider.sendTransaction(startTransaction); + let response = await controller.awaitCompletedExecute(hash); assert.equal( startTransaction.getData().toString(), "start@6c75636b79@6c75636b792d746f6b656e@01@@@0100000001@@", ); - assert.isTrue(startReturnCode.equals(ReturnCode.Ok)); - assert.lengthOf(startReturnValues, 0); + assert.isTrue(response.returnCode == "ok"); + assert.isTrue(response.values.length == 0); // status() (this is a view function, but for the sake of the test, we'll execute it) let statusTransaction = statusInteraction @@ -379,15 +402,16 @@ describe("test smart contract interactor", function () { .buildTransaction(); statusTransaction.applySignature(await alice.signer.sign(statusTransaction.serializeForSigning())); - provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@01"); - let { - bundle: { returnCode: statusReturnCode, values: statusReturnValues, firstValue: statusFirstValue }, - } = await controller.execute(statusInteraction, statusTransaction); + provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@01", "status"); + + hash = await provider.sendTransaction(startTransaction); + response = await controller.awaitCompletedExecute(hash); + console.log({ response }); assert.equal(statusTransaction.getData().toString(), "status@6c75636b79"); - assert.isTrue(statusReturnCode.equals(ReturnCode.Ok)); - assert.lengthOf(statusReturnValues, 1); - assert.deepEqual(statusFirstValue!.valueOf(), { name: "Running", fields: [] }); + assert.isTrue(response.returnCode == "ok"); + assert.isTrue(response.values.length == 1); + assert.deepEqual(response.values[0]!.valueOf(), { name: "Running", fields: [] }); // lotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) let getLotteryInfoTransaction = getLotteryInfoInteraction @@ -401,16 +425,15 @@ describe("test smart contract interactor", function () { ); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult( "@6f6b@0000000b6c75636b792d746f6b656e000000010100000000000000005fc2b9dbffffffff00000001640000000a140ec80fa7ee88000000", + "getLotteryInfo", ); - let { - bundle: { returnCode: infoReturnCode, values: infoReturnValues, firstValue: infoFirstValue }, - } = await controller.execute(getLotteryInfoInteraction, getLotteryInfoTransaction); - + hash = await provider.sendTransaction(startTransaction); + response = await controller.awaitCompletedExecute(hash); assert.equal(getLotteryInfoTransaction.getData().toString(), "getLotteryInfo@6c75636b79"); - assert.isTrue(infoReturnCode.equals(ReturnCode.Ok)); - assert.lengthOf(infoReturnValues, 1); + assert.isTrue(response.returnCode == "ok"); + assert.isTrue(response.values.length == 1); - assert.deepEqual(infoFirstValue!.valueOf(), { + assert.deepEqual(response.values[0]!.valueOf(), { token_identifier: "lucky-token", ticket_price: new BigNumber("1"), tickets_left: new BigNumber(0), diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index 0cca6ae47..d11edf864 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -40,7 +40,7 @@ export class Interaction { private gasLimit: IGasLimit = 0; private gasPrice: IGasPrice | undefined = undefined; private chainID: IChainID = ""; - private querent: IAddress = Address.empty(); + private querent: Address = Address.empty(); private explicitReceiver?: IAddress; private sender: Address = Address.empty(); private version: number = TRANSACTION_VERSION_DEFAULT; @@ -186,7 +186,7 @@ export class Interaction { /** * Sets the "caller" field on contract queries. */ - withQuerent(querent: IAddress): Interaction { + withQuerent(querent: Address): Interaction { this.querent = querent; return this; } diff --git a/src/abi/query.ts b/src/abi/query.ts index 7249ebd6a..f773f9f21 100644 --- a/src/abi/query.ts +++ b/src/abi/query.ts @@ -1,19 +1,19 @@ import { Address } from "../address"; -import { TypedValue } from "./typesystem"; +import { ITransactionValue } from "../interface"; import { ArgSerializer } from "./argSerializer"; -import { IAddress, ITransactionValue } from "../interface"; import { IContractFunction } from "./interface"; +import { TypedValue } from "./typesystem"; export class Query { - caller: IAddress; - address: IAddress; + caller: Address; + address: Address; func: IContractFunction; args: TypedValue[]; value: ITransactionValue; constructor(obj: { - caller?: IAddress; - address: IAddress; + caller?: Address; + address: Address; func: IContractFunction; args?: TypedValue[]; value?: ITransactionValue; diff --git a/src/abi/resultsParser.spec.ts b/src/abi/resultsParser.spec.ts deleted file mode 100644 index 7ce441301..000000000 --- a/src/abi/resultsParser.spec.ts +++ /dev/null @@ -1,371 +0,0 @@ -import BigNumber from "bignumber.js"; -import { assert } from "chai"; -import { Address } from "../address"; -import { ContractQueryResponse } from "../networkProviders"; -import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { SmartContractResult } from "../transactionsOutcomeParsers"; -import { ArgSerializer } from "./argSerializer"; -import { ResultsParser } from "./resultsParser"; -import { ReturnCode } from "./returnCode"; -import { - AbiRegistry, - BigUIntType, - BigUIntValue, - EndpointDefinition, - EndpointModifiers, - EndpointParameterDefinition, - StringType, - StringValue, - TypedValue, - U32Type, - U32Value, - U64Type, - U64Value, - VariadicType, - VariadicValue, -} from "./typesystem"; -import { BytesType, BytesValue } from "./typesystem/bytes"; - -const KnownReturnCodes: string[] = [ - ReturnCode.None.valueOf(), - ReturnCode.Ok.valueOf(), - ReturnCode.FunctionNotFound.valueOf(), - ReturnCode.FunctionWrongSignature.valueOf(), - ReturnCode.ContractNotFound.valueOf(), - ReturnCode.UserError.valueOf(), - ReturnCode.OutOfGas.valueOf(), - ReturnCode.AccountCollision.valueOf(), - ReturnCode.OutOfFunds.valueOf(), - ReturnCode.CallStackOverFlow.valueOf(), - ReturnCode.ContractInvalid.valueOf(), - ReturnCode.ExecutionFailed.valueOf(), - // Returned by protocol, not by VM: - "insufficient funds", - "operation in account not permitted not the owner of the account", - "sending value to non payable contract", - "invalid receiver address", -]; - -describe("test smart contract results parser", () => { - let parser = new ResultsParser(); - - it("should create parser with custom dependencies (1)", async () => { - const customParser = new ResultsParser({ - argsSerializer: { - buffersToValues(_buffers, _parameters) { - return [new U64Value(42)]; - }, - stringToBuffers(_joinedString) { - return []; - }, - }, - }); - - const endpoint = new EndpointDefinition("", [], [], new EndpointModifiers("", [])); - const queryResponse = new ContractQueryResponse({}); - const bundle = customParser.parseQueryResponse(queryResponse, endpoint); - assert.deepEqual(bundle.firstValue, new U64Value(42)); - }); - - it("should create parser with custom dependencies (2)", async () => { - const customParser = new ResultsParser({ - argsSerializer: new ArgSerializer({ - codec: { - decodeTopLevel(_buffer, _type): TypedValue { - return new U64Value(42); - }, - encodeTopLevel(_typedValue): Buffer { - return Buffer.from([]); - }, - }, - }), - }); - - const outputParameters = [new EndpointParameterDefinition("", "", new U64Type())]; - const endpoint = new EndpointDefinition("", [], outputParameters, new EndpointModifiers("", [])); - const queryResponse = new ContractQueryResponse({ returnData: [""] }); - const bundle = customParser.parseQueryResponse(queryResponse, endpoint); - assert.deepEqual(bundle.firstValue, new U64Value(42)); - }); - - it("should parse query response", async () => { - let endpointModifiers = new EndpointModifiers("", []); - let outputParameters = [ - new EndpointParameterDefinition("a", "a", new BigUIntType()), - new EndpointParameterDefinition("b", "b", new BytesType()), - ]; - let endpoint = new EndpointDefinition("foo", [], outputParameters, endpointModifiers); - - let queryResponse = new ContractQueryResponse({ - returnData: [Buffer.from([42]).toString("base64"), Buffer.from("abba", "hex").toString("base64")], - returnCode: "ok", - returnMessage: "foobar", - }); - - let bundle = parser.parseQueryResponse(queryResponse, endpoint); - assert.deepEqual(bundle.returnCode, ReturnCode.Ok); - assert.equal(bundle.returnMessage, "foobar"); - assert.deepEqual(bundle.firstValue, new BigUIntValue(42)); - assert.deepEqual(bundle.secondValue, BytesValue.fromHex("abba")); - assert.lengthOf(bundle.values, 2); - }); - - it("should parse query response (variadic arguments)", async () => { - const endpointModifiers = new EndpointModifiers("", []); - const outputParameters = [new EndpointParameterDefinition("a", "a", new VariadicType(new U32Type(), false))]; - const endpoint = new EndpointDefinition("foo", [], outputParameters, endpointModifiers); - const queryResponse = new ContractQueryResponse({ - returnData: [Buffer.from([42]).toString("base64"), Buffer.from([43]).toString("base64")], - }); - - const bundle = parser.parseQueryResponse(queryResponse, endpoint); - assert.deepEqual(bundle.values[0], VariadicValue.fromItems(new U32Value(42), new U32Value(43))); - }); - - it("should parse query response (one counted-variadic arguments)", async () => { - const endpointModifiers = new EndpointModifiers("", []); - const outputParameters = [new EndpointParameterDefinition("a", "a", new VariadicType(new U32Type(), true))]; - const endpoint = new EndpointDefinition("foo", [], outputParameters, endpointModifiers); - const queryResponse = new ContractQueryResponse({ - returnData: [ - Buffer.from([2]).toString("base64"), - Buffer.from([42]).toString("base64"), - Buffer.from([43]).toString("base64"), - ], - }); - - const bundle = parser.parseQueryResponse(queryResponse, endpoint); - assert.deepEqual(bundle.values[0], VariadicValue.fromItemsCounted(new U32Value(42), new U32Value(43))); - }); - - it("should parse query response (multiple counted-variadic arguments)", async () => { - const endpointModifiers = new EndpointModifiers("", []); - const outputParameters = [ - new EndpointParameterDefinition("a", "a", new VariadicType(new U32Type(), true)), - new EndpointParameterDefinition("b", "b", new VariadicType(new StringType(), true)), - new EndpointParameterDefinition("c", "c", new BigUIntType()), - ]; - const endpoint = new EndpointDefinition("foo", [], outputParameters, endpointModifiers); - const queryResponse = new ContractQueryResponse({ - returnData: [ - Buffer.from([2]).toString("base64"), - Buffer.from([42]).toString("base64"), - Buffer.from([43]).toString("base64"), - Buffer.from([3]).toString("base64"), - Buffer.from("a").toString("base64"), - Buffer.from("b").toString("base64"), - Buffer.from("c").toString("base64"), - Buffer.from([42]).toString("base64"), - ], - }); - - const bundle = parser.parseQueryResponse(queryResponse, endpoint); - assert.deepEqual(bundle.values[0], VariadicValue.fromItemsCounted(new U32Value(42), new U32Value(43))); - assert.deepEqual( - bundle.values[1], - VariadicValue.fromItemsCounted(new StringValue("a"), new StringValue("b"), new StringValue("c")), - ); - assert.deepEqual(bundle.values[2], new BigUIntValue(42)); - }); - - it("should parse contract outcome", async () => { - let endpointModifiers = new EndpointModifiers("", []); - let outputParameters = [ - new EndpointParameterDefinition("a", "a", new BigUIntType()), - new EndpointParameterDefinition("b", "b", new BytesType()), - ]; - let endpoint = new EndpointDefinition("foo", [], outputParameters, endpointModifiers); - - let transactionOnNetwork = new TransactionOnNetwork({ - smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b@2a@abba") })], - }); - - let bundle = parser.parseOutcome(transactionOnNetwork, endpoint); - assert.deepEqual(bundle.returnCode, ReturnCode.Ok); - assert.equal(bundle.returnMessage, "ok"); - assert.deepEqual(bundle.firstValue, new BigUIntValue(42)); - assert.deepEqual(bundle.secondValue, BytesValue.fromHex("abba")); - assert.lengthOf(bundle.values, 2); - }); - - it("should parse contract outcome, on easily found result with return data", async () => { - let transaction = new TransactionOnNetwork({ - smartContractResults: [ - new SmartContractResult({ - data: Buffer.from("@6f6b@03"), - }), - ], - }); - - let bundle = parser.parseUntypedOutcome(transaction); - assert.deepEqual(bundle.returnCode, ReturnCode.Ok); - assert.deepEqual(bundle.values, [Buffer.from("03", "hex")]); - }); - - it("should parse contract outcome, on signal error", async () => { - let transaction = new TransactionOnNetwork({ - logs: new TransactionLogs({ - address: Address.empty(), - events: [ - new TransactionEvent({ - identifier: "signalError", - topics: [Buffer.from("something happened")], - data: Buffer.from("QDc1NzM2NTcyMjA2NTcyNzI2ZjcyQDA3", "base64"), - }), - ], - }), - }); - - let bundle = parser.parseUntypedOutcome(transaction); - assert.deepEqual(bundle.returnCode, ReturnCode.UserError); - assert.equal(bundle.returnMessage, "something happened"); - assert.deepEqual(bundle.values, [Buffer.from("07", "hex")]); - }); - - it("should parse contract outcome, on too much gas warning", async () => { - let transaction = new TransactionOnNetwork({ - logs: new TransactionLogs({ - address: Address.empty(), - events: [ - new TransactionEvent({ - identifier: "writeLog", - topics: [ - Buffer.from( - "QHRvbyBtdWNoIGdhcyBwcm92aWRlZCBmb3IgcHJvY2Vzc2luZzogZ2FzIHByb3ZpZGVkID0gNTk2Mzg0NTAwLCBnYXMgdXNlZCA9IDczMzAxMA==", - "base64", - ), - ], - data: Buffer.from("QDZmNmI=", "base64"), - }), - ], - }), - }); - - let bundle = parser.parseUntypedOutcome(transaction); - assert.deepEqual(bundle.returnCode, ReturnCode.Ok); - assert.equal(bundle.returnMessage, "ok"); - assert.deepEqual(bundle.values, []); - }); - - it("should parse contract event", async () => { - const abiRegistry = await loadAbiRegistry("src/testdata/esdt-safe.abi.json"); - const eventDefinition = abiRegistry.getEvent("deposit"); - - const event = new TransactionEvent({ - topics: [ - Buffer.from("ZGVwb3NpdA==", "base64"), - Buffer.from("cmzC1LRt1r10pMhNAnFb+FyudjGMq4G8CefCYdQUmmc=", "base64"), - Buffer.from("AAAADFdFR0xELTAxZTQ5ZAAAAAAAAAAAAAAAAWQ=", "base64"), - ], - data: Buffer.from("AAAAAAAAA9sAAAA=", "base64"), - }); - - const bundle = parser.parseEvent(event, eventDefinition); - - assert.equal( - (
bundle.dest_address).bech32(), - "erd1wfkv9495dhtt6a9yepxsyu2mlpw2ua333j4cr0qfulpxr4q5nfnshgyqun", - ); - assert.equal(bundle.tokens[0].token_identifier, "WEGLD-01e49d"); - assert.deepEqual(bundle.tokens[0].token_nonce, new BigNumber(0)); - assert.deepEqual(bundle.tokens[0].amount, new BigNumber(100)); - assert.deepEqual(bundle.event_data.tx_nonce, new BigNumber(987)); - assert.isNull(bundle.event_data.opt_function); - assert.isNull(bundle.event_data.opt_arguments); - assert.isNull(bundle.event_data.opt_gas_limit); - }); - - it("should parse contract event (with multi-values)", async () => { - const abiRegistry = AbiRegistry.create({ - events: [ - { - identifier: "foobar", - inputs: [ - { - name: "a", - type: "multi", - indexed: true, - }, - { - name: "b", - type: "multi", - indexed: true, - }, - { - name: "c", - type: "u8", - indexed: false, - }, - ], - }, - ], - }); - - const eventDefinition = abiRegistry.getEvent("foobar"); - - const event = new TransactionEvent({ - topics: b64TopicsToBytes([ - Buffer.from("not used").toString("base64"), - Buffer.from([42]).toString("base64"), - Buffer.from("test").toString("base64"), - Buffer.from([43]).toString("base64"), - Buffer.from("test").toString("base64"), - Buffer.from("test").toString("base64"), - Buffer.from([44]).toString("base64"), - ]), - data: Buffer.from([42]), - }); - - const bundle = parser.parseEvent(event, eventDefinition); - assert.deepEqual(bundle.a, [new BigNumber(42), "test", new BigNumber(43), "test"]); - assert.deepEqual(bundle.b, ["test", new BigNumber(44)]); - assert.deepEqual(bundle.c, new BigNumber(42)); - }); - - it("should parse contract event (Sirius)", async () => { - const abiRegistry = AbiRegistry.create({ - events: [ - { - identifier: "foobar", - inputs: [ - { - name: "a", - type: "u8", - indexed: true, - }, - { - name: "b", - type: "u8", - indexed: false, - }, - { - name: "c", - type: "u8", - indexed: false, - }, - ], - }, - ], - }); - - const eventDefinition = abiRegistry.getEvent("foobar"); - - const event = new TransactionEvent({ - topics: b64TopicsToBytes([ - Buffer.from("not used").toString("base64"), - Buffer.from([42]).toString("base64"), - ]), - additionalData: [Buffer.from([43]), Buffer.from([44])], - // Will be ignored. - data: new Uint8Array(Buffer.from([43])), - }); - - const bundle = parser.parseEvent(event, eventDefinition); - assert.deepEqual(bundle.a, new BigNumber(42)); - assert.deepEqual(bundle.b, new BigNumber(43)); - assert.deepEqual(bundle.c, new BigNumber(44)); - }); -}); diff --git a/src/abi/resultsParser.ts b/src/abi/resultsParser.ts deleted file mode 100644 index fda7147ac..000000000 --- a/src/abi/resultsParser.ts +++ /dev/null @@ -1,435 +0,0 @@ -import { - TransactionDecoder, - TransactionMetadata, -} from "@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder"; -import { Address } from "../address"; -import { ErrCannotParseContractResults } from "../errors"; -import { IContractQueryResponse } from "../interfaceOfNetwork"; -import { Logger } from "../logger"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { SmartContractResult } from "../transactionsOutcomeParsers"; -import { ArgSerializer } from "./argSerializer"; -import { TypedOutcomeBundle, UntypedOutcomeBundle } from "./interface"; -import { ReturnCode } from "./returnCode"; -import { Type, TypedValue } from "./typesystem"; - -enum WellKnownEvents { - OnTransactionCompleted = "completedTxEvent", - OnSignalError = "signalError", - OnWriteLog = "writeLog", -} - -enum WellKnownTopics { - TooMuchGas = "@too much gas provided for processing", -} - -interface IResultsParserOptions { - argsSerializer: IArgsSerializer; -} - -interface IParameterDefinition { - type: Type; -} - -interface IEventInputDefinition { - name: string; - type: Type; - indexed: boolean; -} - -interface IArgsSerializer { - buffersToValues(buffers: Buffer[], parameters: IParameterDefinition[]): TypedValue[]; - stringToBuffers(joinedString: string): Buffer[]; -} - -// TODO: perhaps move default construction options to a factory (ResultsParserFactory), instead of referencing them in the constructor -// (postpone as much as possible, breaking change) -const defaultResultsParserOptions: IResultsParserOptions = { - argsSerializer: new ArgSerializer(), -}; - -/** - * Legacy component. - * For parsing contract query responses, use the "SmartContractQueriesController" instead. - * For parsing smart contract outcome (return data), use the "SmartContractTransactionsOutcomeParser" instead. - * For parding smart contract events, use the "TransactionEventsParser" instead. - * - * Parses contract query responses and smart contract results. - * The parsing involves some heuristics, in order to handle slight inconsistencies (e.g. some SCRs are present on API, but missing on Gateway). - */ -export class ResultsParser { - private readonly argsSerializer: IArgsSerializer; - - constructor(options?: IResultsParserOptions) { - options = { ...defaultResultsParserOptions, ...options }; - this.argsSerializer = options.argsSerializer; - } - - /** - * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. - */ - parseQueryResponse( - queryResponse: IContractQueryResponse, - endpoint: { output: IParameterDefinition[] }, - ): TypedOutcomeBundle { - let parts = queryResponse.getReturnDataParts(); - let values = this.argsSerializer.buffersToValues(parts, endpoint.output); - let returnCode = new ReturnCode(queryResponse.returnCode.toString()); - - return { - returnCode: returnCode, - returnMessage: queryResponse.returnMessage, - values: values, - firstValue: values[0], - secondValue: values[1], - thirdValue: values[2], - lastValue: values[values.length - 1], - }; - } - - /** - * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. - */ - parseUntypedQueryResponse(queryResponse: IContractQueryResponse): UntypedOutcomeBundle { - let returnCode = new ReturnCode(queryResponse.returnCode.toString()); - - return { - returnCode: returnCode, - returnMessage: queryResponse.returnMessage, - values: queryResponse.getReturnDataParts(), - }; - } - - /** - * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. - */ - parseOutcome(transaction: TransactionOnNetwork, endpoint: { output: IParameterDefinition[] }): TypedOutcomeBundle { - const untypedBundle = this.parseUntypedOutcome(transaction); - const typedBundle = this.parseOutcomeFromUntypedBundle(untypedBundle, endpoint); - return typedBundle; - } - - /** - * @internal - * For internal use only. - */ - parseOutcomeFromUntypedBundle(bundle: UntypedOutcomeBundle, endpoint: { output: IParameterDefinition[] }) { - const values = this.argsSerializer.buffersToValues(bundle.values, endpoint.output); - - return { - returnCode: bundle.returnCode, - returnMessage: bundle.returnMessage, - values: values, - firstValue: values[0], - secondValue: values[1], - thirdValue: values[2], - lastValue: values[values.length - 1], - }; - } - - /** - * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. - */ - parseUntypedOutcome(transaction: TransactionOnNetwork): UntypedOutcomeBundle { - let bundle: UntypedOutcomeBundle | null; - - let transactionMetadata = this.parseTransactionMetadata(transaction); - - bundle = this.createBundleOnSimpleMoveBalance(transaction); - if (bundle) { - Logger.trace("parseUntypedOutcome(): on simple move balance"); - return bundle; - } - - if (bundle) { - Logger.trace("parseUntypedOutcome(): on invalid transaction"); - return bundle; - } - - bundle = this.createBundleOnEasilyFoundResultWithReturnData(transaction.smartContractResults); - if (bundle) { - Logger.trace("parseUntypedOutcome(): on easily found result with return data"); - return bundle; - } - - bundle = this.createBundleOnSignalError(transaction.logs); - if (bundle) { - Logger.trace("parseUntypedOutcome(): on signal error"); - return bundle; - } - - bundle = this.createBundleOnTooMuchGasWarning(transaction.logs); - if (bundle) { - Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"); - return bundle; - } - - bundle = this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(transaction.logs, transaction.sender); - if (bundle) { - Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"); - return bundle; - } - - bundle = this.createBundleWithCustomHeuristics(transaction, transactionMetadata); - if (bundle) { - Logger.trace("parseUntypedOutcome(): with custom heuristics"); - return bundle; - } - - bundle = this.createBundleWithFallbackHeuristics(transaction, transactionMetadata); - if (bundle) { - Logger.trace("parseUntypedOutcome(): with fallback heuristics"); - return bundle; - } - - throw new ErrCannotParseContractResults(`transaction ${transaction.hash.toString()}`); - } - - protected parseTransactionMetadata(transaction: TransactionOnNetwork): TransactionMetadata { - return new TransactionDecoder().getTransactionMetadata({ - sender: transaction.sender.bech32(), - receiver: transaction.receiver.bech32(), - data: transaction.data.toString("base64"), - value: transaction.value.toString(), - }); - } - - protected createBundleOnSimpleMoveBalance(transaction: TransactionOnNetwork): UntypedOutcomeBundle | null { - let noResults = transaction.smartContractResults.length == 0; - let noLogs = transaction.logs.events.length == 0; - - if (noResults && noLogs) { - return { - returnCode: ReturnCode.None, - returnMessage: ReturnCode.None.toString(), - values: [], - }; - } - - return null; - } - - protected createBundleOnEasilyFoundResultWithReturnData( - results: SmartContractResult[], - ): UntypedOutcomeBundle | null { - let resultItemWithReturnData = results.find((item) => item.data.toString().startsWith("@")); - if (!resultItemWithReturnData) { - return null; - } - - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(resultItemWithReturnData.data.toString()); - let returnMessage = resultItemWithReturnData.raw["prevTxHash"] || returnCode.toString(); - - return { - returnCode: returnCode, - returnMessage: returnMessage, - values: returnDataParts, - }; - } - - protected createBundleOnSignalError(logs: TransactionLogs): UntypedOutcomeBundle | null { - let eventSignalError = logs.findSingleOrNoneEvent(WellKnownEvents.OnSignalError); - if (!eventSignalError) { - return null; - } - - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(Buffer.from(eventSignalError.data).toString()); - let lastTopic = eventSignalError.getLastTopic(); - let returnMessage = lastTopic?.toString() || returnCode.toString(); - - return { - returnCode: returnCode, - returnMessage: returnMessage, - values: returnDataParts, - }; - } - - protected createBundleOnTooMuchGasWarning(logs: TransactionLogs): UntypedOutcomeBundle | null { - let eventTooMuchGas = logs.findSingleOrNoneEvent( - WellKnownEvents.OnWriteLog, - (event) => - event.findFirstOrNoneTopic((topic) => topic.toString().startsWith(WellKnownTopics.TooMuchGas)) != - undefined, - ); - - if (!eventTooMuchGas) { - return null; - } - - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventTooMuchGas.data.toString()); - - return { - returnCode: returnCode, - returnMessage: returnCode.toString(), - values: returnDataParts, - }; - } - - protected createBundleOnWriteLogWhereFirstTopicEqualsAddress( - logs: TransactionLogs, - address: Address, - ): UntypedOutcomeBundle | null { - let hexAddress = new Address(address.bech32()).hex(); - - let eventWriteLogWhereTopicIsSender = logs.findSingleOrNoneEvent( - WellKnownEvents.OnWriteLog, - (event) => event.findFirstOrNoneTopic((topic) => topic.toString() == hexAddress) != undefined, - ); - - if (!eventWriteLogWhereTopicIsSender) { - return null; - } - - let { returnCode, returnDataParts } = this.sliceDataFieldInParts( - eventWriteLogWhereTopicIsSender.data.toString(), - ); - let returnMessage = returnCode.toString(); - - return { - returnCode: returnCode, - returnMessage: returnMessage, - values: returnDataParts, - }; - } - - /** - * Override this method (in a subclass of {@link ResultsParser}) if the basic heuristics of the parser are not sufficient. - */ - protected createBundleWithCustomHeuristics( - _transaction: TransactionOnNetwork, - _transactionMetadata: TransactionMetadata, - ): UntypedOutcomeBundle | null { - return null; - } - - protected createBundleWithFallbackHeuristics( - transaction: TransactionOnNetwork, - transactionMetadata: TransactionMetadata, - ): UntypedOutcomeBundle | null { - let contractAddress = new Address(transactionMetadata.receiver); - - // Search the nested logs for matching events (writeLog): - for (const resultItem of transaction.smartContractResults) { - let writeLogWithReturnData = resultItem.logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => { - let addressIsSender = event.address.bech32() == transaction.sender.bech32(); - let firstTopicIsContract = event.topics[0].toString() == contractAddress.hex(); - return addressIsSender && firstTopicIsContract; - }); - - if (writeLogWithReturnData) { - let { returnCode, returnDataParts } = this.sliceDataFieldInParts( - writeLogWithReturnData.data.toString(), - ); - let returnMessage = returnCode.toString(); - - return { - returnCode: returnCode, - returnMessage: returnMessage, - values: returnDataParts, - }; - } - } - - // Additional fallback heuristics (alter search constraints): - for (const resultItem of transaction.smartContractResults) { - let writeLogWithReturnData = resultItem.logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => { - const addressIsContract = event.address.bech32() == contractAddress.toBech32(); - return addressIsContract; - }); - - if (writeLogWithReturnData) { - const { returnCode, returnDataParts } = this.sliceDataFieldInParts( - writeLogWithReturnData.data.toString(), - ); - const returnMessage = returnCode.toString(); - - return { - returnCode: returnCode, - returnMessage: returnMessage, - values: returnDataParts, - }; - } - } - - return null; - } - - protected sliceDataFieldInParts(data: string): { returnCode: ReturnCode; returnDataParts: Buffer[] } { - // By default, skip the first part, which is usually empty (e.g. "[empty]@6f6b") - let startingIndex = 1; - - // Before trying to parse the hex strings, cut the unwanted parts of the data field, in case of token transfers: - if (data.startsWith("ESDTTransfer")) { - // Skip "ESDTTransfer" (1), token identifier (2), amount (3) - startingIndex = 3; - } else { - // TODO: Upon gathering more transaction samples, fix for other kinds of transfers, as well (future PR, as needed). - } - - let parts = this.argsSerializer.stringToBuffers(data); - let returnCodePart = parts[startingIndex] || Buffer.from([]); - let returnDataParts = parts.slice(startingIndex + 1); - - if (returnCodePart.length == 0) { - throw new ErrCannotParseContractResults("no return code"); - } - - let returnCode = ReturnCode.fromBuffer(returnCodePart); - return { returnCode, returnDataParts }; - } - - /** - * Legacy method, use "TransactionEventsParser.parseEvent()" instead. - */ - parseEvent(transactionEvent: TransactionEvent, eventDefinition: { inputs: IEventInputDefinition[] }): any { - // We skip the first topic, because, for log entries emitted by smart contracts, that's the same as the event identifier. See: - // https://github.com/multiversx/mx-chain-vm-go/blob/v1.5.27/vmhost/contexts/output.go#L283 - const topics = transactionEvent.topics.map((topic) => Buffer.from(topic.valueOf())).slice(1); - - // Before Sirius, there was no "additionalData" field on transaction logs. - // After Sirius, the "additionalData" field includes the "data" field, as well (as the first element): - // https://github.com/multiversx/mx-chain-go/blob/v1.6.18/process/transactionLog/process.go#L159 - // Right now, the logic below is duplicated (see "TransactionsConverter"). However, "ResultsParser" will be deprecated & removed at a later time. - const legacyData = transactionEvent.data?.valueOf() || Buffer.from([]); - const dataItems = transactionEvent.additionalData?.map((data) => Buffer.from(data)) || []; - if (dataItems.length === 0) { - if (legacyData.length) { - dataItems.push(Buffer.from(legacyData)); - } - } - - return this.doParseEvent({ topics, dataItems, eventDefinition }); - } - - /** - * @internal - * For internal use only. - * - * Once the legacy "ResultParser" is deprecated & removed, this logic will be absorbed into "TransactionEventsParser". - */ - doParseEvent(options: { - topics: Buffer[]; - dataItems: Buffer[]; - eventDefinition: { inputs: IEventInputDefinition[] }; - }): any { - const result: any = {}; - - // "Indexed" ABI "event.inputs" correspond to "event.topics[1:]": - const indexedInputs = options.eventDefinition.inputs.filter((input) => input.indexed); - const decodedTopics = this.argsSerializer.buffersToValues(options.topics, indexedInputs); - for (let i = 0; i < indexedInputs.length; i++) { - result[indexedInputs[i].name] = decodedTopics[i].valueOf(); - } - - // "Non-indexed" ABI "event.inputs" correspond to "event.data": - const nonIndexedInputs = options.eventDefinition.inputs.filter((input) => !input.indexed); - const decodedDataParts = this.argsSerializer.buffersToValues(options.dataItems, nonIndexedInputs); - for (let i = 0; i < nonIndexedInputs.length; i++) { - result[nonIndexedInputs[i].name] = decodedDataParts[i]?.valueOf(); - } - - return result; - } -} diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 9266c0eae..a726357e4 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -12,7 +12,6 @@ import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { decodeUnsignedNumber } from "./codec"; import { ContractFunction } from "./function"; -import { ResultsParser } from "./resultsParser"; import { SmartContract } from "./smartContract"; import { AddressValue, @@ -28,7 +27,6 @@ describe("test on local testnet", function () { let alice: TestWallet, bob: TestWallet, carol: TestWallet; let provider = createLocalnetProvider(); let watcher: TransactionWatcher; - let resultsParser = new ResultsParser(); before(async function () { ({ alice, bob, carol } = await loadTestWallets()); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index f9e5c1005..8ea0481aa 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -7,7 +7,6 @@ import { TransactionComputer } from "../transactionComputer"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { ContractFunction } from "./function"; -import { ResultsParser } from "./resultsParser"; import { SmartContract } from "./smartContract"; describe("fetch transactions from local testnet", function () { @@ -15,8 +14,6 @@ describe("fetch transactions from local testnet", function () { let provider = createLocalnetProvider(); let watcher: TransactionWatcher; - let resultsParser = new ResultsParser(); - before(async function () { ({ alice } = await loadTestWallets()); watcher = new TransactionWatcher({ diff --git a/src/adapters/queryRunnerAdapter.ts b/src/adapters/queryRunnerAdapter.ts index db673de4c..decb29385 100644 --- a/src/adapters/queryRunnerAdapter.ts +++ b/src/adapters/queryRunnerAdapter.ts @@ -1,4 +1,3 @@ -import { Address } from "../address"; import { IAddress } from "../interface"; import { IContractQueryResponse } from "../interfaceOfNetwork"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; @@ -24,8 +23,8 @@ export class QueryRunnerAdapter { async runQuery(query: SmartContractQuery): Promise { const adaptedQuery: IQuery = { - address: Address.fromBech32(query.contract), - caller: query.caller ? Address.fromBech32(query.caller) : undefined, + address: query.contract, + caller: query.caller ? query.caller : undefined, func: query.function, value: query.value, getEncodedArguments: () => query.arguments.map((arg) => Buffer.from(arg).toString("hex")), diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 42b2241e6..f0a850398 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -79,7 +79,7 @@ describe("TestEntrypoint", () => { const txHashExecute = await entrypoint.sendTransaction(executeTransaction); await entrypoint.awaitCompletedTransaction(txHashExecute); - const queryResult = await controller.queryContract(contractAddress, "getSum", []); + const queryResult = await controller.query({ contract: contractAddress, function: "getSum", arguments: [] }); assert.equal(queryResult.length, 1); assert.equal(queryResult[0], 7); }); diff --git a/src/index.ts b/src/index.ts index 88e182683..a642376a9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,7 +28,6 @@ export * from "./relayed"; export * from "./relayedTransactionV1Builder"; export * from "./relayedTransactionV2Builder"; export * from "./signableMessage"; -export * from "./smartContractQueriesController"; export * from "./tokenManagement"; export * from "./tokens"; export * from "./transaction"; diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 807f1640e..3891ca47a 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,4 +1,5 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; +import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; @@ -7,8 +8,7 @@ import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig, defaultPagination } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; -import { ContractQueryResponse } from "./contractQueryResponse"; -import { IAddress, IContractQuery, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "./interface"; +import { IAddress, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; @@ -160,11 +160,11 @@ export class ApiNetworkProvider implements INetworkProvider { return await this.backingProxyNetworkProvider.simulateTransaction(tx); } - async queryContract(query: IContractQuery): Promise { + async queryContract(query: SmartContractQuery): Promise { try { const request = new ContractQueryRequest(query).toHttpRequest(); const response = await this.doPostGeneric("query", request); - return ContractQueryResponse.fromHttpResponse(response); + return SmartContractQueryResponse.fromHttpResponse(response, query.function); } catch (error: any) { throw new ErrContractQuery(error); } diff --git a/src/networkProviders/contractQueryRequest.ts b/src/networkProviders/contractQueryRequest.ts index d64183c9a..d09c01770 100644 --- a/src/networkProviders/contractQueryRequest.ts +++ b/src/networkProviders/contractQueryRequest.ts @@ -1,21 +1,21 @@ -import { IContractQuery } from "./interface"; +import { SmartContractQuery } from "../smartContractQuery"; export class ContractQueryRequest { - private readonly query: IContractQuery; + private readonly query: SmartContractQuery; - constructor(query: IContractQuery) { + constructor(query: SmartContractQuery) { this.query = query; } toHttpRequest() { let request: any = {}; let query = this.query; - request.scAddress = query.address.bech32(); - request.caller = query.caller?.bech32() ? query.caller.bech32() : undefined; - request.funcName = query.func.toString(); + request.scAddress = query.contract.toBech32(); + request.caller = query.caller?.toBech32() ? query.caller.toBech32() : undefined; + request.funcName = query.function; request.value = query.value ? query.value.toString() : undefined; - request.args = query.getEncodedArguments(); - + request.args = query.arguments?.map((x) => Buffer.from(x).toString("hex")); + console.log({ request }); return request; } } diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index b2045ecbc..f1f3a1cf4 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,8 +1,8 @@ import { ITransaction as ITransactionAsInSpecs } from "../interface"; +import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { AccountOnNetwork } from "./accounts"; -import { ContractQueryResponse } from "./contractQueryResponse"; import { NetworkConfig } from "./networkConfig"; import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkStake } from "./networkStake"; @@ -95,7 +95,7 @@ export interface INetworkProvider { /** * Queries a Smart Contract - runs a pure function defined by the contract and returns its results. */ - queryContract(query: IContractQuery): Promise; + queryContract(query: SmartContractQuery): Promise; /** * Fetches the definition of a fungible token. diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 0e24a89bf..d1c121e2a 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -1,7 +1,7 @@ import { AxiosHeaders } from "axios"; import { assert } from "chai"; import { Address } from "../address"; -import { MockQuery } from "../testutils/dummyQuery"; +import { SmartContractQuery } from "../smartContractQuery"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { ApiNetworkProvider } from "./apiNetworkProvider"; import { INetworkProvider, ITransactionNext } from "./interface"; @@ -379,20 +379,16 @@ describe("test network providers on devnet: Proxy and API", function () { this.timeout(10000); // Query: get sum (of adder contract) - let query = new MockQuery({ - address: new Address("erd1qqqqqqqqqqqqqpgqfzydqmdw7m2vazsp6u5p95yxz76t2p9rd8ss0zp9ts"), - func: "getSum", + let query = new SmartContractQuery({ + contract: new Address("erd1qqqqqqqqqqqqqpgqfzydqmdw7m2vazsp6u5p95yxz76t2p9rd8ss0zp9ts"), + function: "getSum", }); let apiResponse = await apiProvider.queryContract(query); let proxyResponse = await proxyProvider.queryContract(query); - // Ignore "gasUsed" due to numerical imprecision (API). - apiResponse.gasUsed = 0; - proxyResponse.gasUsed = 0; - assert.deepEqual(apiResponse, proxyResponse); - assert.deepEqual(apiResponse.getReturnDataParts(), proxyResponse.getReturnDataParts()); + assert.deepEqual(apiResponse.returnDataParts, proxyResponse.returnDataParts); }); it("should handle events 'data' and 'additionalData'", async function () { diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index a9989b62b..379af63e8 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,4 +1,5 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; +import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; @@ -6,8 +7,7 @@ import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; import { BaseUserAgent, EsdtContractAddress } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; -import { ContractQueryResponse } from "./contractQueryResponse"; -import { IAddress, IContractQuery, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "./interface"; +import { IAddress, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; @@ -159,11 +159,12 @@ export class ProxyNetworkProvider implements INetworkProvider { return response; } - async queryContract(query: IContractQuery): Promise { + async queryContract(query: SmartContractQuery): Promise { try { const request = new ContractQueryRequest(query).toHttpRequest(); const response = await this.doPostGeneric("vm-values/query", request); - return ContractQueryResponse.fromHttpResponse(response.data); + console.log(111111, { response }); + return SmartContractQueryResponse.fromHttpResponse(response, query.function); } catch (error: any) { throw new ErrContractQuery(error); } @@ -179,16 +180,16 @@ export class ProxyNetworkProvider implements INetworkProvider { } private async getTokenProperties(identifier: string): Promise { - const encodedIdentifier = Buffer.from(identifier).toString("hex"); + const encodedIdentifier = Buffer.from(identifier); const queryResponse = await this.queryContract({ - address: EsdtContractAddress, - func: "getTokenProperties", - getEncodedArguments: () => [encodedIdentifier], + contract: EsdtContractAddress, + function: "getTokenProperties", + arguments: [new Uint8Array(encodedIdentifier)], }); - const properties = queryResponse.getReturnDataParts(); - return properties; + const properties = queryResponse.returnDataParts; + return properties?.map((prop) => Buffer.from(prop)); } async getDefinitionOfTokenCollection(collection: string): Promise { diff --git a/src/smartContractQueriesController.ts b/src/smartContractQueriesController.ts deleted file mode 100644 index aee47a980..000000000 --- a/src/smartContractQueriesController.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { ArgSerializer, ContractFunction, EndpointDefinition, isTyped, NativeSerializer, ResultsParser } from "./abi"; -import { Err, ErrSmartContractQuery } from "./errors"; -import { IContractQueryResponse } from "./interfaceOfNetwork"; -import { SmartContractQuery, SmartContractQueryResponse } from "./smartContractQuery"; - -interface IAbi { - getEndpoint(name: string | ContractFunction): EndpointDefinition; -} - -interface IQueryRunner { - runQuery(query: SmartContractQuery): Promise; -} - -export class SmartContractQueriesController { - private readonly abi?: IAbi; - private readonly queryRunner: IQueryRunner; - private readonly legacyResultsParser: ResultsParser; - - constructor(options: { abi?: IAbi; queryRunner: IQueryRunner }) { - this.abi = options.abi; - this.queryRunner = options.queryRunner; - this.legacyResultsParser = new ResultsParser(); - } - - async query(options: { - contract: string; - caller?: string; - value?: bigint; - function: string; - arguments: any[]; - }): Promise { - const query = this.createQuery(options); - const queryResponse = await this.runQuery(query); - this.raiseForStatus(queryResponse); - return this.parseQueryResponse(queryResponse); - } - - private raiseForStatus(queryResponse: SmartContractQueryResponse): void { - const isOk = queryResponse.returnCode === "ok"; - if (!isOk) { - throw new ErrSmartContractQuery(queryResponse.returnCode, queryResponse.returnMessage); - } - } - - createQuery(options: { - contract: string; - caller?: string; - value?: bigint; - function: string; - arguments: any[]; - }): SmartContractQuery { - const preparedArguments = this.encodeArguments(options.function, options.arguments); - - return new SmartContractQuery({ - contract: options.contract, - caller: options.caller, - function: options.function, - arguments: preparedArguments, - value: options.value, - }); - } - - private encodeArguments(functionName: string, args: any[]): Uint8Array[] { - const endpoint = this.abi?.getEndpoint(functionName); - - if (endpoint) { - const typedArgs = NativeSerializer.nativeToTypedValues(args, endpoint); - return new ArgSerializer().valuesToBuffers(typedArgs); - } - - if (this.areArgsOfTypedValue(args)) { - return new ArgSerializer().valuesToBuffers(args); - } - - if (this.areArgsBuffers(args)) { - return args.map((arg) => Buffer.from(arg)); - } - - throw new Err( - "cannot encode arguments: when ABI is not available, they must be either typed values or buffers", - ); - } - - private areArgsOfTypedValue(args: any[]): boolean { - return args.every((arg) => isTyped(arg)); - } - - private areArgsBuffers(args: any[]): boolean { - for (const arg of args) { - if (!ArrayBuffer.isView(arg)) { - return false; - } - } - - return true; - } - - async runQuery(query: SmartContractQuery): Promise { - const queryResponse = await this.queryRunner.runQuery(query); - return queryResponse; - } - - parseQueryResponse(response: SmartContractQueryResponse): any[] { - if (!this.abi) { - return response.returnDataParts; - } - - const legacyQueryResponse: IContractQueryResponse = { - returnCode: response.returnCode, - returnMessage: response.returnMessage, - getReturnDataParts: () => response.returnDataParts.map((part) => Buffer.from(part)), - }; - - const functionName = response.function; - const endpoint = this.abi.getEndpoint(functionName); - const legacyBundle = this.legacyResultsParser.parseQueryResponse(legacyQueryResponse, endpoint); - const nativeValues = legacyBundle.values.map((value) => value.valueOf()); - return nativeValues; - } -} diff --git a/src/smartContractQuery.ts b/src/smartContractQuery.ts index 275d16bc8..e2eea4836 100644 --- a/src/smartContractQuery.ts +++ b/src/smartContractQuery.ts @@ -1,16 +1,18 @@ +import { Address } from "./address"; + export class SmartContractQuery { - contract: string; - caller?: string; + contract: Address; + caller?: Address; value?: bigint; function: string; - arguments: Uint8Array[]; + arguments?: Uint8Array[]; constructor(options: { - contract: string; - caller?: string; + contract: Address; + caller?: Address; value?: bigint; function: string; - arguments: Uint8Array[]; + arguments?: Uint8Array[]; }) { this.contract = options.contract; this.caller = options.caller; @@ -20,6 +22,22 @@ export class SmartContractQuery { } } +export class SmartContractQueryInput { + contract: Address; + caller?: Address; + value?: bigint; + function: string; + arguments: any[]; + + constructor(options: { contract: Address; caller?: Address; value?: bigint; function: string; arguments: any[] }) { + this.contract = options.contract; + this.caller = options.caller; + this.value = options.value; + this.function = options.function; + this.arguments = options.arguments; + } +} + export class SmartContractQueryResponse { function: string; returnCode: string; @@ -32,4 +50,17 @@ export class SmartContractQueryResponse { this.returnMessage = obj.returnMessage; this.returnDataParts = obj.returnDataParts; } + + static fromHttpResponse(payload: any, functionName: string): SmartContractQueryResponse { + let returnData = payload["returnData"] || payload["ReturnData"]; + let returnCode = payload["returnCode"] || payload["ReturnCode"]; + let returnMessage = payload["returnMessage"] || payload["ReturnMessage"]; + + return new SmartContractQueryResponse({ + returnDataParts: returnData?.map((item) => Buffer.from(item || "", "base64")), + returnCode: returnCode, + returnMessage: returnMessage, + function: functionName, + }); + } } diff --git a/src/smartContracts/resources.ts b/src/smartContracts/resources.ts index 78285aad8..71b1f5c60 100644 --- a/src/smartContracts/resources.ts +++ b/src/smartContracts/resources.ts @@ -28,6 +28,11 @@ export interface SmartContractDeployOutcome { returnMessage: string; contracts: DeployedSmartContract[]; } +export type ParsedSmartContractCallOutcome = { + values: any[]; + returnCode: string; + returnMessage: string; +}; export class DeployedSmartContract { address: string; diff --git a/src/smartContractQueriesController.spec.ts b/src/smartContracts/smartContractController.spec.ts similarity index 67% rename from src/smartContractQueriesController.spec.ts rename to src/smartContracts/smartContractController.spec.ts index 63c7887a1..679e124ee 100644 --- a/src/smartContractQueriesController.spec.ts +++ b/src/smartContracts/smartContractController.spec.ts @@ -1,58 +1,57 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { AbiRegistry, BigUIntValue, BooleanValue, BytesValue, Tuple, U16Value, U64Value } from "./abi"; -import { QueryRunnerAdapter } from "./adapters/queryRunnerAdapter"; -import { ContractQueryResponse } from "./networkProviders"; -import { SmartContractQueriesController } from "./smartContractQueriesController"; -import { SmartContractQueryResponse } from "./smartContractQuery"; -import { MockNetworkProvider, loadAbiRegistry } from "./testutils"; -import { bigIntToBuffer } from "./tokenOperations/codec"; +import { AbiRegistry, BigUIntValue, BooleanValue, BytesValue, Tuple, U16Value, U64Value } from "../abi"; +import { Address } from "../address"; +import { SmartContractQueryResponse } from "../smartContractQuery"; +import { MockNetworkProvider, loadAbiRegistry } from "../testutils"; +import { bigIntToBuffer } from "../tokenOperations/codec"; +import { SmartContractController } from "./smartContractController"; describe("test smart contract queries controller", () => { describe("createQuery", () => { it("works without ABI, when arguments are buffers", function () { - const adapter = new QueryRunnerAdapter({ networkProvider: new MockNetworkProvider() }); - const controller = new SmartContractQueriesController({ - queryRunner: adapter, + const controller = new SmartContractController({ + chainID: this.chainId, + networkProvider: this.networkProvider, }); const query = controller.createQuery({ - contract: "erd1foo", + contract: Address.empty(), function: "bar", arguments: [bigIntToBuffer(42), Buffer.from("abba")], }); - assert.equal(query.contract, "erd1foo"); + assert.deepEqual(query.contract, Address.empty()); assert.equal(query.function, "bar"); assert.deepEqual(query.arguments, [bigIntToBuffer(42), Buffer.from("abba")]); }); it("works without ABI, when arguments are typed values", function () { - const adapter = new QueryRunnerAdapter({ networkProvider: new MockNetworkProvider() }); - const controller = new SmartContractQueriesController({ - queryRunner: adapter, + const controller = new SmartContractController({ + chainID: this.chainId, + networkProvider: this.networkProvider, }); const query = controller.createQuery({ - contract: "erd1foo", + contract: Address.empty(), function: "bar", arguments: [new BigUIntValue(42), BytesValue.fromUTF8("abba")], }); - assert.equal(query.contract, "erd1foo"); + assert.deepEqual(query.contract, Address.empty()); assert.equal(query.function, "bar"); assert.deepEqual(query.arguments, [bigIntToBuffer(42), Buffer.from("abba")]); }); it("fails without ABI, when arguments aren't buffers, nor typed values", function () { - const adapter = new QueryRunnerAdapter({ networkProvider: new MockNetworkProvider() }); - const controller = new SmartContractQueriesController({ - queryRunner: adapter, + const controller = new SmartContractController({ + chainID: this.chainId, + networkProvider: this.networkProvider, }); assert.throws(() => { controller.createQuery({ - contract: "erd1foo", + contract: Address.empty(), function: "bar", arguments: [42, "abba"], }); @@ -60,41 +59,37 @@ describe("test smart contract queries controller", () => { }); it("works with ABI, when arguments are native JS objects", async function () { - const adapter = new QueryRunnerAdapter({ - networkProvider: new MockNetworkProvider(), - }); - const controller = new SmartContractQueriesController({ + const controller = new SmartContractController({ + chainID: this.chainId, + networkProvider: this.networkProvider, abi: await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"), - queryRunner: adapter, }); const query = controller.createQuery({ - contract: "erd1foo", + contract: Address.empty(), function: "getLotteryInfo", arguments: ["myLottery"], }); - assert.equal(query.contract, "erd1foo"); + assert.deepEqual(query.contract, Address.empty()); assert.equal(query.function, "getLotteryInfo"); assert.deepEqual(query.arguments, [Buffer.from("myLottery")]); }); it("works with ABI, when arguments typed values", async function () { - const adapter = new QueryRunnerAdapter({ - networkProvider: new MockNetworkProvider(), - }); - const controller = new SmartContractQueriesController({ + const controller = new SmartContractController({ + chainID: this.chainId, + networkProvider: this.networkProvider, abi: await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"), - queryRunner: adapter, }); const query = controller.createQuery({ - contract: "erd1foo", + contract: Address.empty(), function: "getLotteryInfo", arguments: [BytesValue.fromUTF8("myLottery")], }); - assert.equal(query.contract, "erd1foo"); + assert.deepEqual(query.contract, Address.empty()); assert.equal(query.function, "getLotteryInfo"); assert.deepEqual(query.arguments, [Buffer.from("myLottery")]); }); @@ -123,16 +118,14 @@ describe("test smart contract queries controller", () => { ], }); - const adapter = new QueryRunnerAdapter({ - networkProvider: new MockNetworkProvider(), - }); - const controller = new SmartContractQueriesController({ + const controller = new SmartContractController({ + chainID: this.chainId, + networkProvider: this.networkProvider, abi: abi, - queryRunner: adapter, }); const query = controller.createQuery({ - contract: "erd1foo", + contract: Address.empty(), function: "bar", arguments: [ // Typed value @@ -148,7 +141,7 @@ describe("test smart contract queries controller", () => { ], }); - assert.equal(query.contract, "erd1foo"); + assert.deepEqual(query.contract, Address.empty()); assert.equal(query.function, "bar"); assert.deepEqual(query.arguments, [ Buffer.from("002a01", "hex"), @@ -162,23 +155,24 @@ describe("test smart contract queries controller", () => { describe("runQuery", () => { it("calls queryContract on the network provider", async function () { const networkProvider = new MockNetworkProvider(); - const adapter = new QueryRunnerAdapter({ + + const controller = new SmartContractController({ + chainID: this.chainId, networkProvider: networkProvider, }); - const controller = new SmartContractQueriesController({ - queryRunner: adapter, - }); networkProvider.mockQueryContractOnFunction( "bar", - new ContractQueryResponse({ - returnData: [Buffer.from("abba").toString("base64")], + new SmartContractQueryResponse({ + function: "bar", + returnDataParts: [Buffer.from("YWJiYQ==", "base64")], returnCode: "ok", + returnMessage: "msg", }), ); const query = { - contract: "erd1qqqqqqqqqqqqqpgqvc7gdl0p4s97guh498wgz75k8sav6sjfjlwqh679jy", + contract: Address.fromBech32("erd1qqqqqqqqqqqqqpgqvc7gdl0p4s97guh498wgz75k8sav6sjfjlwqh679jy"), function: "bar", arguments: [], }; @@ -192,11 +186,9 @@ describe("test smart contract queries controller", () => { describe("parseQueryResponse", () => { it("works without ABI", function () { - const adapter = new QueryRunnerAdapter({ - networkProvider: new MockNetworkProvider(), - }); - const controller = new SmartContractQueriesController({ - queryRunner: adapter, + const controller = new SmartContractController({ + chainID: this.chainId, + networkProvider: this.networkProvider, }); const response = new SmartContractQueryResponse({ @@ -212,12 +204,10 @@ describe("test smart contract queries controller", () => { }); it("works with ABI", async function () { - const adapter = new QueryRunnerAdapter({ - networkProvider: new MockNetworkProvider(), - }); - const controller = new SmartContractQueriesController({ + const controller = new SmartContractController({ + chainID: this.chainId, + networkProvider: this.networkProvider, abi: await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"), - queryRunner: adapter, }); const response = new SmartContractQueryResponse({ diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index e62955fb6..8b6744e74 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -1,9 +1,9 @@ -import { AbiRegistry } from "../abi"; +import { AbiRegistry, ArgSerializer, isTyped, NativeSerializer } from "../abi"; import { IAccount } from "../accounts/interfaces"; -import { QueryRunnerAdapter } from "../adapters"; -import { IAddress } from "../interface"; +import { Err, ErrSmartContractQuery } from "../errors"; +import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { INetworkProvider } from "../networkProviders/interface"; -import { SmartContractQueriesController } from "../smartContractQueriesController"; +import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../smartContractQuery"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; import { TransactionOnNetwork } from "../transactionOnNetwork"; @@ -16,23 +16,25 @@ import { SmartContractTransactionsFactory } from "./smartContractTransactionsFac export class SmartContractController { private factory: SmartContractTransactionsFactory; private parser: SmartContractTransactionsOutcomeParser; - private queryController: SmartContractQueriesController; private transactionWatcher: TransactionWatcher; private txComputer: TransactionComputer; + private networkProvider: ApiNetworkProvider | ProxyNetworkProvider | INetworkProvider; + private abi?: AbiRegistry; - constructor(options: { chainID: string; networkProvider: INetworkProvider; abi?: AbiRegistry }) { + constructor(options: { + chainID: string; + networkProvider: ApiNetworkProvider | ProxyNetworkProvider | INetworkProvider; + abi?: AbiRegistry; + }) { this.factory = new SmartContractTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: options.chainID }), abi: options.abi, }); this.parser = new SmartContractTransactionsOutcomeParser(options); - - this.queryController = new SmartContractQueriesController({ - queryRunner: new QueryRunnerAdapter(options), - abi: options.abi, - }); this.transactionWatcher = new TransactionWatcher(options.networkProvider); this.txComputer = new TransactionComputer(); + this.networkProvider = options.networkProvider; + this.abi = options.abi; } async createTransactionForDeploy( @@ -48,6 +50,10 @@ export class SmartContractController { return transaction; } + parseDeploy(transactionOnNetwork: TransactionOnNetwork): resources.SmartContractDeployOutcome { + return this.parser.parseDeploy({ transactionOnNetwork }); + } + async awaitCompletedDeploy(txHash: string): Promise { const transaction = await this.transactionWatcher.awaitCompleted(txHash); return this.parseDeploy(transaction); @@ -79,17 +85,93 @@ export class SmartContractController { return transaction; } - queryContract(contract: IAddress, func: string, args: any[], caller?: IAddress, value?: bigint): Promise { - return this.queryController.query({ - contract: contract.bech32(), - function: func, - arguments: args, - caller: caller ? caller.bech32() : undefined, - value: BigInt(value ?? 0), + parseExecute(transactionOnNetwork: TransactionOnNetwork): resources.ParsedSmartContractCallOutcome { + return this.parser.parseExecute({ transactionOnNetwork }); + } + + async awaitCompletedExecute(txHash: string): Promise { + const transaction = await this.transactionWatcher.awaitCompleted(txHash); + return this.parseExecute(transaction); + } + + async query(options: SmartContractQueryInput): Promise { + const query = this.createQuery(options); + const queryResponse = await this.runQuery(query); + this.raiseForStatus(queryResponse); + return this.parseQueryResponse(queryResponse); + } + + async runQuery(query: SmartContractQuery): Promise { + const queryResponse = await this.networkProvider.queryContract(query); + return queryResponse; + } + + createQuery(options: SmartContractQueryInput): SmartContractQuery { + const preparedArguments = this.encodeArguments(options.function, options.arguments); + + return new SmartContractQuery({ + contract: options.contract, + caller: options.caller, + function: options.function, + arguments: preparedArguments, + value: options.value, }); } - parseDeploy(transactionOnNetwork: TransactionOnNetwork): resources.SmartContractDeployOutcome { - return this.parser.parseDeploy({ transactionOnNetwork }); + private raiseForStatus(queryResponse: SmartContractQueryResponse): void { + const isOk = queryResponse.returnCode === "ok"; + if (!isOk) { + throw new ErrSmartContractQuery(queryResponse.returnCode, queryResponse.returnMessage); + } + } + + parseQueryResponse(response: SmartContractQueryResponse): any[] { + if (!this.abi) { + return response.returnDataParts; + } + + const argsSerializer = new ArgSerializer(); + const functionName = response.function; + const endpoint = this.abi.getEndpoint(functionName); + const parts = response.returnDataParts.map((part) => Buffer.from(part)); + + let values = argsSerializer.buffersToValues(parts, endpoint.output); + + return values.map((value) => value.valueOf()); + } + + private encodeArguments(functionName: string, args: any[]): Uint8Array[] { + const endpoint = this.abi?.getEndpoint(functionName); + + if (endpoint) { + const typedArgs = NativeSerializer.nativeToTypedValues(args, endpoint); + return new ArgSerializer().valuesToBuffers(typedArgs); + } + + if (this.areArgsOfTypedValue(args)) { + return new ArgSerializer().valuesToBuffers(args); + } + + if (this.areArgsBuffers(args)) { + return args.map((arg) => Buffer.from(arg)); + } + + throw new Err( + "cannot encode arguments: when ABI is not available, they must be either typed values or buffers", + ); + } + + private areArgsOfTypedValue(args: any[]): boolean { + return args.every((arg) => isTyped(arg)); + } + + private areArgsBuffers(args: any[]): boolean { + for (const arg of args) { + if (!ArrayBuffer.isView(arg)) { + return false; + } + } + + return true; } } diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 72923d428..16ca3e906 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -5,6 +5,7 @@ import { Err } from "../errors"; import { TransactionEvent } from "../transactionEvents"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractCallOutcome, SmartContractResult } from "../transactionsOutcomeParsers/resources"; +import * as resources from "./resources"; enum Events { SCDeploy = "SCDeploy", @@ -78,24 +79,19 @@ export class SmartContractTransactionsOutcomeParser { }; } - parseExecute(options: { transactionOnNetwork: TransactionOnNetwork; function?: string }): { - values: any[]; - returnCode: string; - returnMessage: string; - } { + parseExecute(options: { + transactionOnNetwork: TransactionOnNetwork; + function?: string; + }): resources.ParsedSmartContractCallOutcome { return this.parseExecuteGivenTransactionOnNetwork(options.transactionOnNetwork, options.function); } protected parseExecuteGivenTransactionOnNetwork( transactionOnNetwork: TransactionOnNetwork, functionName?: string, - ): { - values: any[]; - returnCode: string; - returnMessage: string; - } { + ): resources.ParsedSmartContractCallOutcome { const directCallOutcome = this.findDirectSmartContractCallOutcome(transactionOnNetwork); - + console.log({ directCallOutcome, abi: this.abi }); if (!this.abi) { return { values: directCallOutcome.returnDataParts, @@ -220,7 +216,7 @@ export class SmartContractTransactionsOutcomeParser { const [event] = eligibleEvents; const data = Buffer.from(event.data).toString(); - const lastTopic = event.getLastTopic()?.toString(); + const lastTopic = event.topics[event.topics.length - 1]?.toString(); const parts = argSerializer.stringToBuffers(data); // Assumption: the last part is the return code. const returnCode = parts[parts.length - 1]; diff --git a/src/testutils/contractController.ts b/src/testutils/contractController.ts deleted file mode 100644 index 18f3f9e46..000000000 --- a/src/testutils/contractController.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { Interaction, ResultsParser, TypedOutcomeBundle, UntypedOutcomeBundle } from "../abi"; -import { Logger } from "../logger"; -import { Transaction } from "../transaction"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionWatcher } from "../transactionWatcher"; -import { INetworkProvider } from "./networkProviders"; - -export class ContractController { - private readonly parser: ResultsParser; - private readonly provider: INetworkProvider; - private readonly transactionCompletionAwaiter: TransactionWatcher; - - constructor(provider: INetworkProvider) { - this.parser = new ResultsParser(); - this.provider = provider; - this.transactionCompletionAwaiter = new TransactionWatcher({ - getTransaction: async (hash: string) => { - return await provider.getTransaction(hash); - }, - }); - } - - async deploy( - transaction: Transaction, - ): Promise<{ transactionOnNetwork: TransactionOnNetwork; bundle: UntypedOutcomeBundle }> { - const txHash = await this.provider.sendTransaction(transaction); - Logger.info(`ContractController.deploy [begin]: transaction = ${txHash}`); - - let transactionOnNetwork = await this.transactionCompletionAwaiter.awaitCompleted(txHash); - let bundle = this.parser.parseUntypedOutcome(transactionOnNetwork); - - Logger.info(`ContractController.deploy [end]: transaction = ${txHash}, return code = ${bundle.returnCode}`); - return { transactionOnNetwork, bundle }; - } - - async execute( - interaction: Interaction, - transaction: Transaction, - ): Promise<{ transactionOnNetwork: TransactionOnNetwork; bundle: TypedOutcomeBundle }> { - const txHash = await this.provider.sendTransaction(transaction); - Logger.info( - `ContractController.execute [begin]: function = ${interaction.getFunction()}, transaction = ${txHash}`, - ); - - interaction.check(); - - let transactionOnNetwork = await this.transactionCompletionAwaiter.awaitCompleted(txHash); - let bundle = this.parser.parseOutcome(transactionOnNetwork, interaction.getEndpoint()); - - Logger.info( - `ContractController.execute [end]: function = ${interaction.getFunction()}, transaction = ${txHash}, return code = ${bundle.returnCode}`, - ); - return { transactionOnNetwork, bundle }; - } - - async query(interaction: Interaction): Promise { - Logger.debug(`ContractController.query [begin]: function = ${interaction.getFunction()}`); - - interaction.check(); - - let queryResponse = await this.provider.queryContract(interaction.buildQuery()); - let bundle = this.parser.parseQueryResponse(queryResponse, interaction.getEndpoint()); - - Logger.debug( - `ContractController.query [end]: function = ${interaction.getFunction()}, return code = ${bundle.returnCode}`, - ); - return bundle; - } -} diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 1e6efc012..1f4dc2281 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -1,40 +1,109 @@ -import { Query } from "../abi/query"; 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, ITransactionStatus } from "../interfaceOfNetwork"; +import { IAccountOnNetwork } from "../interfaceOfNetwork"; +import { + AccountOnNetwork, + DefinitionOfFungibleTokenOnNetwork, + DefinitionOfTokenCollectionOnNetwork, + FungibleTokenOfAccountOnNetwork, + NetworkConfig, + NetworkGeneralStatistics, + NetworkStake, + NetworkStatus, + NonFungibleTokenOfAccountOnNetwork, +} from "../networkProviders"; +import { IAddress, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "../networkProviders/interface"; +import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { Transaction, TransactionHash } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { TransactionStatus } from "../transactionStatus"; import { createAccountBalance } from "./utils"; -export class MockNetworkProvider { +export class MockNetworkProvider implements INetworkProvider { static AddressOfAlice = new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); static AddressOfBob = new Address("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); static AddressOfCarol = new Address("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"); private readonly transactions: Map; private nextTransactionTimelinePoints: any[] = []; - private readonly accounts: Map; + private readonly accounts: Map; private readonly queryContractResponders: QueryContractResponder[] = []; private readonly getTransactionResponders: GetTransactionResponder[] = []; constructor() { this.transactions = new Map(); - this.accounts = new Map(); + this.accounts = new Map(); - this.accounts.set(MockNetworkProvider.AddressOfAlice.bech32(), { - nonce: 0, - balance: createAccountBalance(1000), - }); - this.accounts.set(MockNetworkProvider.AddressOfBob.bech32(), { nonce: 5, balance: createAccountBalance(500) }); - this.accounts.set(MockNetworkProvider.AddressOfCarol.bech32(), { - nonce: 42, - balance: createAccountBalance(300), - }); + this.accounts.set( + MockNetworkProvider.AddressOfAlice.bech32(), + new AccountOnNetwork({ + nonce: 0, + balance: createAccountBalance(1000), + }), + ); + this.accounts.set( + MockNetworkProvider.AddressOfBob.bech32(), + new AccountOnNetwork({ nonce: 5, balance: createAccountBalance(500) }), + ); + this.accounts.set( + MockNetworkProvider.AddressOfCarol.bech32(), + new AccountOnNetwork({ + nonce: 42, + balance: createAccountBalance(300), + }), + ); + } + getNetworkStatus(): Promise { + throw new Error("Method not implemented."); + } + getNetworkStakeStatistics(): Promise { + throw new Error("Method not implemented."); + } + getNetworkGeneralStatistics(): Promise { + throw new Error("Method not implemented."); + } + getFungibleTokensOfAccount( + _address: IAddress, + _pagination?: IPagination, + ): Promise { + throw new Error("Method not implemented."); + } + getNonFungibleTokensOfAccount( + _address: IAddress, + _pagination?: IPagination, + ): Promise { + throw new Error("Method not implemented."); + } + getFungibleTokenOfAccount(_address: IAddress, _tokenIdentifier: string): Promise { + throw new Error("Method not implemented."); + } + getNonFungibleTokenOfAccount( + _address: IAddress, + _collection: string, + _nonce: number, + ): Promise { + throw new Error("Method not implemented."); + } + sendTransactions(_txs: (ITransaction | ITransactionNext)[]): Promise { + throw new Error("Method not implemented."); + } + getDefinitionOfFungibleToken(_tokenIdentifier: string): Promise { + throw new Error("Method not implemented."); + } + getDefinitionOfTokenCollection(_collection: string): Promise { + throw new Error("Method not implemented."); + } + getNonFungibleToken(_collection: string, _nonce: number): Promise { + throw new Error("Method not implemented."); + } + doGetGeneric(_resourceUrl: string): Promise { + throw new Error("Method not implemented."); + } + doPostGeneric(_resourceUrl: string, _payload: any): Promise { + throw new Error("Method not implemented."); } mockUpdateAccount(address: Address, mutate: (item: IAccountOnNetwork) => void) { @@ -56,12 +125,12 @@ export class MockNetworkProvider { this.transactions.set(hash.toString(), item); } - mockQueryContractOnFunction(functionName: string, response: IContractQueryResponse) { - let predicate = (query: Query) => query.func.toString() == functionName; + mockQueryContractOnFunction(functionName: string, response: SmartContractQueryResponse) { + let predicate = (query: SmartContractQuery) => query.function.toString() == functionName; this.queryContractResponders.push(new QueryContractResponder(predicate, response)); } - mockGetTransactionWithAnyHashAsNotarizedWithOneResult(returnCodeAndData: string) { + mockGetTransactionWithAnyHashAsNotarizedWithOneResult(returnCodeAndData: string, functionName: string = "") { let contractResult = new SmartContractResult({ data: Buffer.from(returnCodeAndData) }); let predicate = (_hash: string) => true; @@ -69,6 +138,7 @@ export class MockNetworkProvider { status: new TransactionStatus("executed"), smartContractResults: [contractResult], isCompleted: true, + function: functionName, }); this.getTransactionResponders.unshift(new GetTransactionResponder(predicate, response)); @@ -102,7 +172,7 @@ export class MockNetworkProvider { } } - async getAccount(address: IAddress): Promise { + async getAccount(address: IAddress): Promise { let account = this.accounts.get(address.bech32()); if (account) { return account; @@ -147,16 +217,16 @@ export class MockNetworkProvider { throw new ErrMock("Transaction not found"); } - async getTransactionStatus(txHash: string): Promise { + async getTransactionStatus(txHash: string): Promise { let transaction = await this.getTransaction(txHash); return transaction.status; } - async getNetworkConfig(): Promise { + async getNetworkConfig(): Promise { throw new errors.ErrNotImplemented(); } - async queryContract(query: Query): Promise { + async queryContract(query: SmartContractQuery): Promise { for (const responder of this.queryContractResponders) { if (responder.matches(query)) { return responder.response; @@ -178,10 +248,10 @@ export class Wait { export class MarkCompleted {} class QueryContractResponder { - readonly matches: (query: Query) => boolean; - readonly response: IContractQueryResponse; + readonly matches: (query: SmartContractQuery) => boolean; + readonly response: SmartContractQueryResponse; - constructor(matches: (query: Query) => boolean, response: IContractQueryResponse) { + constructor(matches: (query: SmartContractQuery) => boolean, response: SmartContractQueryResponse) { this.matches = matches; this.response = response; } diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index e75ffa19b..1bddab6d4 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,7 +1,7 @@ -import { Query } from "../abi"; import { IAddress } from "../interface"; -import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionStatus } from "../interfaceOfNetwork"; +import { IAccountOnNetwork, INetworkConfig, ITransactionStatus } from "../interfaceOfNetwork"; import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; +import { SmartContractQueryInput, SmartContractQueryResponse } from "../smartContractQuery"; import { Transaction } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; @@ -38,5 +38,5 @@ export interface INetworkProvider { getTransactionStatus(txHash: string): Promise; sendTransaction(tx: Transaction): Promise; simulateTransaction(tx: Transaction): Promise; - queryContract(query: Query): Promise; + queryContract(query: SmartContractQueryInput): Promise; } diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index 725f92009..5aadce52c 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -30,12 +30,4 @@ export class TransactionEvent { return result; } - - findFirstOrNoneTopic(predicate: (topic: Uint8Array) => boolean): Uint8Array | undefined { - return this.topics.filter((topic) => predicate(topic))[0]; - } - - getLastTopic(): Uint8Array { - return this.topics[this.topics.length - 1]; - } } diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.ts b/src/transactionsOutcomeParsers/transactionEventsParser.ts index 7eb0363fc..93b53df94 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.ts @@ -1,13 +1,11 @@ -import { AbiRegistry, ResultsParser } from "../abi"; +import { AbiRegistry, ArgSerializer } from "../abi"; import { TransactionEvent } from "../transactionEvents"; export class TransactionEventsParser { - private readonly legacyResultsParser: ResultsParser; private readonly abi: AbiRegistry; private readonly firstTopicIsIdentifier: boolean; constructor(options: { abi: AbiRegistry; firstTopicIsIdentifier?: boolean }) { - this.legacyResultsParser = new ResultsParser(); this.abi = options.abi; // By default, we consider that the first topic is the event identifier. @@ -39,12 +37,23 @@ export class TransactionEventsParser { const dataItems = options.event.additionalData.map((dataItem) => Buffer.from(dataItem)); const eventDefinition = this.abi.getEvent(abiIdentifier); - const parsedEvent = this.legacyResultsParser.doParseEvent({ - topics: topics, - dataItems: dataItems, - eventDefinition: eventDefinition, - }); + const result: any = {}; + const argsSerializer = new ArgSerializer(); - return parsedEvent; + // "Indexed" ABI "event.inputs" correspond to "event.topics[1:]": + const indexedInputs = eventDefinition.inputs.filter((input) => input.indexed); + const decodedTopics = argsSerializer.buffersToValues(topics, indexedInputs); + for (let i = 0; i < indexedInputs.length; i++) { + result[indexedInputs[i].name] = decodedTopics[i].valueOf(); + } + + // "Non-indexed" ABI "event.inputs" correspond to "event.data": + const nonIndexedInputs = eventDefinition.inputs.filter((input) => !input.indexed); + const decodedDataParts = argsSerializer.buffersToValues(dataItems, nonIndexedInputs); + for (let i = 0; i < nonIndexedInputs.length; i++) { + result[nonIndexedInputs[i].name] = decodedDataParts[i]?.valueOf(); + } + + return result; } } From befd1c0f0f67e0d4374dc17e50f77df977ee2328 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 27 Nov 2024 15:13:26 +0200 Subject: [PATCH 058/214] Update integration tests --- src/abi/interaction.local.net.spec.ts | 276 ++++++++++-------- src/abi/smartContract.local.net.spec.ts | 152 ++++++---- .../smartContractResults.local.net.spec.ts | 21 +- src/adapters/index.ts | 1 - src/adapters/queryRunnerAdapter.ts | 41 --- src/index.ts | 1 - src/networkProviders/contractQueryRequest.ts | 1 - src/networkProviders/proxyNetworkProvider.ts | 3 +- src/testutils/networkProviders.ts | 17 +- 9 files changed, 278 insertions(+), 235 deletions(-) delete mode 100644 src/adapters/index.ts delete mode 100644 src/adapters/queryRunnerAdapter.ts diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 2af44644e..346a562cd 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -1,30 +1,28 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { promises } from "fs"; -import { QueryRunnerAdapter } from "../adapters/queryRunnerAdapter"; -import { SmartContractQueriesController } from "../smartContractQueriesController"; -import { SmartContractTransactionsFactory } from "../smartContracts"; +import { SmartContractQueryInput } from "../smartContractQuery"; +import { + SmartContractController, + SmartContractTransactionsFactory, + SmartContractTransactionsOutcomeParser, +} from "../smartContracts"; import { loadAbiRegistry, loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; -import { ContractController } from "../testutils/contractController"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { Interaction } from "./interaction"; -import { ResultsParser } from "./resultsParser"; -import { ReturnCode } from "./returnCode"; import { SmartContract } from "./smartContract"; import { ManagedDecimalSignedValue, ManagedDecimalValue } from "./typesystem"; describe("test smart contract interactor", function () { let provider = createLocalnetProvider(); let alice: TestWallet; - let resultsParser: ResultsParser; before(async function () { ({ alice } = await loadTestWallets()); - resultsParser = new ResultsParser(); }); it("should interact with 'answer' (local testnet)", async function () { @@ -32,7 +30,11 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); let contract = new SmartContract({ abi: abiRegistry }); - let controller = new ContractController(provider); + let controller = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + abi: abiRegistry, + }); let network = await provider.getNetworkConfig(); await alice.sync(provider); @@ -47,10 +49,9 @@ describe("test smart contract interactor", function () { chainID: network.ChainID, }); - let { - bundle: { returnCode }, - } = await controller.deploy(deployTransaction); - assert.isTrue(returnCode.isSuccess()); + let deployTxHash = await provider.sendTransaction(deployTransaction); + let deployResponse = await controller.awaitCompletedDeploy(deployTxHash); + assert.isTrue(deployResponse.returnCode == "ok"); const interaction = ( contract.methods @@ -59,12 +60,20 @@ describe("test smart contract interactor", function () { .withChainID(network.ChainID) .withSender(alice.address) ); + const interactionQuery = interaction.buildQuery(); // Query - let queryResponseBundle = await controller.query(interaction); - assert.lengthOf(queryResponseBundle.values, 1); - assert.deepEqual(queryResponseBundle.firstValue!.valueOf(), new BigNumber(42)); - assert.isTrue(queryResponseBundle.returnCode.equals(ReturnCode.Ok)); + const queryResponse = await controller.query( + new SmartContractQueryInput({ + contract: interactionQuery.address, + arguments: interactionQuery.getEncodedArguments(), + function: interactionQuery.func.toString(), + caller: interactionQuery.caller, + value: BigInt(interactionQuery.value.toString()), + }), + ); + assert.lengthOf(queryResponse, 1); + assert.deepEqual(queryResponse[0]!.valueOf(), new BigNumber(42)); // Execute, do not wait for execution let transaction = interaction @@ -79,11 +88,11 @@ describe("test smart contract interactor", function () { transaction = interaction.withSender(alice.address).useThenIncrementNonceOf(alice.account).buildTransaction(); await signTransaction({ transaction: transaction, wallet: alice }); - let { bundle: executionResultsBundle } = await controller.execute(interaction, transaction); - - assert.lengthOf(executionResultsBundle.values, 1); - assert.deepEqual(executionResultsBundle.firstValue!.valueOf(), new BigNumber(42)); - assert.isTrue(executionResultsBundle.returnCode.equals(ReturnCode.Ok)); + let txHash = await provider.sendTransaction(transaction); + let response = await controller.awaitCompletedExecute(txHash); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 1); + assert.deepEqual(response.values[0], new BigNumber(42)); }); it("should interact with 'answer' (local testnet) using the SmartContractTransactionsFactory", async function () { @@ -123,16 +132,20 @@ describe("test smart contract interactor", function () { }); const deployTxHash = await provider.sendTransaction(deployTransaction); - let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); - const untypedBundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(untypedBundle.returnCode.isSuccess()); - const queryRunner = new QueryRunnerAdapter({ networkProvider: provider }); - const queryController = new SmartContractQueriesController({ abi: abiRegistry, queryRunner: queryRunner }); + const queryController = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + abi: abiRegistry, + }); + + let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); + let response = queryController.parseExecute(transactionOnNetwork); + assert.isTrue(response.returnCode == "ok"); const query = queryController.createQuery({ - contract: contractAddress.bech32(), - caller: alice.address.bech32(), + contract: contractAddress, + caller: alice.address, function: "getUltimateAnswer", arguments: [], }); @@ -172,14 +185,11 @@ describe("test smart contract interactor", function () { const executeTxHash = await provider.sendTransaction(transaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(executeTxHash); - const typedBundle = resultsParser.parseOutcome( - transactionOnNetwork, - abiRegistry.getEndpoint("getUltimateAnswer"), - ); + response = queryController.parseExecute(transactionOnNetwork); - assert.lengthOf(typedBundle.values, 1); - assert.deepEqual(typedBundle.firstValue!.valueOf(), new BigNumber(42)); - assert.isTrue(typedBundle.returnCode.equals(ReturnCode.Ok)); + assert.isTrue(response.values.length == 1); + assert.deepEqual(response.values[0], new BigNumber(42)); + assert.isTrue(response.returnCode == "ok"); }); it("should interact with 'basic-features' (local testnet)", async function () { @@ -187,7 +197,11 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/basic-features.abi.json"); let contract = new SmartContract({ abi: abiRegistry }); - let controller = new ContractController(provider); + let controller = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + abi: abiRegistry, + }); let network = await provider.getNetworkConfig(); await alice.sync(provider); @@ -201,11 +215,9 @@ describe("test smart contract interactor", function () { initArguments: [], chainID: network.ChainID, }); - - let { - bundle: { returnCode }, - } = await controller.deploy(deployTransaction); - assert.isTrue(returnCode.isSuccess()); + let deployTxHash = await provider.sendTransaction(deployTransaction); + let deployResponse = await controller.awaitCompletedDeploy(deployTxHash); + assert.isTrue(deployResponse.returnCode == "ok"); let returnEgldInteraction = ( contract.methods @@ -280,38 +292,44 @@ describe("test smart contract interactor", function () { // returnEgld() await signTransaction({ transaction: returnEgldTransaction, wallet: alice }); - let { bundle: bundleEgld } = await controller.execute(returnEgldInteraction, returnEgldTransaction); - assert.isTrue(bundleEgld.returnCode.equals(ReturnCode.Ok)); - assert.lengthOf(bundleEgld.values, 1); - assert.deepEqual(bundleEgld.values[0], new ManagedDecimalValue("0.000000000000000001", 18)); + let txHash = await provider.sendTransaction(returnEgldTransaction); + let response = await controller.awaitCompletedExecute(txHash); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 1); + assert.deepEqual(response.values[0], new ManagedDecimalValue("0.000000000000000001", 18)); // addition with const decimals() await signTransaction({ transaction: additionTransaction, wallet: alice }); - let { bundle: bundleAdditionConst } = await controller.execute(additionInteraction, additionTransaction); - assert.isTrue(bundleAdditionConst.returnCode.equals(ReturnCode.Ok)); - assert.lengthOf(bundleAdditionConst.values, 1); - assert.deepEqual(bundleAdditionConst.values[0], new ManagedDecimalValue("5.2", 2)); + txHash = await provider.sendTransaction(additionTransaction); + response = await controller.awaitCompletedExecute(txHash); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 1); + assert.deepEqual(response.values[0], new ManagedDecimalValue("5.2", 2)); // log await signTransaction({ transaction: mdLnTransaction, wallet: alice }); - let { bundle: bundleMDLn } = await controller.execute(mdLnInteraction, mdLnTransaction); - assert.isTrue(bundleMDLn.returnCode.equals(ReturnCode.Ok)); - assert.lengthOf(bundleMDLn.values, 1); - assert.deepEqual(bundleMDLn.values[0], new ManagedDecimalSignedValue("3.135553845", 9)); + txHash = await provider.sendTransaction(mdLnTransaction); + response = await controller.awaitCompletedExecute(txHash); + + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 1); + assert.deepEqual(response.values[0], new ManagedDecimalSignedValue("3.135553845", 9)); // addition with var decimals await signTransaction({ transaction: additionVarTransaction, wallet: alice }); - let { bundle: bundleAddition } = await controller.execute(additionVarInteraction, additionVarTransaction); - assert.isTrue(bundleAddition.returnCode.equals(ReturnCode.Ok)); - assert.lengthOf(bundleAddition.values, 1); - assert.deepEqual(bundleAddition.values[0], new ManagedDecimalValue("9", 2)); + txHash = await provider.sendTransaction(additionVarTransaction); + response = await controller.awaitCompletedExecute(txHash); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 1); + assert.deepEqual(response.values[0], new ManagedDecimalValue("9", 2)); // log await signTransaction({ transaction: lnVarTransaction, wallet: alice }); - let { bundle: bundleLnVar } = await controller.execute(lnVarInteraction, lnVarTransaction); - assert.isTrue(bundleLnVar.returnCode.equals(ReturnCode.Ok)); - assert.lengthOf(bundleLnVar.values, 1); - assert.deepEqual(bundleLnVar.values[0], new ManagedDecimalSignedValue("3.135553845", 9)); + txHash = await provider.sendTransaction(lnVarTransaction); + response = await controller.awaitCompletedExecute(txHash); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 1); + assert.deepEqual(response.values[0], new ManagedDecimalSignedValue("3.135553845", 9)); }); it("should interact with 'counter' (local testnet)", async function () { @@ -319,7 +337,11 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/counter.abi.json"); let contract = new SmartContract({ abi: abiRegistry }); - let controller = new ContractController(provider); + let controller = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + abi: abiRegistry, + }); let network = await provider.getNetworkConfig(); await alice.sync(provider); @@ -334,12 +356,11 @@ describe("test smart contract interactor", function () { chainID: network.ChainID, }); - let { - bundle: { returnCode }, - } = await controller.deploy(deployTransaction); - assert.isTrue(returnCode.isSuccess()); + await provider.sendTransaction(deployTransaction); + let hash = await provider.sendTransaction(deployTransaction); + let responseExecute = await controller.awaitCompletedExecute(hash); + assert.isTrue(responseExecute.returnCode == "ok"); - let getInteraction = contract.methods.get(); let incrementInteraction = (contract.methods.increment()) .withGasLimit(3000000) .withChainID(network.ChainID) @@ -350,16 +371,27 @@ describe("test smart contract interactor", function () { .withSender(alice.address); // Query "get()" - let { firstValue: counterValue } = await controller.query(getInteraction); - assert.deepEqual(counterValue!.valueOf(), new BigNumber(1)); + + let interactionQuery = incrementInteraction.buildQuery(); + let response = await controller.query( + new SmartContractQueryInput({ + contract: interactionQuery.address, + arguments: interactionQuery.getEncodedArguments(), + function: interactionQuery.func.toString(), + caller: interactionQuery.caller, + value: BigInt(interactionQuery.value.toString()), + }), + ); + assert.deepEqual(response[0]!.valueOf(), new BigNumber(1)); // Increment, wait for execution. let incrementTransaction = incrementInteraction.useThenIncrementNonceOf(alice.account).buildTransaction(); await signTransaction({ transaction: incrementTransaction, wallet: alice }); - let { - bundle: { firstValue: valueAfterIncrement }, - } = await controller.execute(incrementInteraction, incrementTransaction); - assert.deepEqual(valueAfterIncrement!.valueOf(), new BigNumber(2)); + + hash = await provider.sendTransaction(incrementTransaction); + responseExecute = await controller.awaitCompletedExecute(hash); + assert.isTrue(responseExecute.returnCode == "ok"); + assert.deepEqual(responseExecute.values[0], new BigNumber(2)); // Decrement twice. Wait for execution of the second transaction. let decrementTransaction = decrementInteraction.useThenIncrementNonceOf(alice.account).buildTransaction(); @@ -367,11 +399,12 @@ describe("test smart contract interactor", function () { await provider.sendTransaction(decrementTransaction); decrementTransaction = decrementInteraction.useThenIncrementNonceOf(alice.account).buildTransaction(); + await signTransaction({ transaction: decrementTransaction, wallet: alice }); - let { - bundle: { firstValue: valueAfterDecrement }, - } = await controller.execute(decrementInteraction, decrementTransaction); - assert.deepEqual(valueAfterDecrement!.valueOf(), new BigNumber(0)); + hash = await provider.sendTransaction(decrementTransaction); + responseExecute = await controller.awaitCompletedExecute(hash); + assert.isTrue(responseExecute.returnCode == "ok"); + assert.deepEqual(responseExecute.values[0], new BigNumber(0)); }); it("should interact with 'counter' (local testnet) using the SmartContractTransactionsFactory", async function () { @@ -387,6 +420,7 @@ describe("test smart contract interactor", function () { config: config, abi: abiRegistry, }); + const parser = new SmartContractTransactionsOutcomeParser(); const bytecode = await promises.readFile("src/testdata/counter.wasm"); @@ -412,11 +446,14 @@ describe("test smart contract interactor", function () { const deployTxHash = await provider.sendTransaction(deployTransaction); let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); - const untypedBundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(untypedBundle.returnCode.isSuccess()); + let response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); - const queryRunner = new QueryRunnerAdapter({ networkProvider: provider }); - const queryController = new SmartContractQueriesController({ abi: abiRegistry, queryRunner: queryRunner }); + const queryController = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + abi: abiRegistry, + }); let incrementTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -433,7 +470,7 @@ describe("test smart contract interactor", function () { // Query "get()" const query = queryController.createQuery({ - contract: contractAddress.bech32(), + contract: contractAddress, function: "get", arguments: [], }); @@ -443,8 +480,9 @@ describe("test smart contract interactor", function () { const incrementTxHash = await provider.sendTransaction(incrementTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(incrementTxHash); - let typedBundle = resultsParser.parseOutcome(transactionOnNetwork, abiRegistry.getEndpoint("increment")); - assert.deepEqual(typedBundle.firstValue!.valueOf(), new BigNumber(2)); + + response = parser.parseExecute({ transactionOnNetwork }); + assert.deepEqual(response.values[0], new BigNumber(2)); let decrementTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -467,7 +505,7 @@ describe("test smart contract interactor", function () { const decrementTxHash = await provider.sendTransaction(decrementTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(decrementTxHash); - typedBundle = resultsParser.parseOutcome(transactionOnNetwork, abiRegistry.getEndpoint("decrement")); + response = parser.parseExecute({ transactionOnNetwork }); }); it("should interact with 'lottery-esdt' (local testnet)", async function () { @@ -475,7 +513,11 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); let contract = new SmartContract({ abi: abiRegistry }); - let controller = new ContractController(provider); + let controller = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + abi: abiRegistry, + }); let network = await provider.getNetworkConfig(); await alice.sync(provider); @@ -490,10 +532,10 @@ describe("test smart contract interactor", function () { chainID: network.ChainID, }); - let { - bundle: { returnCode }, - } = await controller.deploy(deployTransaction); - assert.isTrue(returnCode.isSuccess()); + const deployTxHash = await provider.sendTransaction(deployTransaction); + let parsedResponse = await controller.awaitCompletedDeploy(deployTxHash); + + assert.isTrue(parsedResponse.returnCode == "ok"); let startInteraction = ( contract.methods @@ -526,9 +568,10 @@ describe("test smart contract interactor", function () { .buildTransaction(); await signTransaction({ transaction: startTransaction, wallet: alice }); - let { bundle: bundleStart } = await controller.execute(startInteraction, startTransaction); - assert.isTrue(bundleStart.returnCode.equals(ReturnCode.Ok)); - assert.lengthOf(bundleStart.values, 0); + const startTxHash = await provider.sendTransaction(startTransaction); + let response = await controller.awaitCompletedExecute(startTxHash); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 0); // status() let lotteryStatusTransaction = lotteryStatusInteraction @@ -537,10 +580,11 @@ describe("test smart contract interactor", function () { .buildTransaction(); await signTransaction({ transaction: lotteryStatusTransaction, wallet: alice }); - let { bundle: bundleStatus } = await controller.execute(lotteryStatusInteraction, lotteryStatusTransaction); - assert.isTrue(bundleStatus.returnCode.equals(ReturnCode.Ok)); - assert.lengthOf(bundleStatus.values, 1); - assert.equal(bundleStatus.firstValue!.valueOf().name, "Running"); + const lotteryStatusTxHash = await provider.sendTransaction(lotteryStatusTransaction); + response = await controller.awaitCompletedExecute(lotteryStatusTxHash); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 1); + assert.equal(response[0].name, "Running"); // lotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) let lotteryInfoTransaction = getLotteryInfoInteraction @@ -549,12 +593,13 @@ describe("test smart contract interactor", function () { .buildTransaction(); await signTransaction({ transaction: lotteryInfoTransaction, wallet: alice }); - let { bundle: bundleLotteryInfo } = await controller.execute(getLotteryInfoInteraction, lotteryInfoTransaction); - assert.isTrue(bundleLotteryInfo.returnCode.equals(ReturnCode.Ok)); - assert.lengthOf(bundleLotteryInfo.values, 1); + const lotteryInfoTxHash = await provider.sendTransaction(lotteryInfoTransaction); + response = await controller.awaitCompletedExecute(lotteryInfoTxHash); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 1); // Ignore "deadline" field in our test - let info = bundleLotteryInfo.firstValue!.valueOf(); + let info = response[0].valueOf(); delete info.deadline; assert.deepEqual(info, { @@ -571,6 +616,7 @@ describe("test smart contract interactor", function () { this.timeout(140000); let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); + let parser = new SmartContractTransactionsOutcomeParser(); let network = await provider.getNetworkConfig(); await alice.sync(provider); @@ -606,8 +652,8 @@ describe("test smart contract interactor", function () { const deployTxHash = await provider.sendTransaction(deployTransaction); let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); - const untypedBundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(untypedBundle.returnCode.isSuccess()); + const deployResponse = parser.parseDeploy({ transactionOnNetwork }); + assert.isTrue(deployResponse.returnCode == "ok"); // start() let startTransaction = factory.createTransactionForExecute(alice.address, { @@ -625,9 +671,9 @@ describe("test smart contract interactor", function () { const startTxHash = await provider.sendTransaction(startTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(startTxHash); - let typedBundle = resultsParser.parseOutcome(transactionOnNetwork, abiRegistry.getEndpoint("start")); - assert.equal(typedBundle.returnCode.valueOf(), "ok"); - assert.lengthOf(typedBundle.values, 0); + let response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 0); // status() let lotteryStatusTransaction = factory.createTransactionForExecute(alice.address, { @@ -645,10 +691,10 @@ describe("test smart contract interactor", function () { const statusTxHash = await provider.sendTransaction(lotteryStatusTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(statusTxHash); - typedBundle = resultsParser.parseOutcome(transactionOnNetwork, abiRegistry.getEndpoint("status")); - assert.equal(typedBundle.returnCode.valueOf(), "ok"); - assert.lengthOf(typedBundle.values, 1); - assert.equal(typedBundle.firstValue!.valueOf().name, "Running"); + response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 0); + assert.equal(response.values[0].name, "Running"); // getlotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) let lotteryInfoTransaction = factory.createTransactionForExecute(alice.address, { @@ -666,12 +712,12 @@ describe("test smart contract interactor", function () { const infoTxHash = await provider.sendTransaction(lotteryInfoTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(infoTxHash); - typedBundle = resultsParser.parseOutcome(transactionOnNetwork, abiRegistry.getEndpoint("getLotteryInfo")); - assert.equal(typedBundle.returnCode.valueOf(), "ok"); - assert.lengthOf(typedBundle.values, 1); + response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); + assert.lengthOf(response.values, 0); // Ignore "deadline" field in our test - let info = typedBundle.firstValue!.valueOf(); + let info = response.values[0]!.valueOf(); delete info.deadline; assert.deepEqual(info, { diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index a726357e4..c06c15c9d 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -1,9 +1,12 @@ import { assert } from "chai"; import { promises } from "fs"; -import { QueryRunnerAdapter } from "../adapters/queryRunnerAdapter"; import { Logger } from "../logger"; -import { SmartContractQueriesController } from "../smartContractQueriesController"; -import { SmartContractTransactionsFactory } from "../smartContracts"; +import { SmartContractQueryInput } from "../smartContractQuery"; +import { + SmartContractController, + SmartContractTransactionsFactory, + SmartContractTransactionsOutcomeParser, +} from "../smartContracts"; import { prepareDeployment } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { loadTestWallets, TestWallet } from "../testutils/wallets"; @@ -27,6 +30,7 @@ describe("test on local testnet", function () { let alice: TestWallet, bob: TestWallet, carol: TestWallet; let provider = createLocalnetProvider(); let watcher: TransactionWatcher; + let parser: SmartContractTransactionsOutcomeParser; before(async function () { ({ alice, bob, carol } = await loadTestWallets()); @@ -36,6 +40,7 @@ describe("test on local testnet", function () { return await provider.getTransaction(hash); }, }); + parser = new SmartContractTransactionsOutcomeParser(); }); it("counter: should deploy, then simulate transactions", async function () { @@ -100,13 +105,14 @@ describe("test on local testnet", function () { await watcher.awaitCompleted(txHashDeploy); let transactionOnNetwork = await provider.getTransaction(txHashDeploy); - let bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(bundle.returnCode.isSuccess()); + let response = parser.parseExecute({ transactionOnNetwork }); + + assert.isTrue(response.returnCode == "ok"); await watcher.awaitCompleted(txHashIncrement); transactionOnNetwork = await provider.getTransaction(txHashIncrement); - bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(bundle.returnCode.isSuccess()); + response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); // Simulate Logger.trace(JSON.stringify(await provider.simulateTransaction(simulateOne), null, 4)); @@ -185,13 +191,14 @@ describe("test on local testnet", function () { await watcher.awaitCompleted(deployTxHash); let transactionOnNetwork = await provider.getTransaction(deployTxHash); - let bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(bundle.returnCode.isSuccess()); + let response = parser.parseExecute({ transactionOnNetwork }); + + assert.isTrue(response.returnCode == "ok"); await watcher.awaitCompleted(callTxHash); transactionOnNetwork = await provider.getTransaction(callTxHash); - bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(bundle.returnCode.isSuccess()); + response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); // Simulate Logger.trace(JSON.stringify(await provider.simulateTransaction(simulateOne), null, 4)); @@ -258,9 +265,15 @@ describe("test on local testnet", function () { // Check counter let query = contract.createQuery({ func: new ContractFunction("get") }); - let queryResponse = await provider.queryContract(query); - assert.lengthOf(queryResponse.getReturnDataParts(), 1); - assert.equal(3, decodeUnsignedNumber(queryResponse.getReturnDataParts()[0])); + let queryResponse = await provider.queryContract( + new SmartContractQueryInput({ + contract: query.address, + arguments: query.args, + function: query.func.toString(), + }), + ); + assert.isTrue(queryResponse.returnDataParts.length == 1); + assert.equal(3, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); }); it("counter: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { @@ -325,11 +338,13 @@ describe("test on local testnet", function () { await watcher.awaitCompleted(secondScCallHash); // Check counter - const queryRunner = new QueryRunnerAdapter({ networkProvider: provider }); - const smartContractQueriesController = new SmartContractQueriesController({ queryRunner: queryRunner }); + const smartContractQueriesController = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + }); const query = smartContractQueriesController.createQuery({ - contract: contractAddress.bech32(), + contract: contractAddress, function: "get", arguments: [], }); @@ -397,33 +412,56 @@ describe("test on local testnet", function () { // Query state, do some assertions let query = contract.createQuery({ func: new ContractFunction("totalSupply") }); - let queryResponse = await provider.queryContract(query); - assert.lengthOf(queryResponse.getReturnDataParts(), 1); - assert.equal(10000, decodeUnsignedNumber(queryResponse.getReturnDataParts()[0])); + let queryResponse = await provider.queryContract( + new SmartContractQueryInput({ + contract: query.address, + arguments: query.args, + function: query.func.toString(), + }), + ); + assert.isTrue(queryResponse.returnDataParts.length == 1); + assert.equal(10000, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); query = contract.createQuery({ func: new ContractFunction("balanceOf"), args: [new AddressValue(alice.address)], }); - queryResponse = await provider.queryContract(query); - - assert.equal(7500, decodeUnsignedNumber(queryResponse.getReturnDataParts()[0])); + queryResponse = await provider.queryContract( + new SmartContractQueryInput({ + contract: query.address, + arguments: query.args, + function: query.func.toString(), + }), + ); + assert.equal(7500, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); query = contract.createQuery({ func: new ContractFunction("balanceOf"), args: [new AddressValue(bob.address)], }); - queryResponse = await provider.queryContract(query); + queryResponse = await provider.queryContract( + new SmartContractQueryInput({ + contract: query.address, + arguments: query.args, + function: query.func.toString(), + }), + ); - assert.equal(1000, decodeUnsignedNumber(queryResponse.getReturnDataParts()[0])); + assert.equal(1000, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); query = contract.createQuery({ func: new ContractFunction("balanceOf"), args: [new AddressValue(carol.address)], }); - queryResponse = await provider.queryContract(query); + queryResponse = await provider.queryContract( + new SmartContractQueryInput({ + contract: query.address, + arguments: query.args, + function: query.func.toString(), + }), + ); - assert.equal(1500, decodeUnsignedNumber(queryResponse.getReturnDataParts()[0])); + assert.equal(1500, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); }); it("erc20: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { @@ -490,11 +528,13 @@ describe("test on local testnet", function () { await watcher.awaitCompleted(mintCarolTxHash); // Query state, do some assertions - const queryRunner = new QueryRunnerAdapter({ networkProvider: provider }); - const smartContractQueriesController = new SmartContractQueriesController({ queryRunner: queryRunner }); + const smartContractQueriesController = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + }); let query = smartContractQueriesController.createQuery({ - contract: contractAddress.bech32(), + contract: contractAddress, function: "totalSupply", arguments: [], }); @@ -503,7 +543,7 @@ describe("test on local testnet", function () { assert.equal(10000, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); query = smartContractQueriesController.createQuery({ - contract: contractAddress.bech32(), + contract: contractAddress, function: "balanceOf", arguments: [new AddressValue(alice.address)], }); @@ -511,7 +551,7 @@ describe("test on local testnet", function () { assert.equal(7500, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); query = smartContractQueriesController.createQuery({ - contract: contractAddress.bech32(), + contract: contractAddress, function: "balanceOf", arguments: [new AddressValue(bob.address)], }); @@ -519,7 +559,7 @@ describe("test on local testnet", function () { assert.equal(1000, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); query = smartContractQueriesController.createQuery({ - contract: contractAddress.bech32(), + contract: contractAddress, function: "balanceOf", arguments: [new AddressValue(carol.address)], }); @@ -580,27 +620,39 @@ describe("test on local testnet", function () { // Let's check the SCRs let transactionOnNetwork = await provider.getTransaction(transactionDeploy.getHash().hex()); - let bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(bundle.returnCode.isSuccess()); + let response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); transactionOnNetwork = await provider.getTransaction(transactionStart.getHash().hex()); - bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(bundle.returnCode.isSuccess()); + response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); // Query state, do some assertions let query = contract.createQuery({ func: new ContractFunction("status"), args: [BytesValue.fromUTF8("lucky")], }); - let queryResponse = await provider.queryContract(query); - assert.equal(decodeUnsignedNumber(queryResponse.getReturnDataParts()[0]), 1); + let queryResponse = await provider.queryContract( + new SmartContractQueryInput({ + contract: query.address, + arguments: query.args, + function: query.func.toString(), + }), + ); + assert.equal(decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0])), 1); query = contract.createQuery({ func: new ContractFunction("status"), args: [BytesValue.fromUTF8("missingLottery")], }); - queryResponse = await provider.queryContract(query); - assert.equal(decodeUnsignedNumber(queryResponse.getReturnDataParts()[0]), 0); + queryResponse = await provider.queryContract( + new SmartContractQueryInput({ + contract: query.address, + arguments: query.args, + function: query.func.toString(), + }), + ); + assert.equal(decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0])), 0); }); it("lottery: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { @@ -663,19 +715,21 @@ describe("test on local testnet", function () { // Let's check the SCRs let transactionOnNetwork = await provider.getTransaction(deployTx); - let bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(bundle.returnCode.isSuccess()); + let response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); transactionOnNetwork = await provider.getTransaction(startTx); - bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); - assert.isTrue(bundle.returnCode.isSuccess()); + response = parser.parseExecute({ transactionOnNetwork }); + assert.isTrue(response.returnCode == "ok"); // Query state, do some assertions - const queryRunner = new QueryRunnerAdapter({ networkProvider: provider }); - const smartContractQueriesController = new SmartContractQueriesController({ queryRunner: queryRunner }); + const smartContractQueriesController = new SmartContractController({ + chainID: "localnet", + networkProvider: provider, + }); let query = smartContractQueriesController.createQuery({ - contract: contractAddress.bech32(), + contract: contractAddress, function: "status", arguments: [BytesValue.fromUTF8("lucky")], }); @@ -683,7 +737,7 @@ describe("test on local testnet", function () { assert.equal(decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0])), 1); query = smartContractQueriesController.createQuery({ - contract: contractAddress.bech32(), + contract: contractAddress, function: "status", arguments: [BytesValue.fromUTF8("missingLottery")], }); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 8ea0481aa..87201fa5e 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -1,6 +1,6 @@ import { assert } from "chai"; import { promises } from "fs"; -import { SmartContractTransactionsFactory } from "../smartContracts"; +import { SmartContractTransactionsFactory, SmartContractTransactionsOutcomeParser } from "../smartContracts"; import { loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { TransactionComputer } from "../transactionComputer"; @@ -13,6 +13,7 @@ describe("fetch transactions from local testnet", function () { let alice: TestWallet; let provider = createLocalnetProvider(); let watcher: TransactionWatcher; + let parser: SmartContractTransactionsOutcomeParser; before(async function () { ({ alice } = await loadTestWallets()); @@ -21,6 +22,8 @@ describe("fetch transactions from local testnet", function () { return await provider.getTransaction(hash); }, }); + + parser = new SmartContractTransactionsOutcomeParser(); }); it("counter smart contract", async function () { @@ -67,11 +70,11 @@ describe("fetch transactions from local testnet", function () { const transactionOnNetworkDeploy = await provider.getTransaction(txHashDeploy); const transactionOnNetworkIncrement = await provider.getTransaction(txHashIncrement); - let bundle = resultsParser.parseUntypedOutcome(transactionOnNetworkDeploy); - assert.isTrue(bundle.returnCode.isSuccess()); + let response = parser.parseExecute({ transactionOnNetwork: transactionOnNetworkDeploy }); + assert.isTrue(response.returnCode == "ok"); - bundle = resultsParser.parseUntypedOutcome(transactionOnNetworkIncrement); - assert.isTrue(bundle.returnCode.isSuccess()); + response = parser.parseExecute({ transactionOnNetwork: transactionOnNetworkIncrement }); + assert.isTrue(response.returnCode == "ok"); }); it("interact with counter smart contract using SmartContractTransactionsFactory", async function () { @@ -124,10 +127,10 @@ describe("fetch transactions from local testnet", function () { let transactionOnNetworkDeploy = await provider.getTransaction(deployTxHash); let transactionOnNetworkIncrement = await provider.getTransaction(callTxHash); - let bundle = resultsParser.parseUntypedOutcome(transactionOnNetworkDeploy); - assert.isTrue(bundle.returnCode.isSuccess()); + let response = parser.parseExecute({ transactionOnNetwork: transactionOnNetworkDeploy }); + assert.isTrue(response.returnCode == "ok"); - bundle = resultsParser.parseUntypedOutcome(transactionOnNetworkIncrement); - assert.isTrue(bundle.returnCode.isSuccess()); + response = parser.parseExecute({ transactionOnNetwork: transactionOnNetworkIncrement }); + assert.isTrue(response.returnCode == "ok"); }); }); diff --git a/src/adapters/index.ts b/src/adapters/index.ts deleted file mode 100644 index e73a1b2d8..000000000 --- a/src/adapters/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./queryRunnerAdapter"; diff --git a/src/adapters/queryRunnerAdapter.ts b/src/adapters/queryRunnerAdapter.ts deleted file mode 100644 index decb29385..000000000 --- a/src/adapters/queryRunnerAdapter.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { IAddress } from "../interface"; -import { IContractQueryResponse } from "../interfaceOfNetwork"; -import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; - -interface INetworkProvider { - queryContract(query: IQuery): Promise; -} - -interface IQuery { - address: IAddress; - caller?: IAddress; - func: { toString(): string }; - value?: { toString(): string }; - getEncodedArguments(): string[]; -} - -export class QueryRunnerAdapter { - private readonly networkProvider: INetworkProvider; - - constructor(options: { networkProvider: INetworkProvider }) { - this.networkProvider = options.networkProvider; - } - - async runQuery(query: SmartContractQuery): Promise { - const adaptedQuery: IQuery = { - address: query.contract, - caller: query.caller ? query.caller : undefined, - func: query.function, - value: query.value, - getEncodedArguments: () => query.arguments.map((arg) => Buffer.from(arg).toString("hex")), - }; - - const adaptedQueryResponse = await this.networkProvider.queryContract(adaptedQuery); - return new SmartContractQueryResponse({ - function: query.function, - returnCode: adaptedQueryResponse.returnCode.toString(), - returnMessage: adaptedQueryResponse.returnMessage, - returnDataParts: adaptedQueryResponse.getReturnDataParts(), - }); - } -} diff --git a/src/index.ts b/src/index.ts index a642376a9..1816c81e1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,7 +9,6 @@ require("./globals"); export * from "./abi"; export * from "./accountManagement"; export * from "./accounts"; -export * from "./adapters"; export * from "./address"; export * from "./asyncTimer"; export * from "./config"; diff --git a/src/networkProviders/contractQueryRequest.ts b/src/networkProviders/contractQueryRequest.ts index d09c01770..2b1f8b0fc 100644 --- a/src/networkProviders/contractQueryRequest.ts +++ b/src/networkProviders/contractQueryRequest.ts @@ -15,7 +15,6 @@ export class ContractQueryRequest { request.funcName = query.function; request.value = query.value ? query.value.toString() : undefined; request.args = query.arguments?.map((x) => Buffer.from(x).toString("hex")); - console.log({ request }); return request; } } diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 379af63e8..1c2cbedef 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -163,8 +163,7 @@ export class ProxyNetworkProvider implements INetworkProvider { try { const request = new ContractQueryRequest(query).toHttpRequest(); const response = await this.doPostGeneric("vm-values/query", request); - console.log(111111, { response }); - return SmartContractQueryResponse.fromHttpResponse(response, query.function); + return SmartContractQueryResponse.fromHttpResponse(response.data, query.function); } catch (error: any) { throw new ErrContractQuery(error); } diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 1bddab6d4..1892c1d6d 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,10 +1,5 @@ -import { IAddress } from "../interface"; -import { IAccountOnNetwork, INetworkConfig, ITransactionStatus } from "../interfaceOfNetwork"; import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; -import { SmartContractQueryInput, SmartContractQueryResponse } from "../smartContractQuery"; - -import { Transaction } from "../transaction"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { INetworkProvider } from "../networkProviders/interface"; export function createLocalnetProvider(): INetworkProvider { return new ProxyNetworkProvider("http://localhost:7950", { timeout: 5000 }); @@ -30,13 +25,3 @@ export function createMainnetProvider(): INetworkProvider { clientName: "mx-sdk-js-core/tests", }); } - -export interface INetworkProvider { - getNetworkConfig(): Promise; - getAccount(address: IAddress): Promise; - getTransaction(txHash: string): Promise; - getTransactionStatus(txHash: string): Promise; - sendTransaction(tx: Transaction): Promise; - simulateTransaction(tx: Transaction): Promise; - queryContract(query: SmartContractQueryInput): Promise; -} From 590831fed7583e983ad169be7d98d018ce1c82cb Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 27 Nov 2024 15:19:56 +0200 Subject: [PATCH 059/214] FIx compiling issue on integration tests --- src/abi/interaction.local.net.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 346a562cd..baa4f5100 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -584,7 +584,7 @@ describe("test smart contract interactor", function () { response = await controller.awaitCompletedExecute(lotteryStatusTxHash); assert.isTrue(response.returnCode == "ok"); assert.lengthOf(response.values, 1); - assert.equal(response[0].name, "Running"); + assert.equal(response.values[0].name, "Running"); // lotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) let lotteryInfoTransaction = getLotteryInfoInteraction @@ -599,7 +599,7 @@ describe("test smart contract interactor", function () { assert.lengthOf(response.values, 1); // Ignore "deadline" field in our test - let info = response[0].valueOf(); + let info = response.values[0].valueOf(); delete info.deadline; assert.deepEqual(info, { From 5ce149785478a237e370418f3f10a9478c6e412b Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 27 Nov 2024 15:38:49 +0200 Subject: [PATCH 060/214] Fix imports --- src/transaction.local.net.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 1ac7e632e..8d8201dd9 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -1,8 +1,9 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Logger } from "./logger"; +import { INetworkProvider } from "./networkProviders/interface"; import { loadTestWallets, TestWallet } from "./testutils"; -import { createLocalnetProvider, INetworkProvider } from "./testutils/networkProviders"; +import { createLocalnetProvider } from "./testutils/networkProviders"; import { TokenTransfer } from "./tokens"; import { Transaction } from "./transaction"; import { TransactionComputer } from "./transactionComputer"; From 6d5fd2193eb0098a7955bd226fac4eb6ad9d153c Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 27 Nov 2024 15:57:55 +0200 Subject: [PATCH 061/214] Fix Method call --- src/smartContracts/smartContractTransactionsOutcomeParser.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 16ca3e906..3187938bc 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -154,7 +154,7 @@ export class SmartContractTransactionsOutcomeParser { for (const result of transactionOnNetwork.smartContractResults) { const matchesCriteriaOnData = result.data.toString().startsWith(ARGUMENTS_SEPARATOR); - const matchesCriteriaOnReceiver = result.receiver.bech32() === transactionOnNetwork.sender.bech32(); + const matchesCriteriaOnReceiver = result.receiver.toBech32() === transactionOnNetwork.sender.toBech32(); const matchesCriteriaOnPreviousHash = result; const matchesCriteria = matchesCriteriaOnData && matchesCriteriaOnReceiver && matchesCriteriaOnPreviousHash; From ce4e18030f1fb4ef4eb70f43163abb4eeba67bf1 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 27 Nov 2024 16:21:08 +0200 Subject: [PATCH 062/214] Fix smartContractResults mapping --- src/abi/interaction.local.net.spec.ts | 2 +- src/abi/interaction.spec.ts | 3 --- .../smartContractTransactionsOutcomeParser.ts | 1 - src/transactionOnNetwork.ts | 17 ++++++++++++++--- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index baa4f5100..fd92cc089 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -17,7 +17,7 @@ import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; import { ManagedDecimalSignedValue, ManagedDecimalValue } from "./typesystem"; -describe("test smart contract interactor", function () { +describe.only("test smart contract interactor", function () { let provider = createLocalnetProvider(); let alice: TestWallet; diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 099013157..468d078a9 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -237,7 +237,6 @@ describe("test smart contract interactor", function () { value: BigInt(interactionQuery.value.toString()), }), ); - console.log(22222, response); assert.isTrue(response.length == 1); assert.deepEqual(response[0], new BigNumber(42)); @@ -271,7 +270,6 @@ describe("test smart contract interactor", function () { let hash = await provider.sendTransaction(transaction); let responseExecute = await controller.awaitCompletedExecute(hash); - console.log(responseExecute, responseExecute.values[0]!.valueOf()); assert.isTrue(responseExecute.values.length == 1); assert.deepEqual(responseExecute.values[0], new BigNumber(43)); assert.isTrue(responseExecute.returnCode == "ok"); @@ -407,7 +405,6 @@ describe("test smart contract interactor", function () { hash = await provider.sendTransaction(startTransaction); response = await controller.awaitCompletedExecute(hash); - console.log({ response }); assert.equal(statusTransaction.getData().toString(), "status@6c75636b79"); assert.isTrue(response.returnCode == "ok"); assert.isTrue(response.values.length == 1); diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 3187938bc..12cdab62d 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -91,7 +91,6 @@ export class SmartContractTransactionsOutcomeParser { functionName?: string, ): resources.ParsedSmartContractCallOutcome { const directCallOutcome = this.findDirectSmartContractCallOutcome(transactionOnNetwork); - console.log({ directCallOutcome, abi: this.abi }); if (!this.abi) { return { values: directCallOutcome.returnDataParts, diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 5b33fa992..10adef8c0 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -72,7 +72,13 @@ export class TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); result.smartContractResults = response.smartContractResults?.map( - (result: Partial) => new SmartContractResult({ ...result, raw: result }), + (result: Partial) => + new SmartContractResult({ + ...result, + receiver: result.receiver ? new Address(result.receiver) : undefined, + sender: result.sender ? new Address(result.sender) : undefined, + raw: result, + }), ) ?? []; if (processStatus) { @@ -87,7 +93,13 @@ export class TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); result.smartContractResults = response.results?.map( - (result: Partial) => new SmartContractResult({ ...result, raw: result }), + (result: Partial) => + new SmartContractResult({ + ...result, + receiver: result.receiver ? new Address(result.receiver) : undefined, + sender: result.sender ? new Address(result.sender) : undefined, + raw: result, + }), ) ?? []; result.isCompleted = !result.status.isPending(); return result; @@ -95,7 +107,6 @@ export class TransactionOnNetwork { private static fromHttpResponse(txHash: string, response: any): TransactionOnNetwork { let result = new TransactionOnNetwork(); - result.hash = txHash; result.type = response.type || ""; result.nonce = response.nonce || 0; From 9f1b195f95a177ebbebf538f23394e52ae7b1b76 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 5 Dec 2024 14:26:43 +0200 Subject: [PATCH 063/214] fix integration tests --- src/abi/interaction.local.net.spec.ts | 23 +++++++++---------- .../smartContractTransactionsOutcomeParser.ts | 2 +- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index fd92cc089..47dd1b787 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -17,7 +17,7 @@ import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; import { ManagedDecimalSignedValue, ManagedDecimalValue } from "./typesystem"; -describe.only("test smart contract interactor", function () { +describe("test smart contract interactor", function () { let provider = createLocalnetProvider(); let alice: TestWallet; @@ -73,7 +73,7 @@ describe.only("test smart contract interactor", function () { }), ); assert.lengthOf(queryResponse, 1); - assert.deepEqual(queryResponse[0]!.valueOf(), new BigNumber(42)); + assert.deepEqual(queryResponse[0], new BigNumber(42)); // Execute, do not wait for execution let transaction = interaction @@ -138,9 +138,8 @@ describe.only("test smart contract interactor", function () { networkProvider: provider, abi: abiRegistry, }); - let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); - let response = queryController.parseExecute(transactionOnNetwork); + let response = queryController.parseDeploy(transactionOnNetwork); assert.isTrue(response.returnCode == "ok"); const query = queryController.createQuery({ @@ -185,10 +184,10 @@ describe.only("test smart contract interactor", function () { const executeTxHash = await provider.sendTransaction(transaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(executeTxHash); - response = queryController.parseExecute(transactionOnNetwork); + const responseD = queryController.parseExecute(transactionOnNetwork); - assert.isTrue(response.values.length == 1); - assert.deepEqual(response.values[0], new BigNumber(42)); + assert.isTrue(response.contracts.length == 1); + assert.deepEqual(responseD.values[0], new BigNumber(42)); assert.isTrue(response.returnCode == "ok"); }); @@ -358,8 +357,8 @@ describe.only("test smart contract interactor", function () { await provider.sendTransaction(deployTransaction); let hash = await provider.sendTransaction(deployTransaction); - let responseExecute = await controller.awaitCompletedExecute(hash); - assert.isTrue(responseExecute.returnCode == "ok"); + let responseDeploy = await controller.awaitCompletedDeploy(hash); + assert.isTrue(responseDeploy.returnCode == "ok"); let incrementInteraction = (contract.methods.increment()) .withGasLimit(3000000) @@ -382,14 +381,14 @@ describe.only("test smart contract interactor", function () { value: BigInt(interactionQuery.value.toString()), }), ); - assert.deepEqual(response[0]!.valueOf(), new BigNumber(1)); + assert.deepEqual(response[0], new BigNumber(1)); // Increment, wait for execution. let incrementTransaction = incrementInteraction.useThenIncrementNonceOf(alice.account).buildTransaction(); await signTransaction({ transaction: incrementTransaction, wallet: alice }); hash = await provider.sendTransaction(incrementTransaction); - responseExecute = await controller.awaitCompletedExecute(hash); + let responseExecute = await controller.awaitCompletedExecute(hash); assert.isTrue(responseExecute.returnCode == "ok"); assert.deepEqual(responseExecute.values[0], new BigNumber(2)); @@ -446,7 +445,7 @@ describe.only("test smart contract interactor", function () { const deployTxHash = await provider.sendTransaction(deployTransaction); let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); - let response = parser.parseExecute({ transactionOnNetwork }); + let response = parser.parseExecute({ transactionOnNetwork, function: "deploy" }); assert.isTrue(response.returnCode == "ok"); const queryController = new SmartContractController({ diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 12cdab62d..f342a78dd 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -100,7 +100,6 @@ export class SmartContractTransactionsOutcomeParser { } functionName = functionName || directCallOutcome.function; - if (!functionName) { throw new Err( `Function name is not available in the transaction, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?`, @@ -121,6 +120,7 @@ export class SmartContractTransactionsOutcomeParser { protected findDirectSmartContractCallOutcome(transactionOnNetwork: TransactionOnNetwork): SmartContractCallOutcome { let outcome = this.findDirectSmartContractCallOutcomeWithinSmartContractResults(transactionOnNetwork); + if (outcome) { return outcome; } From e8726f63aa438fa4477fd22bc9d4561f59aee91c Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 5 Dec 2024 16:13:01 +0200 Subject: [PATCH 064/214] Remove tests that dont use factory as they are duplicated --- src/abi/smartContract.local.net.spec.ts | 366 +----------------------- 1 file changed, 9 insertions(+), 357 deletions(-) diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index c06c15c9d..6a99bde98 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -1,20 +1,17 @@ import { assert } from "chai"; import { promises } from "fs"; import { Logger } from "../logger"; -import { SmartContractQueryInput } from "../smartContractQuery"; import { SmartContractController, SmartContractTransactionsFactory, SmartContractTransactionsOutcomeParser, } from "../smartContracts"; -import { prepareDeployment } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { loadTestWallets, TestWallet } from "../testutils/wallets"; import { TransactionComputer } from "../transactionComputer"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { decodeUnsignedNumber } from "./codec"; -import { ContractFunction } from "./function"; import { SmartContract } from "./smartContract"; import { AddressValue, @@ -43,82 +40,6 @@ describe("test on local testnet", function () { parser = new SmartContractTransactionsOutcomeParser(); }); - it("counter: should deploy, then simulate transactions", async function () { - this.timeout(60000); - - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - - let network = await provider.getNetworkConfig(); - await alice.sync(provider); - - // Deploy - let contract = new SmartContract({}); - - let transactionDeploy = await prepareDeployment({ - contract: contract, - deployer: alice, - codePath: "src/testdata/counter.wasm", - gasLimit: 3000000, - initArguments: [], - chainID: network.ChainID, - }); - - // ++ - let transactionIncrement = contract.call({ - func: new ContractFunction("increment"), - gasLimit: 3000000, - chainID: network.ChainID, - caller: alice.address, - }); - transactionIncrement.setNonce(alice.account.nonce); - transactionIncrement.applySignature(await alice.signer.sign(transactionIncrement.serializeForSigning())); - - alice.account.incrementNonce(); - - // Now, let's build a few transactions, to be simulated - let simulateOne = contract.call({ - func: new ContractFunction("increment"), - gasLimit: 100000, - chainID: network.ChainID, - caller: alice.address, - }); - simulateOne.setSender(alice.address); - - let simulateTwo = contract.call({ - func: new ContractFunction("foobar"), - gasLimit: 500000, - chainID: network.ChainID, - caller: alice.address, - }); - simulateTwo.setSender(alice.address); - - simulateOne.setNonce(alice.account.nonce); - simulateTwo.setNonce(alice.account.nonce); - - simulateOne.applySignature(await alice.signer.sign(simulateOne.serializeForSigning())); - simulateTwo.applySignature(await alice.signer.sign(simulateTwo.serializeForSigning())); - - // Broadcast & execute - const txHashDeploy = await provider.sendTransaction(transactionDeploy); - const txHashIncrement = await provider.sendTransaction(transactionIncrement); - - await watcher.awaitCompleted(txHashDeploy); - let transactionOnNetwork = await provider.getTransaction(txHashDeploy); - let response = parser.parseExecute({ transactionOnNetwork }); - - assert.isTrue(response.returnCode == "ok"); - - await watcher.awaitCompleted(txHashIncrement); - transactionOnNetwork = await provider.getTransaction(txHashIncrement); - response = parser.parseExecute({ transactionOnNetwork }); - assert.isTrue(response.returnCode == "ok"); - - // Simulate - Logger.trace(JSON.stringify(await provider.simulateTransaction(simulateOne), null, 4)); - Logger.trace(JSON.stringify(await provider.simulateTransaction(simulateTwo), null, 4)); - }); - it("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { this.timeout(60000); @@ -205,77 +126,6 @@ describe("test on local testnet", function () { Logger.trace(JSON.stringify(await provider.simulateTransaction(simulateTwo), null, 4)); }); - it("counter: should deploy, call and query contract", async function () { - this.timeout(80000); - - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - - let network = await provider.getNetworkConfig(); - await alice.sync(provider); - - // Deploy - let contract = new SmartContract({}); - - let transactionDeploy = await prepareDeployment({ - contract: contract, - deployer: alice, - codePath: "src/testdata/counter.wasm", - gasLimit: 3000000, - initArguments: [], - chainID: network.ChainID, - }); - - // ++ - let transactionIncrementFirst = contract.call({ - func: new ContractFunction("increment"), - gasLimit: 2000000, - chainID: network.ChainID, - caller: alice.address, - }); - transactionIncrementFirst.setNonce(alice.account.nonce); - transactionIncrementFirst.applySignature( - await alice.signer.sign(transactionIncrementFirst.serializeForSigning()), - ); - - alice.account.incrementNonce(); - - // ++ - let transactionIncrementSecond = contract.call({ - func: new ContractFunction("increment"), - gasLimit: 2000000, - chainID: network.ChainID, - caller: alice.address, - }); - transactionIncrementSecond.setNonce(alice.account.nonce); - transactionIncrementSecond.applySignature( - await alice.signer.sign(transactionIncrementSecond.serializeForSigning()), - ); - - alice.account.incrementNonce(); - - // Broadcast & execute - await provider.sendTransaction(transactionDeploy); - await provider.sendTransaction(transactionIncrementFirst); - await provider.sendTransaction(transactionIncrementSecond); - - await watcher.awaitCompleted(transactionDeploy.getHash().hex()); - await watcher.awaitCompleted(transactionIncrementFirst.getHash().hex()); - await watcher.awaitCompleted(transactionIncrementSecond.getHash().hex()); - - // Check counter - let query = contract.createQuery({ func: new ContractFunction("get") }); - let queryResponse = await provider.queryContract( - new SmartContractQueryInput({ - contract: query.address, - arguments: query.args, - function: query.func.toString(), - }), - ); - assert.isTrue(queryResponse.returnDataParts.length == 1); - assert.equal(3, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); - }); - it("counter: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { this.timeout(80000); @@ -354,116 +204,6 @@ describe("test on local testnet", function () { assert.equal(3, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); }); - it("erc20: should deploy, call and query contract", async function () { - this.timeout(60000); - - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - - let network = await provider.getNetworkConfig(); - await alice.sync(provider); - - // Deploy - let contract = new SmartContract({}); - - let transactionDeploy = await prepareDeployment({ - contract: contract, - deployer: alice, - codePath: "src/testdata/erc20.wasm", - gasLimit: 50000000, - initArguments: [new U32Value(10000)], - chainID: network.ChainID, - }); - - // Minting - let transactionMintBob = contract.call({ - func: new ContractFunction("transferToken"), - gasLimit: 9000000, - args: [new AddressValue(bob.address), new U32Value(1000)], - chainID: network.ChainID, - caller: alice.address, - }); - - let transactionMintCarol = contract.call({ - func: new ContractFunction("transferToken"), - gasLimit: 9000000, - args: [new AddressValue(carol.address), new U32Value(1500)], - chainID: network.ChainID, - caller: alice.address, - }); - - // Apply nonces and sign the remaining transactions - transactionMintBob.setNonce(alice.account.nonce); - alice.account.incrementNonce(); - transactionMintCarol.setNonce(alice.account.nonce); - alice.account.incrementNonce(); - - transactionMintBob.applySignature(await alice.signer.sign(transactionMintBob.serializeForSigning())); - transactionMintCarol.applySignature(await alice.signer.sign(transactionMintCarol.serializeForSigning())); - - // Broadcast & execute - await provider.sendTransaction(transactionDeploy); - await provider.sendTransaction(transactionMintBob); - await provider.sendTransaction(transactionMintCarol); - - await watcher.awaitCompleted(transactionDeploy.getHash().hex()); - await watcher.awaitCompleted(transactionMintBob.getHash().hex()); - await watcher.awaitCompleted(transactionMintCarol.getHash().hex()); - - // Query state, do some assertions - let query = contract.createQuery({ func: new ContractFunction("totalSupply") }); - let queryResponse = await provider.queryContract( - new SmartContractQueryInput({ - contract: query.address, - arguments: query.args, - function: query.func.toString(), - }), - ); - assert.isTrue(queryResponse.returnDataParts.length == 1); - assert.equal(10000, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); - - query = contract.createQuery({ - func: new ContractFunction("balanceOf"), - args: [new AddressValue(alice.address)], - }); - queryResponse = await provider.queryContract( - new SmartContractQueryInput({ - contract: query.address, - arguments: query.args, - function: query.func.toString(), - }), - ); - assert.equal(7500, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); - - query = contract.createQuery({ - func: new ContractFunction("balanceOf"), - args: [new AddressValue(bob.address)], - }); - queryResponse = await provider.queryContract( - new SmartContractQueryInput({ - contract: query.address, - arguments: query.args, - function: query.func.toString(), - }), - ); - - assert.equal(1000, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); - - query = contract.createQuery({ - func: new ContractFunction("balanceOf"), - args: [new AddressValue(carol.address)], - }); - queryResponse = await provider.queryContract( - new SmartContractQueryInput({ - contract: query.address, - arguments: query.args, - function: query.func.toString(), - }), - ); - - assert.equal(1500, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); - }); - it("erc20: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { this.timeout(60000); @@ -528,133 +268,45 @@ describe("test on local testnet", function () { await watcher.awaitCompleted(mintCarolTxHash); // Query state, do some assertions - const smartContractQueriesController = new SmartContractController({ + const smartContractController = new SmartContractController({ chainID: "localnet", networkProvider: provider, }); - let query = smartContractQueriesController.createQuery({ + let query = smartContractController.createQuery({ contract: contractAddress, function: "totalSupply", arguments: [], }); - let queryResponse = await smartContractQueriesController.runQuery(query); + let queryResponse = await smartContractController.runQuery(query); assert.lengthOf(queryResponse.returnDataParts, 1); assert.equal(10000, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); - query = smartContractQueriesController.createQuery({ + query = smartContractController.createQuery({ contract: contractAddress, function: "balanceOf", arguments: [new AddressValue(alice.address)], }); - queryResponse = await smartContractQueriesController.runQuery(query); + queryResponse = await smartContractController.runQuery(query); assert.equal(7500, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); - query = smartContractQueriesController.createQuery({ + query = smartContractController.createQuery({ contract: contractAddress, function: "balanceOf", arguments: [new AddressValue(bob.address)], }); - queryResponse = await smartContractQueriesController.runQuery(query); + queryResponse = await smartContractController.runQuery(query); assert.equal(1000, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); - query = smartContractQueriesController.createQuery({ + query = smartContractController.createQuery({ contract: contractAddress, function: "balanceOf", arguments: [new AddressValue(carol.address)], }); - queryResponse = await smartContractQueriesController.runQuery(query); + queryResponse = await smartContractController.runQuery(query); assert.equal(1500, decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0]))); }); - it("lottery: should deploy, call and query contract", async function () { - this.timeout(60000); - - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - - let network = await provider.getNetworkConfig(); - await alice.sync(provider); - - // Deploy - let contract = new SmartContract({}); - - let transactionDeploy = await prepareDeployment({ - contract: contract, - deployer: alice, - codePath: "src/testdata/lottery-esdt.wasm", - gasLimit: 50000000, - initArguments: [], - chainID: network.ChainID, - }); - - // Start - let transactionStart = contract.call({ - func: new ContractFunction("start"), - gasLimit: 10000000, - args: [ - BytesValue.fromUTF8("lucky"), - new TokenIdentifierValue("EGLD"), - new BigUIntValue(1), - OptionValue.newMissing(), - OptionValue.newMissing(), - OptionValue.newProvided(new U32Value(1)), - OptionValue.newMissing(), - OptionValue.newMissing(), - OptionalValue.newMissing(), - ], - chainID: network.ChainID, - caller: alice.address, - }); - // Apply nonces and sign the remaining transactions - transactionStart.setNonce(alice.account.nonce); - - transactionStart.applySignature(await alice.signer.sign(transactionStart.serializeForSigning())); - - // Broadcast & execute - await provider.sendTransaction(transactionDeploy); - await provider.sendTransaction(transactionStart); - - await watcher.awaitAllEvents(transactionDeploy.getHash().hex(), ["SCDeploy"]); - await watcher.awaitAnyEvent(transactionStart.getHash().hex(), ["completedTxEvent"]); - - // Let's check the SCRs - let transactionOnNetwork = await provider.getTransaction(transactionDeploy.getHash().hex()); - let response = parser.parseExecute({ transactionOnNetwork }); - assert.isTrue(response.returnCode == "ok"); - - transactionOnNetwork = await provider.getTransaction(transactionStart.getHash().hex()); - response = parser.parseExecute({ transactionOnNetwork }); - assert.isTrue(response.returnCode == "ok"); - - // Query state, do some assertions - let query = contract.createQuery({ - func: new ContractFunction("status"), - args: [BytesValue.fromUTF8("lucky")], - }); - let queryResponse = await provider.queryContract( - new SmartContractQueryInput({ - contract: query.address, - arguments: query.args, - function: query.func.toString(), - }), - ); - assert.equal(decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0])), 1); - - query = contract.createQuery({ - func: new ContractFunction("status"), - args: [BytesValue.fromUTF8("missingLottery")], - }); - queryResponse = await provider.queryContract( - new SmartContractQueryInput({ - contract: query.address, - arguments: query.args, - function: query.func.toString(), - }), - ); - assert.equal(decodeUnsignedNumber(Buffer.from(queryResponse.returnDataParts[0])), 0); - }); - it("lottery: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { this.timeout(60000); From 915973c0e7ac77e9b1270c015d1cbc7808341b56 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 5 Dec 2024 16:50:39 +0200 Subject: [PATCH 065/214] Fix tests --- src/abi/interaction.local.net.spec.ts | 257 +------------------------- 1 file changed, 4 insertions(+), 253 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 47dd1b787..2ab0b84d9 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -1,7 +1,6 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { promises } from "fs"; -import { SmartContractQueryInput } from "../smartContractQuery"; import { SmartContractController, SmartContractTransactionsFactory, @@ -17,7 +16,7 @@ import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; import { ManagedDecimalSignedValue, ManagedDecimalValue } from "./typesystem"; -describe("test smart contract interactor", function () { +describe.only("test smart contract interactor", function () { let provider = createLocalnetProvider(); let alice: TestWallet; @@ -25,76 +24,6 @@ describe("test smart contract interactor", function () { ({ alice } = await loadTestWallets()); }); - it("should interact with 'answer' (local testnet)", async function () { - this.timeout(80000); - - let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); - let contract = new SmartContract({ abi: abiRegistry }); - let controller = new SmartContractController({ - chainID: "localnet", - networkProvider: provider, - abi: abiRegistry, - }); - - let network = await provider.getNetworkConfig(); - await alice.sync(provider); - - // Deploy the contract - let deployTransaction = await prepareDeployment({ - contract: contract, - deployer: alice, - codePath: "src/testdata/answer.wasm", - gasLimit: 3000000, - initArguments: [], - chainID: network.ChainID, - }); - - let deployTxHash = await provider.sendTransaction(deployTransaction); - let deployResponse = await controller.awaitCompletedDeploy(deployTxHash); - assert.isTrue(deployResponse.returnCode == "ok"); - - const interaction = ( - contract.methods - .getUltimateAnswer() - .withGasLimit(3000000) - .withChainID(network.ChainID) - .withSender(alice.address) - ); - const interactionQuery = interaction.buildQuery(); - - // Query - const queryResponse = await controller.query( - new SmartContractQueryInput({ - contract: interactionQuery.address, - arguments: interactionQuery.getEncodedArguments(), - function: interactionQuery.func.toString(), - caller: interactionQuery.caller, - value: BigInt(interactionQuery.value.toString()), - }), - ); - assert.lengthOf(queryResponse, 1); - assert.deepEqual(queryResponse[0], new BigNumber(42)); - - // Execute, do not wait for execution - let transaction = interaction - .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) - .buildTransaction(); - - await signTransaction({ transaction: transaction, wallet: alice }); - await provider.sendTransaction(transaction); - - // Execute, and wait for execution - transaction = interaction.withSender(alice.address).useThenIncrementNonceOf(alice.account).buildTransaction(); - - await signTransaction({ transaction: transaction, wallet: alice }); - let txHash = await provider.sendTransaction(transaction); - let response = await controller.awaitCompletedExecute(txHash); - assert.isTrue(response.returnCode == "ok"); - assert.lengthOf(response.values, 1); - assert.deepEqual(response.values[0], new BigNumber(42)); - }); - it("should interact with 'answer' (local testnet) using the SmartContractTransactionsFactory", async function () { this.timeout(80000); @@ -331,81 +260,6 @@ describe("test smart contract interactor", function () { assert.deepEqual(response.values[0], new ManagedDecimalSignedValue("3.135553845", 9)); }); - it("should interact with 'counter' (local testnet)", async function () { - this.timeout(120000); - - let abiRegistry = await loadAbiRegistry("src/testdata/counter.abi.json"); - let contract = new SmartContract({ abi: abiRegistry }); - let controller = new SmartContractController({ - chainID: "localnet", - networkProvider: provider, - abi: abiRegistry, - }); - - let network = await provider.getNetworkConfig(); - await alice.sync(provider); - - // Deploy the contract - let deployTransaction = await prepareDeployment({ - contract: contract, - deployer: alice, - codePath: "src/testdata/counter.wasm", - gasLimit: 3000000, - initArguments: [], - chainID: network.ChainID, - }); - - await provider.sendTransaction(deployTransaction); - let hash = await provider.sendTransaction(deployTransaction); - let responseDeploy = await controller.awaitCompletedDeploy(hash); - assert.isTrue(responseDeploy.returnCode == "ok"); - - let incrementInteraction = (contract.methods.increment()) - .withGasLimit(3000000) - .withChainID(network.ChainID) - .withSender(alice.address); - let decrementInteraction = (contract.methods.decrement()) - .withGasLimit(3000000) - .withChainID(network.ChainID) - .withSender(alice.address); - - // Query "get()" - - let interactionQuery = incrementInteraction.buildQuery(); - let response = await controller.query( - new SmartContractQueryInput({ - contract: interactionQuery.address, - arguments: interactionQuery.getEncodedArguments(), - function: interactionQuery.func.toString(), - caller: interactionQuery.caller, - value: BigInt(interactionQuery.value.toString()), - }), - ); - assert.deepEqual(response[0], new BigNumber(1)); - - // Increment, wait for execution. - let incrementTransaction = incrementInteraction.useThenIncrementNonceOf(alice.account).buildTransaction(); - await signTransaction({ transaction: incrementTransaction, wallet: alice }); - - hash = await provider.sendTransaction(incrementTransaction); - let responseExecute = await controller.awaitCompletedExecute(hash); - assert.isTrue(responseExecute.returnCode == "ok"); - assert.deepEqual(responseExecute.values[0], new BigNumber(2)); - - // Decrement twice. Wait for execution of the second transaction. - let decrementTransaction = decrementInteraction.useThenIncrementNonceOf(alice.account).buildTransaction(); - await signTransaction({ transaction: decrementTransaction, wallet: alice }); - await provider.sendTransaction(decrementTransaction); - - decrementTransaction = decrementInteraction.useThenIncrementNonceOf(alice.account).buildTransaction(); - - await signTransaction({ transaction: decrementTransaction, wallet: alice }); - hash = await provider.sendTransaction(decrementTransaction); - responseExecute = await controller.awaitCompletedExecute(hash); - assert.isTrue(responseExecute.returnCode == "ok"); - assert.deepEqual(responseExecute.values[0], new BigNumber(0)); - }); - it("should interact with 'counter' (local testnet) using the SmartContractTransactionsFactory", async function () { this.timeout(120000); @@ -481,7 +335,7 @@ describe("test smart contract interactor", function () { transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(incrementTxHash); response = parser.parseExecute({ transactionOnNetwork }); - assert.deepEqual(response.values[0], new BigNumber(2)); + assert.deepEqual(response.values[0].valueOf(), new BigNumber(2)); let decrementTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -507,110 +361,6 @@ describe("test smart contract interactor", function () { response = parser.parseExecute({ transactionOnNetwork }); }); - it("should interact with 'lottery-esdt' (local testnet)", async function () { - this.timeout(140000); - - let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); - let contract = new SmartContract({ abi: abiRegistry }); - let controller = new SmartContractController({ - chainID: "localnet", - networkProvider: provider, - abi: abiRegistry, - }); - - let network = await provider.getNetworkConfig(); - await alice.sync(provider); - - // Deploy the contract - let deployTransaction = await prepareDeployment({ - contract: contract, - deployer: alice, - codePath: "src/testdata/lottery-esdt.wasm", - gasLimit: 100000000, - initArguments: [], - chainID: network.ChainID, - }); - - const deployTxHash = await provider.sendTransaction(deployTransaction); - let parsedResponse = await controller.awaitCompletedDeploy(deployTxHash); - - assert.isTrue(parsedResponse.returnCode == "ok"); - - let startInteraction = ( - contract.methods - .start(["lucky", "EGLD", 1, null, null, 1, null, null]) - .withGasLimit(30000000) - .withChainID(network.ChainID) - .withSender(alice.address) - ); - - let lotteryStatusInteraction = ( - contract.methods - .status(["lucky"]) - .withGasLimit(5000000) - .withChainID(network.ChainID) - .withSender(alice.address) - ); - - let getLotteryInfoInteraction = ( - contract.methods - .getLotteryInfo(["lucky"]) - .withGasLimit(5000000) - .withChainID(network.ChainID) - .withSender(alice.address) - ); - - // start() - let startTransaction = startInteraction - .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) - .buildTransaction(); - - await signTransaction({ transaction: startTransaction, wallet: alice }); - const startTxHash = await provider.sendTransaction(startTransaction); - let response = await controller.awaitCompletedExecute(startTxHash); - assert.isTrue(response.returnCode == "ok"); - assert.lengthOf(response.values, 0); - - // status() - let lotteryStatusTransaction = lotteryStatusInteraction - .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) - .buildTransaction(); - - await signTransaction({ transaction: lotteryStatusTransaction, wallet: alice }); - const lotteryStatusTxHash = await provider.sendTransaction(lotteryStatusTransaction); - response = await controller.awaitCompletedExecute(lotteryStatusTxHash); - assert.isTrue(response.returnCode == "ok"); - assert.lengthOf(response.values, 1); - assert.equal(response.values[0].name, "Running"); - - // lotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) - let lotteryInfoTransaction = getLotteryInfoInteraction - .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) - .buildTransaction(); - - await signTransaction({ transaction: lotteryInfoTransaction, wallet: alice }); - const lotteryInfoTxHash = await provider.sendTransaction(lotteryInfoTransaction); - response = await controller.awaitCompletedExecute(lotteryInfoTxHash); - assert.isTrue(response.returnCode == "ok"); - assert.lengthOf(response.values, 1); - - // Ignore "deadline" field in our test - let info = response.values[0].valueOf(); - delete info.deadline; - - assert.deepEqual(info, { - token_identifier: "EGLD", - ticket_price: new BigNumber("1"), - tickets_left: new BigNumber(800), - max_entries_per_user: new BigNumber(1), - prize_distribution: Buffer.from([0x64]), - prize_pool: new BigNumber("0"), - }); - }); - it("should interact with 'lottery-esdt' (local testnet) using the SmartContractTransactionsFactory", async function () { this.timeout(140000); @@ -692,7 +442,8 @@ describe("test smart contract interactor", function () { transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(statusTxHash); response = parser.parseExecute({ transactionOnNetwork }); assert.isTrue(response.returnCode == "ok"); - assert.lengthOf(response.values, 0); + assert.lengthOf(response.values, 1); + console.log(response.values[0].valueOf()); assert.equal(response.values[0].name, "Running"); // getlotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) From fa2b75a71870201b10fbd521ead33cf3ab517749 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 9 Dec 2024 14:29:54 +0200 Subject: [PATCH 066/214] Fix integration tests --- src/abi/interaction.local.net.spec.ts | 29 +++++++++++++-------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 2ab0b84d9..298117045 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -14,9 +14,9 @@ import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; -import { ManagedDecimalSignedValue, ManagedDecimalValue } from "./typesystem"; +import { ManagedDecimalValue } from "./typesystem"; -describe.only("test smart contract interactor", function () { +describe("test smart contract interactor", function () { let provider = createLocalnetProvider(); let alice: TestWallet; @@ -224,7 +224,7 @@ describe.only("test smart contract interactor", function () { let response = await controller.awaitCompletedExecute(txHash); assert.isTrue(response.returnCode == "ok"); assert.lengthOf(response.values, 1); - assert.deepEqual(response.values[0], new ManagedDecimalValue("0.000000000000000001", 18)); + assert.deepEqual(response.values[0], new BigNumber("0.000000000000000001")); // addition with const decimals() await signTransaction({ transaction: additionTransaction, wallet: alice }); @@ -232,7 +232,7 @@ describe.only("test smart contract interactor", function () { response = await controller.awaitCompletedExecute(txHash); assert.isTrue(response.returnCode == "ok"); assert.lengthOf(response.values, 1); - assert.deepEqual(response.values[0], new ManagedDecimalValue("5.2", 2)); + assert.deepEqual(response.values[0], new BigNumber("5.2")); // log await signTransaction({ transaction: mdLnTransaction, wallet: alice }); @@ -241,7 +241,7 @@ describe.only("test smart contract interactor", function () { assert.isTrue(response.returnCode == "ok"); assert.lengthOf(response.values, 1); - assert.deepEqual(response.values[0], new ManagedDecimalSignedValue("3.135553845", 9)); + assert.deepEqual(response.values[0], new BigNumber("3.135553845")); // addition with var decimals await signTransaction({ transaction: additionVarTransaction, wallet: alice }); @@ -249,7 +249,7 @@ describe.only("test smart contract interactor", function () { response = await controller.awaitCompletedExecute(txHash); assert.isTrue(response.returnCode == "ok"); assert.lengthOf(response.values, 1); - assert.deepEqual(response.values[0], new ManagedDecimalValue("9", 2)); + assert.deepEqual(response.values[0], new BigNumber("9")); // log await signTransaction({ transaction: lnVarTransaction, wallet: alice }); @@ -257,7 +257,7 @@ describe.only("test smart contract interactor", function () { response = await controller.awaitCompletedExecute(txHash); assert.isTrue(response.returnCode == "ok"); assert.lengthOf(response.values, 1); - assert.deepEqual(response.values[0], new ManagedDecimalSignedValue("3.135553845", 9)); + assert.deepEqual(response.values[0], new BigNumber("3.135553845")); }); it("should interact with 'counter' (local testnet) using the SmartContractTransactionsFactory", async function () { @@ -273,7 +273,7 @@ describe.only("test smart contract interactor", function () { config: config, abi: abiRegistry, }); - const parser = new SmartContractTransactionsOutcomeParser(); + const parser = new SmartContractTransactionsOutcomeParser({ abi: abiRegistry }); const bytecode = await promises.readFile("src/testdata/counter.wasm"); @@ -299,8 +299,8 @@ describe.only("test smart contract interactor", function () { const deployTxHash = await provider.sendTransaction(deployTransaction); let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); - let response = parser.parseExecute({ transactionOnNetwork, function: "deploy" }); - assert.isTrue(response.returnCode == "ok"); + const deployResponse = parser.parseDeploy({ transactionOnNetwork }); + assert.isTrue(deployResponse.returnCode == "ok"); const queryController = new SmartContractController({ chainID: "localnet", @@ -334,8 +334,8 @@ describe.only("test smart contract interactor", function () { const incrementTxHash = await provider.sendTransaction(incrementTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(incrementTxHash); - response = parser.parseExecute({ transactionOnNetwork }); - assert.deepEqual(response.values[0].valueOf(), new BigNumber(2)); + let response = parser.parseExecute({ transactionOnNetwork }); + assert.deepEqual(response.values[0], new BigNumber(2)); let decrementTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -365,7 +365,7 @@ describe.only("test smart contract interactor", function () { this.timeout(140000); let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); - let parser = new SmartContractTransactionsOutcomeParser(); + let parser = new SmartContractTransactionsOutcomeParser({ abi: abiRegistry }); let network = await provider.getNetworkConfig(); await alice.sync(provider); @@ -443,7 +443,6 @@ describe.only("test smart contract interactor", function () { response = parser.parseExecute({ transactionOnNetwork }); assert.isTrue(response.returnCode == "ok"); assert.lengthOf(response.values, 1); - console.log(response.values[0].valueOf()); assert.equal(response.values[0].name, "Running"); // getlotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) @@ -464,7 +463,7 @@ describe.only("test smart contract interactor", function () { transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(infoTxHash); response = parser.parseExecute({ transactionOnNetwork }); assert.isTrue(response.returnCode == "ok"); - assert.lengthOf(response.values, 0); + assert.lengthOf(response.values, 1); // Ignore "deadline" field in our test let info = response.values[0]!.valueOf(); From 17177ac15bc9784c3153ec36d7fb70941ba81cec Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 9 Dec 2024 16:03:39 +0200 Subject: [PATCH 067/214] Pass INetworkProvider where needed --- src/entrypoints/entrypoints.ts | 5 +++-- src/smartContracts/smartContractController.ts | 9 ++------- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 713779c54..76e722548 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -6,6 +6,7 @@ import { DelegationController } from "../delegation"; import { ErrInvalidNetworkProviderKind } from "../errors"; import { Message, MessageComputer } from "../message"; import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; +import { INetworkProvider } from "../networkProviders/interface"; import { RelayedController } from "../relayed/relayedController"; import { SmartContractController } from "../smartContracts/smartContractController"; import { TokenManagementController } from "../tokenManagement"; @@ -18,7 +19,7 @@ import { UserVerifier } from "../wallet"; import { DevnetEntrypointConfig, MainnetEntrypointConfig, TestnetEntrypointConfig } from "./config"; class NetworkEntrypoint { - private networkProvider: ApiNetworkProvider | ProxyNetworkProvider; + private networkProvider: INetworkProvider; private chainId: string; constructor(options: { networkProviderUrl: string; networkProviderKind: string; chainId: string }) { @@ -80,7 +81,7 @@ class NetworkEntrypoint { return transactionAwaiter.awaitCompleted(txHash); } - createNetworkProvider(): ApiNetworkProvider | ProxyNetworkProvider { + createNetworkProvider(): INetworkProvider { return this.networkProvider; } diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index 8b6744e74..cbe495623 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -1,7 +1,6 @@ import { AbiRegistry, ArgSerializer, isTyped, NativeSerializer } from "../abi"; import { IAccount } from "../accounts/interfaces"; import { Err, ErrSmartContractQuery } from "../errors"; -import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { INetworkProvider } from "../networkProviders/interface"; import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../smartContractQuery"; import { Transaction } from "../transaction"; @@ -18,14 +17,10 @@ export class SmartContractController { private parser: SmartContractTransactionsOutcomeParser; private transactionWatcher: TransactionWatcher; private txComputer: TransactionComputer; - private networkProvider: ApiNetworkProvider | ProxyNetworkProvider | INetworkProvider; + private networkProvider: INetworkProvider; private abi?: AbiRegistry; - constructor(options: { - chainID: string; - networkProvider: ApiNetworkProvider | ProxyNetworkProvider | INetworkProvider; - abi?: AbiRegistry; - }) { + constructor(options: { chainID: string; networkProvider: INetworkProvider; abi?: AbiRegistry }) { this.factory = new SmartContractTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: options.chainID }), abi: options.abi, From e8aa3e2f55994db4c85ab74fbe416b1aa29bf404 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 9 Dec 2024 16:08:09 +0200 Subject: [PATCH 068/214] Remove deprecated code --- src/abi/index.ts | 2 - src/abi/interaction.spec.ts | 31 ++- src/abi/interaction.ts | 9 - src/abi/interactionChecker.spec.ts | 85 ------ src/abi/interactionChecker.ts | 59 ---- src/abi/transactionPayloadBuilders.spec.ts | 47 ---- src/abi/transactionPayloadBuilders.ts | 174 ------------ src/accounts/account.ts | 22 +- src/address.ts | 21 -- src/constants.ts | 25 -- src/gasEstimator.spec.ts | 42 --- src/gasEstimator.ts | 74 ----- src/index.ts | 4 - src/interface.ts | 5 - src/networkProviders/apiNetworkProvider.ts | 9 +- src/networkProviders/interface.ts | 15 +- .../providers.dev.net.spec.ts | 104 +++---- src/networkProviders/proxyNetworkProvider.ts | 9 +- src/relayedTransactionV1Builder.spec.ts | 260 ------------------ src/relayedTransactionV1Builder.ts | 173 ------------ src/relayedTransactionV2Builder.spec.ts | 94 ------- src/relayedTransactionV2Builder.ts | 122 -------- src/signableMessage.spec.ts | 34 --- src/signableMessage.ts | 81 ------ src/testutils/mockNetworkProvider.ts | 5 +- src/testutils/wallets.ts | 2 +- src/tokenTransferBuilders.spec.ts | 57 ---- src/tokenTransferBuilders.ts | 109 -------- src/tokens.ts | 14 - src/transactionOnNetwork.ts | 8 +- 30 files changed, 80 insertions(+), 1616 deletions(-) delete mode 100644 src/abi/interactionChecker.spec.ts delete mode 100644 src/abi/interactionChecker.ts delete mode 100644 src/abi/transactionPayloadBuilders.spec.ts delete mode 100644 src/abi/transactionPayloadBuilders.ts delete mode 100644 src/gasEstimator.spec.ts delete mode 100644 src/gasEstimator.ts delete mode 100644 src/relayedTransactionV1Builder.spec.ts delete mode 100644 src/relayedTransactionV1Builder.ts delete mode 100644 src/relayedTransactionV2Builder.spec.ts delete mode 100644 src/relayedTransactionV2Builder.ts delete mode 100644 src/signableMessage.spec.ts delete mode 100644 src/signableMessage.ts delete mode 100644 src/tokenTransferBuilders.spec.ts delete mode 100644 src/tokenTransferBuilders.ts diff --git a/src/abi/index.ts b/src/abi/index.ts index 58a6a1f79..c07177226 100644 --- a/src/abi/index.ts +++ b/src/abi/index.ts @@ -4,11 +4,9 @@ export * from "./codec"; export * from "./codeMetadata"; export * from "./function"; export * from "./interaction"; -export * from "./interactionChecker"; export * from "./interface"; export * from "./nativeSerializer"; export * from "./query"; export * from "./returnCode"; export * from "./smartContract"; -export * from "./transactionPayloadBuilders"; export * from "./typesystem"; diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 468d078a9..75418b317 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -282,7 +282,7 @@ describe("test smart contract interactor", function () { let contract = new SmartContract({ address: dummyAddress, abi: abi }); let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abi }); - let getInteraction = contract.methodsExplicit.get().check(); + let getInteraction = contract.methodsExplicit.get(); let incrementInteraction = (contract.methods.increment()).withGasLimit(543210); let decrementInteraction = (contract.methods.decrement()).withGasLimit(987654); @@ -353,20 +353,21 @@ describe("test smart contract interactor", function () { let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry }); - let startInteraction = contract.methodsExplicit - .start([ - BytesValue.fromUTF8("lucky"), - new TokenIdentifierValue("lucky-token"), - new BigUIntValue(1), - OptionValue.newMissing(), - OptionValue.newMissing(), - OptionValue.newProvided(new U32Value(1)), - OptionValue.newMissing(), - OptionValue.newMissing(), - OptionalValue.newMissing(), - ]) - .withGasLimit(5000000) - .check(); + let startInteraction = ( + contract.methodsExplicit + .start([ + BytesValue.fromUTF8("lucky"), + new TokenIdentifierValue("lucky-token"), + new BigUIntValue(1), + OptionValue.newMissing(), + OptionValue.newMissing(), + OptionValue.newProvided(new U32Value(1)), + OptionValue.newMissing(), + OptionValue.newMissing(), + OptionalValue.newMissing(), + ]) + .withGasLimit(5000000) + ); let statusInteraction = contract.methods.status(["lucky"]).withGasLimit(5000000); diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index d11edf864..2726cb3c1 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -8,7 +8,6 @@ import { TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { ContractFunction } from "./function"; -import { InteractionChecker } from "./interactionChecker"; import { CallArguments } from "./interface"; import { Query } from "./query"; import { EndpointDefinition, TypedValue } from "./typesystem"; @@ -195,12 +194,4 @@ export class Interaction { this.explicitReceiver = receiver; return this; } - - /** - * To perform custom checking, extend {@link Interaction} and override this method. - */ - check(): Interaction { - new InteractionChecker().checkInteraction(this, this.getEndpoint()); - return this; - } } diff --git a/src/abi/interactionChecker.spec.ts b/src/abi/interactionChecker.spec.ts deleted file mode 100644 index caabab429..000000000 --- a/src/abi/interactionChecker.spec.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { assert } from "chai"; -import { Address } from "../address"; -import * as errors from "../errors"; -import { loadAbiRegistry } from "../testutils"; -import { TokenTransfer } from "../tokens"; -import { Interaction } from "./interaction"; -import { InteractionChecker } from "./interactionChecker"; -import { SmartContract } from "./smartContract"; -import { - BigUIntType, - BigUIntValue, - BytesValue, - OptionalType, - OptionalValue, - OptionValue, - TokenIdentifierValue, - U32Value, -} from "./typesystem"; - -describe("integration tests: test checker within interactor", function () { - let dummyAddress = new Address("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"); - let checker = new InteractionChecker(); - - it("should detect errors for 'ultimate answer'", async function () { - let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); - let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); - let endpoint = abiRegistry.getEndpoint("getUltimateAnswer"); - - // Send value to non-payable - assert.throw( - () => { - let interaction = (contract.methods.getUltimateAnswer()).withValue( - TokenTransfer.egldFromAmount(1), - ); - checker.checkInteraction(interaction, endpoint); - }, - errors.ErrContractInteraction, - "cannot send EGLD value to non-payable", - ); - - // Bad arguments - assert.throw( - () => { - contract.methods.getUltimateAnswer(["abba"]); - }, - Error, - "Wrong number of arguments for endpoint getUltimateAnswer: expected between 0 and 0 arguments, have 1", - ); - }); - - it("should detect errors for 'lottery'", async function () { - let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); - let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); - let endpoint = abiRegistry.getEndpoint("start"); - - // Bad number of arguments - assert.throw( - () => { - contract.methods.start(["lucky", TokenTransfer.egldFromAmount(1)]); - }, - Error, - "Wrong number of arguments for endpoint start: expected between 8 and 9 arguments, have 2", - ); - - // Bad types (U64 instead of U32) - assert.throw( - () => { - let interaction = contract.methodsExplicit.start([ - BytesValue.fromUTF8("lucky"), - new TokenIdentifierValue("lucky-token"), - new BigUIntValue(1), - OptionValue.newMissing(), - OptionValue.newProvided(new U32Value(1)), - OptionValue.newProvided(new U32Value(1)), - OptionValue.newMissing(), - OptionValue.newMissing(), - new OptionalValue(new OptionalType(new BigUIntType())), - ]); - checker.checkInteraction(interaction, endpoint); - }, - errors.ErrContractInteraction, - "type mismatch at index 4, expected: Option, got: Option", - ); - }); -}); diff --git a/src/abi/interactionChecker.ts b/src/abi/interactionChecker.ts deleted file mode 100644 index 744525f56..000000000 --- a/src/abi/interactionChecker.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as errors from "../errors"; -import { EndpointDefinition } from "./typesystem"; -import { Interaction } from "./interaction"; -import BigNumber from "bignumber.js"; - -/** - * An interaction checker that aims to be as strict as possible. - * It is designed to catch programmer errors such as: - * - incorrect types of contract call arguments - * - errors related to calling "non-payable" functions with some value provided - * - gas estimation errors (not yet implemented) - */ -/** - * @deprecated The Interaction checker is deprecated due to lack of use. - */ -export class InteractionChecker { - checkInteraction(interaction: Interaction, definition: EndpointDefinition): void { - this.checkPayable(interaction, definition); - this.checkArguments(interaction, definition); - } - - private checkPayable(interaction: Interaction, definition: EndpointDefinition) { - let hasValue = !new BigNumber(interaction.getValue().toString()).isZero(); - let isPayableInEGLD = definition.modifiers.isPayableInEGLD(); - - if (hasValue && !isPayableInEGLD) { - throw new errors.ErrContractInteraction("cannot send EGLD value to non-payable"); - } - } - - private checkArguments(interaction: Interaction, definition: EndpointDefinition) { - let formalArguments = definition.input; - let actualArguments = interaction.getArguments(); - let numFormalArguments = formalArguments.length; - let numActualArguments = actualArguments.length; - - if (numFormalArguments != numActualArguments) { - throw new errors.ErrContractInteraction( - `bad arguments, expected: ${numFormalArguments}, got: ${numActualArguments}`, - ); - } - - // TODO: discuss again, possibly redesign the handling of covariance / contravariance. - - for (let i = 0; i < numFormalArguments; i++) { - let expectedType = formalArguments[i].type; - let argument = actualArguments[i]; - let actualType = argument.getType(); - // isAssignableFrom() is responsible to handle covariance and contravariance (depending on the class that overrides it). - let ok = expectedType.isAssignableFrom(actualType); - - if (!ok) { - throw new errors.ErrContractInteraction( - `type mismatch at index ${i}, expected: ${expectedType}, got: ${actualType}`, - ); - } - } - } -} diff --git a/src/abi/transactionPayloadBuilders.spec.ts b/src/abi/transactionPayloadBuilders.spec.ts deleted file mode 100644 index 884c48b06..000000000 --- a/src/abi/transactionPayloadBuilders.spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { assert } from "chai"; -import { Address } from "../address"; -import { ContractFunction } from "./function"; -import { Code } from "./code"; -import { CodeMetadata } from "./codeMetadata"; -import { AddressValue, U32Value } from "./typesystem"; -import { - ContractCallPayloadBuilder, - ContractDeployPayloadBuilder, - ContractUpgradePayloadBuilder, -} from "./transactionPayloadBuilders"; - -describe("test contract payload builders", () => { - it("should prepare deploy correctly", async () => { - let payload = new ContractDeployPayloadBuilder() - .setCode(Code.fromBuffer(Buffer.from([1, 2, 3, 4]))) - .setCodeMetadata(new CodeMetadata(true, false, true)) - .addInitArg(new U32Value(1024)) - .build(); - - assert.equal(payload.valueOf().toString(), "01020304@0500@0102@0400"); - }); - - it("should prepare upgrade correctly", async () => { - let payload = new ContractUpgradePayloadBuilder() - .setCode(Code.fromBuffer(Buffer.from([1, 2, 3, 4]))) - .setCodeMetadata(new CodeMetadata(true, false, true)) - .addInitArg(new U32Value(1024)) - .build(); - - assert.equal(payload.valueOf().toString(), "upgradeContract@01020304@0102@0400"); - }); - - it("should prepare call correctly", async () => { - let alice = new Address("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz"); - let payload = new ContractCallPayloadBuilder() - .setFunction(new ContractFunction("transferToken")) - .addArg(new AddressValue(alice)) - .addArg(new U32Value(1024)) - .build(); - - assert.equal( - payload.valueOf().toString(), - "transferToken@fd691bb5e85d102687d81079dffce842d4dc328276d2d4c60d8fd1c3433c3293@0400", - ); - }); -}); diff --git a/src/abi/transactionPayloadBuilders.ts b/src/abi/transactionPayloadBuilders.ts deleted file mode 100644 index 215b9e729..000000000 --- a/src/abi/transactionPayloadBuilders.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { WasmVirtualMachine } from "../constants"; -import { TransactionPayload } from "../transactionPayload"; -import { guardValueIsSet } from "../utils"; -import { ArgSerializer } from "./argSerializer"; -import { ICode, ICodeMetadata, IContractFunction } from "./interface"; -import { TypedValue } from "./typesystem"; - -/** - * @deprecated Use {@link SmartContractTransactionsFactory} instead. - * - * A builder for {@link TransactionPayload} objects, to be used for Smart Contract deployment transactions. - */ -export class ContractDeployPayloadBuilder { - private code: ICode | null = null; - private codeMetadata: ICodeMetadata = ""; - private arguments: TypedValue[] = []; - - /** - * Sets the code of the Smart Contract. - */ - setCode(code: ICode): ContractDeployPayloadBuilder { - this.code = code; - return this; - } - - /** - * Sets the code metadata of the Smart Contract. - */ - setCodeMetadata(codeMetadata: ICodeMetadata): ContractDeployPayloadBuilder { - this.codeMetadata = codeMetadata; - return this; - } - - /** - * Adds constructor (`init`) arguments. - */ - addInitArg(arg: TypedValue): ContractDeployPayloadBuilder { - this.arguments.push(arg); - return this; - } - - /** - * Sets constructor (`init`) arguments. - */ - setInitArgs(args: TypedValue[]): ContractDeployPayloadBuilder { - this.arguments = args; - return this; - } - - /** - * Builds the {@link TransactionPayload}. - */ - build(): TransactionPayload { - guardValueIsSet("code", this.code); - - let code = this.code!.toString(); - let codeMetadata = this.codeMetadata.toString(); - let data = `${code}@${WasmVirtualMachine}@${codeMetadata}`; - data = appendArgumentsToString(data, this.arguments); - - return new TransactionPayload(data); - } -} - -/** - * @deprecated Use {@link SmartContractTransactionsFactory} instead. - * - * A builder for {@link TransactionPayload} objects, to be used for Smart Contract upgrade transactions. - */ -export class ContractUpgradePayloadBuilder { - private code: ICode | null = null; - private codeMetadata: ICodeMetadata = ""; - private arguments: TypedValue[] = []; - - /** - * Sets the code of the Smart Contract. - */ - setCode(code: ICode): ContractUpgradePayloadBuilder { - this.code = code; - return this; - } - - /** - * Sets the code metadata of the Smart Contract. - */ - setCodeMetadata(codeMetadata: ICodeMetadata): ContractUpgradePayloadBuilder { - this.codeMetadata = codeMetadata; - return this; - } - - /** - * Adds upgrade (`init`) arguments. - */ - addInitArg(arg: TypedValue): ContractUpgradePayloadBuilder { - this.arguments.push(arg); - return this; - } - - /** - * Sets upgrade (`init`) arguments. - */ - setInitArgs(args: TypedValue[]): ContractUpgradePayloadBuilder { - this.arguments = args; - return this; - } - - /** - * Builds the {@link TransactionPayload}. - */ - build(): TransactionPayload { - guardValueIsSet("code", this.code); - - let code = this.code!.toString(); - let codeMetadata = this.codeMetadata.toString(); - let data = `upgradeContract@${code}@${codeMetadata}`; - data = appendArgumentsToString(data, this.arguments); - - return new TransactionPayload(data); - } -} - -/** - * @deprecated Use {@link SmartContractTransactionsFactory} instead. - * - * A builder for {@link TransactionPayload} objects, to be used for Smart Contract execution transactions. - */ -export class ContractCallPayloadBuilder { - private contractFunction: IContractFunction | null = null; - private arguments: TypedValue[] = []; - - /** - * Sets the function to be called (executed). - */ - setFunction(contractFunction: IContractFunction): ContractCallPayloadBuilder { - this.contractFunction = contractFunction; - return this; - } - - /** - * Adds a function argument. - */ - addArg(arg: TypedValue): ContractCallPayloadBuilder { - this.arguments.push(arg); - return this; - } - - /** - * Sets the function arguments. - */ - setArgs(args: TypedValue[]): ContractCallPayloadBuilder { - this.arguments = args; - return this; - } - - /** - * Builds the {@link TransactionPayload}. - */ - build(): TransactionPayload { - guardValueIsSet("calledFunction", this.contractFunction); - - let data = this.contractFunction!.toString(); - data = appendArgumentsToString(data, this.arguments); - - return new TransactionPayload(data); - } -} - -function appendArgumentsToString(to: string, values: TypedValue[]) { - let { argumentsString, count } = new ArgSerializer().valuesToString(values); - if (count == 0) { - return to; - } - return `${to}@${argumentsString}`; -} diff --git a/src/accounts/account.ts b/src/accounts/account.ts index e164a34b2..126e194d3 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -1,6 +1,6 @@ import { Address } from "../address"; import { LibraryConfig } from "../config"; -import { IAccountBalance, INonce } from "../interface"; +import { INonce } from "../interface"; import { Mnemonic, UserSigner, UserWallet } from "../wallet"; import { IAccount } from "./interfaces"; @@ -18,14 +18,6 @@ export class Account implements IAccount { */ nonce: INonce = 0; - /** - * @deprecated This will be remove with the next release as not needed anymore. - */ - /** - * The balance of the account. - */ - balance: IAccountBalance = "0"; - /** * The signer of the account. */ @@ -39,17 +31,6 @@ export class Account implements IAccount { this.signer = signer; } - /** - * @deprecated This will be remove with the next release as not needed anymore. - */ - /** - * Updates account properties (such as nonce, balance). - */ - update(obj: { nonce: INonce; balance: IAccountBalance }) { - this.nonce = obj.nonce; - this.balance = obj.balance; - } - /** * Increments (locally) the nonce (the account sequence number). */ @@ -73,7 +54,6 @@ export class Account implements IAccount { return { address: this.address.bech32(), nonce: this.nonce.valueOf(), - balance: this.balance.toString(), }; } diff --git a/src/address.ts b/src/address.ts index 00241fee8..ec5fae2f7 100644 --- a/src/address.ts +++ b/src/address.ts @@ -124,27 +124,6 @@ export class Address { return Address.newFromHex(value, hrp); } - /** - * @deprecated Constructing an address object from another object is deprecated. - */ - static fromAddress(address: Address): Address { - return new Address(address); - } - - /** - * @deprecated Use the constructor, instead. - */ - static fromBuffer(buffer: Buffer, hrp?: string): Address { - return new Address(buffer, hrp); - } - - /** - * @deprecated Use {@link newFromBech32} or {@link newFromHex}. - */ - static fromString(value: string, hrp?: string): Address { - return new Address(value, hrp); - } - private static isValidHex(value: string) { return Buffer.from(value, "hex").length == PUBKEY_LENGTH; } diff --git a/src/constants.ts b/src/constants.ts index 9300d9780..d62de0fa7 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -26,28 +26,3 @@ export const SDK_JS_SIGNER = "sdk-js"; export const UNKNOWN_SIGNER = "unknown"; export const EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER = "EGLD-000000"; - -/** - * @deprecated - */ -export const DEFAULT_HRP = "erd"; - -/** - * @deprecated - */ -export const BECH32_ADDRESS_LENGTH = 62; - -/** - * @deprecated Use {@link CONTRACT_DEPLOY_ADDRESS_HEX} instead. - */ -export const CONTRACT_DEPLOY_ADDRESS = "erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu"; - -/** - * @deprecated Use {@link DELEGATION_MANAGER_SC_ADDRESS_HEX} instead. - */ -export const DELEGATION_MANAGER_SC_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"; - -/** - * @deprecated Use {@link 000000000000000000010000000000000000000000000000000000000002ffff} instead. - */ -export const ESDT_CONTRACT_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"; diff --git a/src/gasEstimator.spec.ts b/src/gasEstimator.spec.ts deleted file mode 100644 index e1394717f..000000000 --- a/src/gasEstimator.spec.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { assert } from "chai"; -import { GasEstimator } from "./gasEstimator"; - -describe("test gas estimator", () => { - it("should estimate gas limit (default gas configuration)", () => { - const estimator = new GasEstimator(); - - assert.equal(estimator.forEGLDTransfer(0), 50000); - assert.equal(estimator.forEGLDTransfer(3), 50000 + 3 * 1500); - - assert.equal(estimator.forESDTTransfer(80), 50000 + 80 * 1500 + 200000 + 100000); - assert.equal(estimator.forESDTTransfer(100), 50000 + 100 * 1500 + 200000 + 100000); - - assert.equal(estimator.forESDTNFTTransfer(80), 50000 + 80 * 1500 + 200000 + 800000); - assert.equal(estimator.forESDTNFTTransfer(100), 50000 + 100 * 1500 + 200000 + 800000); - - assert.equal(estimator.forMultiESDTNFTTransfer(80, 1), 50000 + 80 * 1500 + (200000 + 800000) * 1); - assert.equal(estimator.forMultiESDTNFTTransfer(80, 3), 50000 + 80 * 1500 + (200000 + 800000) * 3); - }); - - it("should estimate gas limit (custom gas configuration)", () => { - const estimator = new GasEstimator({ - minGasLimit: 10000, - gasPerDataByte: 3000, - gasCostESDTTransfer: 200000, - gasCostESDTNFTTransfer: 300000, - gasCostESDTNFTMultiTransfer: 400000, - }); - - assert.equal(estimator.forEGLDTransfer(0), 10000); - assert.equal(estimator.forEGLDTransfer(3), 10000 + 3 * 3000); - - assert.equal(estimator.forESDTTransfer(80), 10000 + 80 * 3000 + 200000 + 100000); - assert.equal(estimator.forESDTTransfer(100), 10000 + 100 * 3000 + 200000 + 100000); - - assert.equal(estimator.forESDTNFTTransfer(80), 10000 + 80 * 3000 + 300000 + 800000); - assert.equal(estimator.forESDTNFTTransfer(100), 10000 + 100 * 3000 + 300000 + 800000); - - assert.equal(estimator.forMultiESDTNFTTransfer(80, 1), 10000 + 80 * 3000 + (400000 + 800000) * 1); - assert.equal(estimator.forMultiESDTNFTTransfer(80, 3), 10000 + 80 * 3000 + (400000 + 800000) * 3); - }); -}); diff --git a/src/gasEstimator.ts b/src/gasEstimator.ts deleted file mode 100644 index 716ddb27f..000000000 --- a/src/gasEstimator.ts +++ /dev/null @@ -1,74 +0,0 @@ -interface IGasConfiguration { - readonly minGasLimit: number; - readonly gasPerDataByte: number; - readonly gasCostESDTTransfer: number; - readonly gasCostESDTNFTTransfer: number; - readonly gasCostESDTNFTMultiTransfer: number; -} - -/** - * This is mirroring (on a best efforts basis) the network's gas configuration & gas schedule: - * - https://gateway.multiversx.com/network/config - * - https://github.com/multiversx/mx-chain-mainnet-config/tree/master/gasSchedules - * - https://github.com/multiversx/mx-chain-mainnet-config/blob/master/enableEpochs.toml#L200 - */ -export const DefaultGasConfiguration: IGasConfiguration = { - minGasLimit: 50000, - gasPerDataByte: 1500, - gasCostESDTTransfer: 200000, - gasCostESDTNFTTransfer: 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), -// 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; - -/** - * @deprecated This will be remove with the next release as the only place where it is used is a deprecated constructor. - */ -export class GasEstimator { - private readonly gasConfiguration: IGasConfiguration; - - constructor(gasConfiguration?: IGasConfiguration) { - this.gasConfiguration = gasConfiguration || DefaultGasConfiguration; - } - - forEGLDTransfer(dataLength: number) { - const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasPerDataByte * dataLength; - - return gasLimit; - } - - forESDTTransfer(dataLength: number) { - const gasLimit = - this.gasConfiguration.minGasLimit + - this.gasConfiguration.gasCostESDTTransfer + - this.gasConfiguration.gasPerDataByte * dataLength + - ADDITIONAL_GAS_FOR_ESDT_TRANSFER; - - return gasLimit; - } - - forESDTNFTTransfer(dataLength: number) { - const gasLimit = - this.gasConfiguration.minGasLimit + - this.gasConfiguration.gasCostESDTNFTTransfer + - this.gasConfiguration.gasPerDataByte * dataLength + - ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER; - - return gasLimit; - } - - forMultiESDTNFTTransfer(dataLength: number, numTransfers: number) { - const gasLimit = - this.gasConfiguration.minGasLimit + - (this.gasConfiguration.gasCostESDTNFTMultiTransfer + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER) * numTransfers + - this.gasConfiguration.gasPerDataByte * dataLength; - - return gasLimit; - } -} diff --git a/src/index.ts b/src/index.ts index 1816c81e1..9917a1971 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,7 +16,6 @@ export * from "./converters"; export * from "./delegation"; export * from "./entrypoints"; export * from "./errors"; -export * from "./gasEstimator"; export * from "./interface"; export * from "./interfaceOfNetwork"; export * from "./logger"; @@ -24,9 +23,6 @@ export * from "./message"; export * from "./networkParams"; export * from "./networkProviders"; export * from "./relayed"; -export * from "./relayedTransactionV1Builder"; -export * from "./relayedTransactionV2Builder"; -export * from "./signableMessage"; export * from "./tokenManagement"; export * from "./tokens"; export * from "./transaction"; diff --git a/src/interface.ts b/src/interface.ts index a1e7fe422..a3fb3b2c2 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -83,11 +83,6 @@ export interface ITokenTransfer { valueOf(): BigNumber.Value; } -/** - * @deprecated Use {@link ITokenTransfer} instead. - */ -export type ITokenPayment = ITokenTransfer; - export interface ITransaction { sender: string; receiver: string; diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 3891ca47a..d6445a096 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,4 +1,5 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; +import { ITransaction } from "../interface"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; @@ -8,7 +9,7 @@ import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig, defaultPagination } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; -import { IAddress, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "./interface"; +import { IAddress, INetworkProvider, IPagination } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; @@ -146,17 +147,17 @@ export class ApiNetworkProvider implements INetworkProvider { return status; } - async sendTransaction(tx: ITransaction | ITransactionNext): Promise { + async sendTransaction(tx: ITransaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transactions", transaction); return response.txHash; } - async sendTransactions(txs: (ITransaction | ITransactionNext)[]): Promise { + async sendTransactions(txs: ITransaction[]): Promise { return await this.backingProxyNetworkProvider.sendTransactions(txs); } - async simulateTransaction(tx: ITransaction | ITransactionNext): Promise { + async simulateTransaction(tx: ITransaction): Promise { return await this.backingProxyNetworkProvider.simulateTransaction(tx); } diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index f1f3a1cf4..675f27db2 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,4 +1,4 @@ -import { ITransaction as ITransactionAsInSpecs } from "../interface"; +import { ITransaction } from "../interface"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; @@ -79,12 +79,12 @@ export interface INetworkProvider { /** * Broadcasts an already-signed transaction. */ - sendTransaction(tx: ITransaction | ITransactionNext): Promise; + sendTransaction(tx: ITransaction): Promise; /** * Broadcasts a list of already-signed transactions. */ - sendTransactions(txs: (ITransaction | ITransactionNext)[]): Promise; + sendTransactions(txs: ITransaction[]): Promise; /** * Simulates the processing of an already-signed transaction. @@ -136,15 +136,6 @@ export interface IPagination { size: number; } -export interface ITransaction { - toSendable(): any; -} - export interface IAddress { bech32(): string; } - -/** - * @deprecated This will be removed with the next release (replaced by the `ITransaction` interface from "src/interface.ts"). - */ -export type ITransactionNext = ITransactionAsInSpecs; diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index d1c121e2a..1b79d9d4e 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -1,10 +1,11 @@ import { AxiosHeaders } from "axios"; import { assert } from "chai"; import { Address } from "../address"; +import { ITransaction } from "../interface"; import { SmartContractQuery } from "../smartContractQuery"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { ApiNetworkProvider } from "./apiNetworkProvider"; -import { INetworkProvider, ITransactionNext } from "./interface"; +import { INetworkProvider } from "./interface"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; import { NonFungibleTokenOfAccountOnNetwork } from "./tokens"; @@ -196,43 +197,46 @@ describe("test network providers on devnet: Proxy and API", function () { const txs = [ { - toSendable: function () { - return { - nonce: 42, - value: "1", - receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", - sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", - gasPrice: 1000000000, - gasLimit: 50000, - chainID: "D", - version: 1, - signature: - "c8eb539e486db7d703d8c70cab3b7679113f77c4685d8fcc94db027ceacc6b8605115034355386dffd7aa12e63dbefa03251a2f1b1d971f52250187298d12900", - }; - }, + nonce: 42n, + value: 1n, + receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", + sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", + data: new Uint8Array(Buffer.from("test")), + gasPrice: 1000000000n, + gasLimit: 50000n, + chainID: "D", + version: 1, + signature: new Uint8Array( + Buffer.from( + "c8eb539e486db7d703d8c70cab3b7679113f77c4685d8fcc94db027ceacc6b8605115034355386dffd7aa12e63dbefa03251a2f1b1d971f52250187298d12900", + ), + ), + senderUsername: "", + receiverUsername: "", + guardian: "", + guardianSignature: new Uint8Array(), + options: 0, }, { - toSendable: function () { - return { - nonce: 43, - value: "1", - receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", - sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", - gasPrice: 1000000000, - gasLimit: 50000, - chainID: "D", - version: 1, - signature: - "9c4c22d0ae1b5a10c39583a5ab9020b00b27aa69d4ac8ab4922620dbf0df4036ed890f9946d38a9d0c85d6ac485c0d9b2eac0005e752f249fd0ad863b0471d02", - }; - }, - }, - { - toSendable: function () { - return { - nonce: 44, - }; - }, + nonce: 43n, + value: 1n, + receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", + sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", + gasPrice: 1000000000n, + gasLimit: 50000n, + chainID: "D", + version: 1, + signature: new Uint8Array( + Buffer.from( + "9c4c22d0ae1b5a10c39583a5ab9020b00b27aa69d4ac8ab4922620dbf0df4036ed890f9946d38a9d0c85d6ac485c0d9b2eac0005e752f249fd0ad863b0471d02", + ), + ), + senderUsername: "", + receiverUsername: "", + guardian: "", + guardianSignature: new Uint8Array(), + options: 0, + data: new Uint8Array(), }, ]; @@ -408,27 +412,10 @@ describe("test network providers on devnet: Proxy and API", function () { assert.deepEqual(proxyResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==", "base64")]); }); - it("should send both `Transaction` and `TransactionNext`", async function () { + it("should send both `Transaction` ", async function () { this.timeout(50000); - const transaction = { - toSendable: function () { - return { - nonce: 7, - value: "0", - receiver: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - sender: "erd1zztjf9fhwvuvquzsllknq4qcmffwad6n0hjtn5dyzytr5tgz7uas0mkgrq", - gasPrice: 1000000000, - gasLimit: 50000, - chainID: "D", - version: 2, - signature: - "149f1d8296efcb9489c5b3142ae659aacfa3a7daef3645f1d3747a96dc9cee377070dd8b83b322997c15ba3c305ac18daaee0fd25760eba334b14a9272b34802", - }; - }, - }; - - const transactionNext: ITransactionNext = { + const transaction: ITransaction = { nonce: BigInt(8), value: BigInt(0), receiver: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", @@ -449,13 +436,10 @@ describe("test network providers on devnet: Proxy and API", function () { options: 0, }; - const apiLegacyTxHash = await apiProvider.sendTransaction(transaction); - const apiTxNextHash = await apiProvider.sendTransaction(transactionNext); + const apiTxNextHash = await apiProvider.sendTransaction(transaction); - const proxyLegacyTxHash = await proxyProvider.sendTransaction(transaction); - const proxyTxNextHash = await proxyProvider.sendTransaction(transactionNext); + const proxyTxNextHash = await proxyProvider.sendTransaction(transaction); - assert.equal(apiLegacyTxHash, proxyLegacyTxHash); assert.equal(apiTxNextHash, proxyTxNextHash); }); }); diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 1c2cbedef..855f391ff 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,4 +1,5 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; +import { ITransaction } from "../interface"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; @@ -7,7 +8,7 @@ import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; import { BaseUserAgent, EsdtContractAddress } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; -import { IAddress, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "./interface"; +import { IAddress, INetworkProvider, IPagination } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; @@ -134,13 +135,13 @@ export class ProxyNetworkProvider implements INetworkProvider { return status; } - async sendTransaction(tx: ITransaction | ITransactionNext): Promise { + async sendTransaction(tx: ITransaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transaction/send", transaction); return response.txHash; } - async sendTransactions(txs: (ITransaction | ITransactionNext)[]): Promise { + async sendTransactions(txs: ITransaction[]): Promise { const data = txs.map((tx) => prepareTransactionForBroadcasting(tx)); const response = await this.doPostGeneric("transaction/send-multiple", data); @@ -153,7 +154,7 @@ export class ProxyNetworkProvider implements INetworkProvider { return hashes; } - async simulateTransaction(tx: ITransaction | ITransactionNext): Promise { + async simulateTransaction(tx: ITransaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transaction/simulate", transaction); return response; diff --git a/src/relayedTransactionV1Builder.spec.ts b/src/relayedTransactionV1Builder.spec.ts deleted file mode 100644 index 018ba6b04..000000000 --- a/src/relayedTransactionV1Builder.spec.ts +++ /dev/null @@ -1,260 +0,0 @@ -import { assert } from "chai"; -import { Address } from "./address"; -import * as errors from "./errors"; -import { TransactionOptions, TransactionVersion } from "./networkParams"; -import { RelayedTransactionV1Builder } from "./relayedTransactionV1Builder"; -import { TestWallet, loadTestWallets } from "./testutils"; -import { TokenTransfer } from "./tokens"; -import { Transaction } from "./transaction"; -import { TransactionPayload } from "./transactionPayload"; - -describe("test relayed v1 transaction builder", function () { - let alice: TestWallet, bob: TestWallet, carol: TestWallet, grace: TestWallet, frank: TestWallet; - - before(async function () { - ({ alice, bob, carol, grace, frank } = await loadTestWallets()); - }); - - it("should throw exception if args were not set", async function () { - const builder = new RelayedTransactionV1Builder(); - assert.throw(() => builder.build(), errors.ErrInvalidRelayedV1BuilderArguments); - - const innerTx = new Transaction({ - nonce: 15, - sender: alice.address, - receiver: Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), - gasLimit: 10000000, - chainID: "1", - data: new TransactionPayload("getContractConfig"), - }); - builder.setInnerTransaction(innerTx); - assert.throw(() => builder.build(), errors.ErrInvalidRelayedV1BuilderArguments); - - const networkConfig = { - MinGasLimit: 50_000, - GasPerDataByte: 1_500, - GasPriceModifier: 0.01, - ChainID: "T", - }; - builder.setNetworkConfig(networkConfig); - assert.throw(() => builder.build(), errors.ErrInvalidRelayedV1BuilderArguments); - - builder.setRelayerAddress(alice.getAddress()); - assert.doesNotThrow(() => builder.build()); - }); - - it("should compute relayed v1 transaction", async function () { - const networkConfig = { - MinGasLimit: 50_000, - GasPerDataByte: 1_500, - GasPriceModifier: 0.01, - ChainID: "T", - }; - - const innerTx = new Transaction({ - nonce: 198, - sender: bob.address, - receiver: Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), - gasLimit: 60000000, - chainID: networkConfig.ChainID, - data: new TransactionPayload("getContractConfig"), - }); - - innerTx.applySignature(await bob.signer.sign(innerTx.serializeForSigning())); - - const builder = new RelayedTransactionV1Builder(); - const relayedTxV1 = builder - .setInnerTransaction(innerTx) - .setRelayerNonce(2627) - .setNetworkConfig(networkConfig) - .setRelayerAddress(alice.address) - .build(); - - relayedTxV1.applySignature(await alice.signer.sign(relayedTxV1.serializeForSigning())); - - assert.equal(relayedTxV1.getNonce().valueOf(), 2627); - assert.equal( - relayedTxV1.getData().toString(), - "relayedTx@7b226e6f6e6365223a3139382c2273656e646572223a2267456e574f65576d6d413063306a6b71764d354241707a61644b46574e534f69417643575163776d4750673d222c227265636569766572223a22414141414141414141414141415141414141414141414141414141414141414141414141414141432f2f383d222c2276616c7565223a302c226761735072696365223a313030303030303030302c226761734c696d6974223a36303030303030302c2264617461223a225a3256305132397564484a68593352446232356d6157633d222c227369676e6174757265223a2272525455544858677a4273496e4f6e454b6b7869642b354e66524d486e33534948314673746f577352434c434b3258514c41614f4e704449346531476173624c5150616130566f364144516d4f2b52446b6f364a43413d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a327d", - ); - assert.equal( - relayedTxV1.getSignature().toString("hex"), - "128e7cdc14c2b9beee2f3ff7a7fa5d1f5ef31a654a0c92e223c90ab28265fa277d306f23a06536248cf9573e828017004fb639617fade4d68a37524aafca710d", - ); - }); - - it("should compute relayed v1 transaction (with usernames)", async function () { - const networkConfig = { - MinGasLimit: 50_000, - GasPerDataByte: 1_500, - GasPriceModifier: 0.01, - ChainID: "T", - }; - - const innerTx = new Transaction({ - nonce: 208, - value: TokenTransfer.egldFromAmount(1), - sender: carol.address, - receiver: alice.address, - senderUsername: "carol", - receiverUsername: "alice", - gasLimit: 50000, - chainID: networkConfig.ChainID, - }); - - innerTx.applySignature(await carol.signer.sign(innerTx.serializeForSigning())); - - const builder = new RelayedTransactionV1Builder(); - const relayedTxV1 = builder - .setInnerTransaction(innerTx) - .setRelayerNonce(715) - .setNetworkConfig(networkConfig) - .setRelayerAddress(frank.address) - .build(); - - relayedTxV1.applySignature(await frank.signer.sign(relayedTxV1.serializeForSigning())); - - assert.equal(relayedTxV1.getNonce().valueOf(), 715); - assert.equal( - relayedTxV1.getData().toString(), - "relayedTx@7b226e6f6e6365223a3230382c2273656e646572223a227371455656633553486b6c45344a717864556e59573068397a536249533141586f3534786f32634969626f3d222c227265636569766572223a2241546c484c76396f686e63616d433877673970645168386b77704742356a6949496f3349484b594e6165453d222c2276616c7565223a313030303030303030303030303030303030302c226761735072696365223a313030303030303030302c226761734c696d6974223a35303030302c2264617461223a22222c227369676e6174757265223a226a33427a6469554144325963517473576c65707663664a6f75657a48573063316b735a424a4d6339573167435450512b6870636759457858326f6f367a4b5654347464314b4b6f79783841526a346e336474576c44413d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a322c22736e64557365724e616d65223a22593246796232773d222c22726376557365724e616d65223a22595778705932553d227d", - ); - assert.equal( - relayedTxV1.getSignature().toString("hex"), - "3787d640e5a579e7977a4a1bcdd435ad11855632fa4a414a06fbf8355692d1a58d76ef0adbdd6ccd6bd3c329f36bd53c180d4873ec1a6c558e659aeb9ab92d00", - ); - }); - - it("should compute relayed v1 transaction with big value", async function () { - const networkConfig = { - MinGasLimit: 50_000, - GasPerDataByte: 1_500, - GasPriceModifier: 0.01, - ChainID: "T", - }; - - const innerTx = new Transaction({ - nonce: 208, - value: TokenTransfer.egldFromAmount(1999999), - sender: carol.address, - receiver: alice.address, - senderUsername: "carol", - receiverUsername: "alice", - gasLimit: 50000, - chainID: networkConfig.ChainID, - }); - - innerTx.applySignature(await carol.signer.sign(innerTx.serializeForSigning())); - - const builder = new RelayedTransactionV1Builder(); - const relayedTxV1 = builder - .setInnerTransaction(innerTx) - .setRelayerNonce(715) - .setNetworkConfig(networkConfig) - .setRelayerAddress(frank.address) - .build(); - - relayedTxV1.applySignature(await frank.signer.sign(relayedTxV1.serializeForSigning())); - - assert.equal(relayedTxV1.getNonce().valueOf(), 715); - assert.equal( - relayedTxV1.getData().toString(), - "relayedTx@7b226e6f6e6365223a3230382c2273656e646572223a227371455656633553486b6c45344a717864556e59573068397a536249533141586f3534786f32634969626f3d222c227265636569766572223a2241546c484c76396f686e63616d433877673970645168386b77704742356a6949496f3349484b594e6165453d222c2276616c7565223a313939393939393030303030303030303030303030303030302c226761735072696365223a313030303030303030302c226761734c696d6974223a35303030302c2264617461223a22222c227369676e6174757265223a22594661677972512f726d614c7333766e7159307657553858415a7939354b4e31725738347a4f764b62376c7a3773576e2f566a546d68704378774d682b7261314e444832574d6f3965507648304f79427453776a44773d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a322c22736e64557365724e616d65223a22593246796232773d222c22726376557365724e616d65223a22595778705932553d227d", - ); - assert.equal( - relayedTxV1.getSignature().toString("hex"), - "c0fb5cf8c0a413d6988ba35dc279c63f8849572c5f23b1cab36dcc50952dc3ed9da01068d6ac0cbde7e14167bfc2eca5164d5c2154c89eb313c9c596e3f8b801", - ); - }); - - it("should compute guarded inner Tx - relayed v1 transaction", async function () { - const networkConfig = { - MinGasLimit: 50_000, - GasPerDataByte: 1_500, - GasPriceModifier: 0.01, - ChainID: "T", - }; - - const innerTx = new Transaction({ - nonce: 198, - sender: bob.address, - receiver: Address.fromBech32("erd1qqqqqqqqqqqqqpgq54tsxmej537z9leghvp69hfu4f8gg5eu396q83gnnz"), - gasLimit: 60000000, - chainID: networkConfig.ChainID, - data: new TransactionPayload("getContractConfig"), - guardian: grace.address, - version: TransactionVersion.withTxOptions(), - options: TransactionOptions.withOptions({ guarded: true }), - }); - - innerTx.applySignature(await bob.signer.sign(innerTx.serializeForSigning())); - innerTx.applyGuardianSignature(await grace.signer.sign(innerTx.serializeForSigning())); - - const builder = new RelayedTransactionV1Builder(); - const relayedTxV1 = builder - .setInnerTransaction(innerTx) - .setRelayerNonce(2627) - .setNetworkConfig(networkConfig) - .setRelayerAddress(alice.address) - .build(); - - relayedTxV1.applySignature(await alice.signer.sign(relayedTxV1.serializeForSigning())); - - assert.equal(relayedTxV1.getNonce().valueOf(), 2627); - assert.equal( - relayedTxV1.getData().toString(), - "relayedTx@7b226e6f6e6365223a3139382c2273656e646572223a2267456e574f65576d6d413063306a6b71764d354241707a61644b46574e534f69417643575163776d4750673d222c227265636569766572223a22414141414141414141414146414b565841323879704877692f79693741364c64504b704f68464d386958513d222c2276616c7565223a302c226761735072696365223a313030303030303030302c226761734c696d6974223a36303030303030302c2264617461223a225a3256305132397564484a68593352446232356d6157633d222c227369676e6174757265223a224b4b78324f33383655725135416b4f465258307578327933446a384853334b373038487174344668377161557669424550716c45614e746e6158706a6f2f333651476d4a456934784435457a6c6f4f677a634d4442773d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a322c226f7074696f6e73223a322c22677561726469616e223a22486f714c61306e655733766843716f56696c70715372744c5673774939535337586d7a563868477450684d3d222c22677561726469616e5369676e6174757265223a222b5431526f4833625a792f54423177342b6a365155477258645637457577553073753948646551626453515269463953757a686d634b705463526d58595252366c534c6652394931624d7134674730436538363741513d3d227d", - ); - assert.equal( - relayedTxV1.getSignature().toString("hex"), - "39cff9d5100e290fbc7361cb6e2402261caf864257b4116f150e0c61e7869155dff8361fa5449431eb7a8ed847c01ba9b3b5ebafe5fac1a3d40c64829d827e00", - ); - }); - - it("should compute guarded inner tx and guarded relayed v1 transaction", async function () { - const networkConfig = { - MinGasLimit: 50_000, - GasPerDataByte: 1_500, - GasPriceModifier: 0.01, - ChainID: "T", - }; - - const innerTx = new Transaction({ - nonce: 198, - sender: bob.address, - receiver: Address.fromBech32("erd1qqqqqqqqqqqqqpgq54tsxmej537z9leghvp69hfu4f8gg5eu396q83gnnz"), - gasLimit: 60000000, - chainID: networkConfig.ChainID, - data: new TransactionPayload("addNumber"), - guardian: grace.address, - version: TransactionVersion.withTxOptions(), - options: TransactionOptions.withOptions({ guarded: true }), - }); - - innerTx.applySignature(await bob.signer.sign(innerTx.serializeForSigning())); - innerTx.applyGuardianSignature(await grace.signer.sign(innerTx.serializeForSigning())); - const builder = new RelayedTransactionV1Builder(); - const relayedTxV1 = builder - .setInnerTransaction(innerTx) - .setRelayerNonce(2627) - .setNetworkConfig(networkConfig) - .setRelayerAddress(alice.address) - .setRelayedTransactionVersion(TransactionVersion.withTxOptions()) - .setRelayedTransactionOptions(TransactionOptions.withOptions({ guarded: true })) - .setRelayedTransactionGuardian(frank.address) - .build(); - - relayedTxV1.applySignature(await alice.signer.sign(relayedTxV1.serializeForSigning())); - relayedTxV1.applyGuardianSignature(await frank.signer.sign(relayedTxV1.serializeForSigning())); - - assert.equal(relayedTxV1.getNonce().valueOf(), 2627); - assert.equal( - relayedTxV1.getData().toString(), - "relayedTx@7b226e6f6e6365223a3139382c2273656e646572223a2267456e574f65576d6d413063306a6b71764d354241707a61644b46574e534f69417643575163776d4750673d222c227265636569766572223a22414141414141414141414146414b565841323879704877692f79693741364c64504b704f68464d386958513d222c2276616c7565223a302c226761735072696365223a313030303030303030302c226761734c696d6974223a36303030303030302c2264617461223a225957526b546e5674596d5679222c227369676e6174757265223a223469724d4b4a656d724d375174344e7635487633544c44683775654779487045564c4371674a3677652f7a662b746a4933354975573452633458543451533433475333356158386c6a533834324a38426854645043673d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a322c226f7074696f6e73223a322c22677561726469616e223a22486f714c61306e655733766843716f56696c70715372744c5673774939535337586d7a563868477450684d3d222c22677561726469616e5369676e6174757265223a2270424754394e674a78307539624c56796b654d78786a454865374269696c37764932324a46676f32787a6e2f496e3032463769546563356b44395045324f747065386c475335412b532f4a36417762576834446744673d3d227d", - ); - assert.equal( - relayedTxV1.getSignature().toString("hex"), - "8ede1bbeed96b102344dffeac12c2592c62b7313cdeb132e8c8bf11d2b1d3bb8189d257a6dbcc99e222393d9b9ec77656c349dae97a32e68bdebd636066bf706", - ); - }); -}); diff --git a/src/relayedTransactionV1Builder.ts b/src/relayedTransactionV1Builder.ts deleted file mode 100644 index 52a48262d..000000000 --- a/src/relayedTransactionV1Builder.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { Address } from "./address"; -import { ErrInvalidRelayedV1BuilderArguments } from "./errors"; -import { IAddress, INonce } from "./interface"; -import { INetworkConfig } from "./interfaceOfNetwork"; -import { TransactionOptions, TransactionVersion } from "./networkParams"; -import { Transaction } from "./transaction"; -import { TransactionPayload } from "./transactionPayload"; - -const JSONbig = require("json-bigint"); - -/** - * @deprecated Use {@link RelayedTransactionsFactory} instead. - */ -export class RelayedTransactionV1Builder { - innerTransaction: Transaction | undefined; - relayerAddress: IAddress | undefined; - relayerNonce: INonce | undefined; - netConfig: INetworkConfig | undefined; - relayedTransactionOptions: TransactionOptions | undefined; - relayedTransactionVersion: TransactionVersion | undefined; - relayedTransactionGuardian: IAddress | undefined; - - /** - * Sets the inner transaction to be used. It has to be already signed. - * - * @param {Transaction} transaction The inner transaction to be used - */ - setInnerTransaction(transaction: Transaction): RelayedTransactionV1Builder { - this.innerTransaction = transaction; - return this; - } - - /** - * Sets the network config to be used for building the relayed v1 transaction - * - * @param {INetworkConfig} netConfig The network configuration to be used - */ - setNetworkConfig(netConfig: INetworkConfig): RelayedTransactionV1Builder { - this.netConfig = netConfig; - return this; - } - - /** - * Sets the address of the relayer (the one that will actually pay the fee) - * - * @param relayerAddress - */ - setRelayerAddress(relayerAddress: IAddress): RelayedTransactionV1Builder { - this.relayerAddress = relayerAddress; - return this; - } - - /** - * (optional) Sets the nonce of the relayer - * - * @param relayerNonce - */ - setRelayerNonce(relayerNonce: INonce): RelayedTransactionV1Builder { - this.relayerNonce = relayerNonce; - return this; - } - - /** - * (optional) Sets the version of the relayed transaction - * - * @param relayedTxVersion - */ - setRelayedTransactionVersion(relayedTxVersion: TransactionVersion): RelayedTransactionV1Builder { - this.relayedTransactionVersion = relayedTxVersion; - return this; - } - - /** - * (optional) Sets the options of the relayed transaction - * - * @param relayedTxOptions - */ - setRelayedTransactionOptions(relayedTxOptions: TransactionOptions): RelayedTransactionV1Builder { - this.relayedTransactionOptions = relayedTxOptions; - return this; - } - - /** - * (optional) Sets the guardian of the relayed transaction - * - * @param relayedTxGuardian - */ - setRelayedTransactionGuardian(relayedTxGuardian: IAddress): RelayedTransactionV1Builder { - this.relayedTransactionGuardian = relayedTxGuardian; - return this; - } - - /** - * Tries to build the relayed v1 transaction based on the previously set fields - * - * @throws ErrInvalidRelayedV1BuilderArguments - * @return Transaction - */ - build(): Transaction { - if ( - !this.innerTransaction || - !this.netConfig || - !this.relayerAddress || - !this.innerTransaction.getSignature() - ) { - throw new ErrInvalidRelayedV1BuilderArguments(); - } - - const serializedTransaction = this.prepareInnerTransaction(); - const data = `relayedTx@${Buffer.from(serializedTransaction).toString("hex")}`; - const payload = new TransactionPayload(data); - - const gasLimit = - this.netConfig.MinGasLimit + - this.netConfig.GasPerDataByte * payload.length() + - this.innerTransaction.getGasLimit().valueOf(); - let relayedTransaction = new Transaction({ - nonce: this.relayerNonce, - sender: this.relayerAddress, - receiver: this.innerTransaction.getSender(), - value: 0, - gasLimit: gasLimit, - data: payload, - chainID: this.netConfig.ChainID, - version: this.relayedTransactionVersion, - options: this.relayedTransactionOptions, - guardian: this.relayedTransactionGuardian, - }); - - if (this.relayerNonce) { - relayedTransaction.setNonce(this.relayerNonce); - } - - return relayedTransaction; - } - - private prepareInnerTransaction(): string { - if (!this.innerTransaction) { - return ""; - } - - const txObject = { - nonce: this.innerTransaction.getNonce().valueOf(), - sender: new Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"), - receiver: new Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"), - value: BigInt(this.innerTransaction.getValue().toString()), - gasPrice: this.innerTransaction.getGasPrice().valueOf(), - gasLimit: this.innerTransaction.getGasLimit().valueOf(), - data: this.innerTransaction.getData().valueOf().toString("base64"), - signature: this.innerTransaction.getSignature().toString("base64"), - chainID: Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"), - version: this.innerTransaction.getVersion().valueOf(), - options: - this.innerTransaction.getOptions().valueOf() == 0 - ? undefined - : this.innerTransaction.getOptions().valueOf(), - guardian: this.innerTransaction.getGuardian().bech32() - ? new Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64") - : undefined, - guardianSignature: this.innerTransaction.getGuardianSignature().toString("hex") - ? this.innerTransaction.getGuardianSignature().toString("base64") - : undefined, - sndUserName: this.innerTransaction.getSenderUsername() - ? Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64") - : undefined, - rcvUserName: this.innerTransaction.getReceiverUsername() - ? Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64") - : undefined, - }; - - return JSONbig.stringify(txObject); - } -} diff --git a/src/relayedTransactionV2Builder.spec.ts b/src/relayedTransactionV2Builder.spec.ts deleted file mode 100644 index cb4cd530c..000000000 --- a/src/relayedTransactionV2Builder.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { loadTestWallets, TestWallet } from "./testutils"; -import { RelayedTransactionV2Builder } from "./relayedTransactionV2Builder"; -import { Address } from "./address"; -import { TransactionPayload } from "./transactionPayload"; -import { assert } from "chai"; -import { Transaction } from "./transaction"; -import * as errors from "./errors"; - -describe("test relayed v2 transaction builder", function () { - let alice: TestWallet, bob: TestWallet; - - before(async function () { - ({ alice, bob } = await loadTestWallets()); - }); - - it("should throw exception if args were not set", async function () { - const builder = new RelayedTransactionV2Builder(); - assert.throw(() => builder.build(), errors.ErrInvalidRelayedV2BuilderArguments); - }); - - it("should throw exception if gas limit of the inner tx is not 0", async function () { - let builder = new RelayedTransactionV2Builder(); - - let networkConfig = { - MinGasLimit: 50_000, - GasPerDataByte: 1_500, - GasPriceModifier: 0.01, - ChainID: "T", - }; - - const innerTx = new Transaction({ - nonce: 15, - sender: alice.address, - receiver: Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), - gasLimit: 10, - chainID: networkConfig.ChainID, - data: new TransactionPayload("getContractConfig"), - }); - builder = builder - .setNetworkConfig(networkConfig) - .setInnerTransactionGasLimit(10) - .setInnerTransaction(innerTx) - .setRelayerAddress(alice.address); - assert.throw(() => builder.build(), errors.ErrGasLimitShouldBe0ForInnerTransaction); - - innerTx.setGasLimit({ - valueOf: function () { - return 10; - }, - }); - builder = builder.setNetworkConfig(networkConfig).setInnerTransactionGasLimit(10).setInnerTransaction(innerTx); - assert.throw(() => builder.build(), errors.ErrGasLimitShouldBe0ForInnerTransaction); - }); - - it("should compute relayed v2 tx", async function () { - let networkConfig = { - MinGasLimit: 50_000, - GasPerDataByte: 1_500, - GasPriceModifier: 0.01, - ChainID: "T", - }; - - const innerTx = new Transaction({ - nonce: 15, - sender: bob.address, - receiver: Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), - gasLimit: 0, - chainID: networkConfig.ChainID, - data: new TransactionPayload("getContractConfig"), - version: 2, - }); - - innerTx.applySignature(await bob.signer.sign(innerTx.serializeForSigning())); - - const builder = new RelayedTransactionV2Builder(); - const relayedTxV2 = builder - .setInnerTransaction(innerTx) - .setInnerTransactionGasLimit(60_000_000) - .setRelayerNonce(37) - .setNetworkConfig(networkConfig) - .setRelayerAddress(alice.getAddress()) - .build(); - - relayedTxV2.setSender(alice.address); - relayedTxV2.applySignature(await alice.signer.sign(relayedTxV2.serializeForSigning())); - - assert.equal(relayedTxV2.getNonce().valueOf(), 37); - assert.equal(relayedTxV2.getVersion().valueOf(), 2); - assert.equal( - relayedTxV2.getData().toString(), - "relayedTxV2@000000000000000000010000000000000000000000000000000000000002ffff@0f@676574436f6e7472616374436f6e666967@fc3ed87a51ee659f937c1a1ed11c1ae677e99629fae9cc289461f033e6514d1a8cfad1144ae9c1b70f28554d196bd6ba1604240c1c1dc19c959e96c1c3b62d0c", - ); - }); -}); diff --git a/src/relayedTransactionV2Builder.ts b/src/relayedTransactionV2Builder.ts deleted file mode 100644 index 54d1595b7..000000000 --- a/src/relayedTransactionV2Builder.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { AddressValue, ArgSerializer, BytesValue, U64Value } from "./abi"; -import { ErrGasLimitShouldBe0ForInnerTransaction, ErrInvalidRelayedV2BuilderArguments } from "./errors"; -import { IAddress, IGasLimit, INonce } from "./interface"; -import { INetworkConfig } from "./interfaceOfNetwork"; -import { Transaction } from "./transaction"; -import { TransactionPayload } from "./transactionPayload"; - -/** - * @deprecated Use {@link RelayedTransactionsFactory} instead. - */ -export class RelayedTransactionV2Builder { - innerTransaction: Transaction | undefined; - innerTransactionGasLimit: IGasLimit | undefined; - relayerAddress: IAddress | undefined; - relayerNonce: INonce | undefined; - netConfig: INetworkConfig | undefined; - - /** - * Sets the inner transaction to be used. It has to be already signed and with gasLimit set to 0. These checks - * are performed on the build() method - * - * @param {Transaction} transaction The inner transaction to be used - */ - setInnerTransaction(transaction: Transaction): RelayedTransactionV2Builder { - this.innerTransaction = transaction; - return this; - } - - /** - * Sets the gas limit to be used for the SC Call inside the inner transaction - * - * @param {IGasLimit} gasLimit The gas limit to be used. The inner transaction needs to have the gas limit set to 0, - * so this field will specify the gas to be used for the SC call of the inner transaction - */ - setInnerTransactionGasLimit(gasLimit: IGasLimit): RelayedTransactionV2Builder { - this.innerTransactionGasLimit = gasLimit; - return this; - } - - /** - * Sets the network config to be used for building the relayed v2 transaction - * - * @param {INetworkConfig} netConfig The network configuration to be used - */ - setNetworkConfig(netConfig: INetworkConfig): RelayedTransactionV2Builder { - this.netConfig = netConfig; - return this; - } - - /** - * Sets the address of the relayer (the one that will actually pay the fee) - * - * @param relayerAddress - */ - setRelayerAddress(relayerAddress: IAddress): RelayedTransactionV2Builder { - this.relayerAddress = relayerAddress; - return this; - } - - /** - * (optional) Sets the nonce of the relayer - * - * @param relayerNonce - */ - setRelayerNonce(relayerNonce: INonce): RelayedTransactionV2Builder { - this.relayerNonce = relayerNonce; - return this; - } - - /** - * Tries to build the relayed v2 transaction based on the previously set fields. - * It returns a transaction that isn't signed - * - * @throws ErrInvalidRelayedV2BuilderArguments - * @throws ErrGasLimitShouldBe0ForInnerTransaction - * @return Transaction - */ - build(): Transaction { - if ( - !this.innerTransaction || - !this.innerTransactionGasLimit || - !this.relayerAddress || - !this.netConfig || - !this.innerTransaction.getSignature() - ) { - throw new ErrInvalidRelayedV2BuilderArguments(); - } - if (this.innerTransaction.getGasLimit() != 0) { - throw new ErrGasLimitShouldBe0ForInnerTransaction(); - } - - const { argumentsString } = new ArgSerializer().valuesToString([ - new AddressValue(this.innerTransaction.getReceiver()), - new U64Value(this.innerTransaction.getNonce().valueOf()), - new BytesValue(this.innerTransaction.getData().valueOf()), - new BytesValue(this.innerTransaction.getSignature()), - ]); - - const data = `relayedTxV2@${argumentsString}`; - const payload = new TransactionPayload(data); - - let relayedTransaction = new Transaction({ - sender: this.relayerAddress, - receiver: this.innerTransaction.getSender(), - value: 0, - gasLimit: - this.innerTransactionGasLimit.valueOf() + - this.netConfig.MinGasLimit + - this.netConfig.GasPerDataByte * payload.length(), - data: payload, - chainID: this.netConfig.ChainID, - version: this.innerTransaction.getVersion(), - options: this.innerTransaction.getOptions(), - }); - - if (this.relayerNonce) { - relayedTransaction.setNonce(this.relayerNonce); - } - - return relayedTransaction; - } -} diff --git a/src/signableMessage.spec.ts b/src/signableMessage.spec.ts deleted file mode 100644 index 4480b66dc..000000000 --- a/src/signableMessage.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { assert } from "chai"; -import { SignableMessage } from "./signableMessage"; -import { loadTestWallets, TestWallet } from "./testutils"; - -describe("test signable message", () => { - let alice: TestWallet; - before(async function () { - ({ alice } = await loadTestWallets()); - }); - it("should create signableMessage", async () => { - const sm = new SignableMessage({ - address: alice.address, - message: Buffer.from("test message", "ascii"), - signature: Buffer.from("a".repeat(128), "hex"), - signer: "ElrondWallet", - }); - - const jsonSM = sm.toJSON(); - - // We just test that the returned object contains what was passed and the hex values are prefixed with 0x - assert.deepEqual( - jsonSM, - { - address: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - message: "0x74657374206d657373616765", - signature: - "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - version: 1, - signer: "ElrondWallet", - }, - "invalid signable message returned", - ); - }); -}); diff --git a/src/signableMessage.ts b/src/signableMessage.ts deleted file mode 100644 index 872407cf0..000000000 --- a/src/signableMessage.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { Address } from "./address"; -import { ISignature } from "./interface"; -import { interpretSignatureAsBuffer } from "./signature"; -import { MESSAGE_PREFIX } from "./constants"; -const createKeccakHash = require("keccak"); - -/** - * @deprecated Use {@link Message} instead. - */ -export class SignableMessage { - /** - * Actual message being signed. - */ - message: Buffer; - /** - * Signature obtained by a signer of type @param signer . - */ - signature: Buffer; - - /** - * Address of the wallet that performed the signing operation - */ - address: Address; - - /** - * Text representing the identifer for the application that signed the message - */ - signer: string; - - /** - * Number representing the signable message version - */ - version: number; - - public constructor(init?: Partial) { - this.message = Buffer.from([]); - this.signature = Buffer.from([]); - this.version = 1; - this.signer = "ErdJS"; - this.address = Address.empty(); - - Object.assign(this, init); - } - - serializeForSigning(): Buffer { - const messageSize = Buffer.from(this.message.length.toString()); - const signableMessage = Buffer.concat([messageSize, this.message]); - let bytesToHash = Buffer.concat([Buffer.from(MESSAGE_PREFIX), signableMessage]); - - return createKeccakHash("keccak256").update(bytesToHash).digest(); - } - - serializeForSigningRaw(): Buffer { - return Buffer.concat([this.getMessageSize(), this.message]); - } - - getSignature(): Buffer { - return this.signature; - } - - applySignature(signature: ISignature | Uint8Array) { - this.signature = interpretSignatureAsBuffer(signature); - } - - getMessageSize(): Buffer { - const messageSize = Buffer.alloc(4); - messageSize.writeUInt32BE(this.message.length, 0); - - return messageSize; - } - - toJSON(): object { - return { - address: this.address.bech32(), - message: "0x" + this.message.toString("hex"), - signature: "0x" + this.signature.toString("hex"), - version: this.version, - signer: this.signer, - }; - } -} diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 1f4dc2281..b73f48d53 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -2,6 +2,7 @@ import { Address } from "../address"; import { AsyncTimer } from "../asyncTimer"; import * as errors from "../errors"; import { ErrMock } from "../errors"; +import { ITransaction } from "../interface"; import { IAccountOnNetwork } from "../interfaceOfNetwork"; import { AccountOnNetwork, @@ -14,7 +15,7 @@ import { NetworkStatus, NonFungibleTokenOfAccountOnNetwork, } from "../networkProviders"; -import { IAddress, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "../networkProviders/interface"; +import { IAddress, INetworkProvider, IPagination } from "../networkProviders/interface"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { Transaction, TransactionHash } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; @@ -87,7 +88,7 @@ export class MockNetworkProvider implements INetworkProvider { ): Promise { throw new Error("Method not implemented."); } - sendTransactions(_txs: (ITransaction | ITransactionNext)[]): Promise { + sendTransactions(_txs: ITransaction[]): Promise { throw new Error("Method not implemented."); } getDefinitionOfFungibleToken(_tokenIdentifier: string): Promise { diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index c5e77ccb8..0dac24a84 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -113,7 +113,7 @@ export class TestWallet { async sync(provider: IAccountFetcher) { let accountOnNetwork = await provider.getAccount(this.address); - this.account.update(accountOnNetwork); + this.account.nonce = accountOnNetwork.nonce; return this; } } diff --git a/src/tokenTransferBuilders.spec.ts b/src/tokenTransferBuilders.spec.ts deleted file mode 100644 index e3fd02add..000000000 --- a/src/tokenTransferBuilders.spec.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { assert } from "chai"; -import { Address } from "./address"; -import { TokenTransfer } from "./tokens"; -import { - ESDTNFTTransferPayloadBuilder, - ESDTTransferPayloadBuilder, - MultiESDTNFTTransferPayloadBuilder, -} from "./tokenTransferBuilders"; - -describe("test token transfer builders", () => { - it("should work with ESDT transfers", () => { - const transfer = TokenTransfer.fungibleFromAmount("COUNTER-8b028f", "100.00", 0); - const payload = new ESDTTransferPayloadBuilder().setPayment(transfer).build(); - assert.equal(payload.toString(), "ESDTTransfer@434f554e5445522d386230323866@64"); - }); - - it("should work with ESDTNFT transfers (NFT)", () => { - const transfer = TokenTransfer.nonFungible("ERDJS-38f249", 1); - const payload = new ESDTNFTTransferPayloadBuilder() - .setPayment(transfer) - .setDestination(new Address("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx")) - .build(); - - assert.equal( - payload.toString(), - "ESDTNFTTransfer@4552444a532d333866323439@01@01@8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8", - ); - }); - - it("should work with ESDTNFT transfers (SFT)", () => { - const transfer = TokenTransfer.semiFungible("SEMI-9efd0f", 1, 5); - - const payload = new ESDTNFTTransferPayloadBuilder() - .setPayment(transfer) - .setDestination(new Address("erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7")) - .build(); - - assert.equal( - payload.toString(), - "ESDTNFTTransfer@53454d492d396566643066@01@05@5e60b9ff2385ea27ba0c3da4689779a8f7364acee1db0ee7bee59ac660a28974", - ); - }); - - it("should work with Multi ESDTNFT transfers", () => { - const transferOne = TokenTransfer.nonFungible("ERDJS-38f249", 1); - const transferTwo = TokenTransfer.fungibleFromAmount("BAR-c80d29", "10.00", 18); - const payload = new MultiESDTNFTTransferPayloadBuilder() - .setPayments([transferOne, transferTwo]) - .setDestination(new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th")) - .build(); - - assert.equal( - payload.toString(), - "MultiESDTNFTTransfer@0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1@02@4552444a532d333866323439@01@01@4241522d633830643239@@8ac7230489e80000", - ); - }); -}); diff --git a/src/tokenTransferBuilders.ts b/src/tokenTransferBuilders.ts deleted file mode 100644 index d4b6d37ad..000000000 --- a/src/tokenTransferBuilders.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, TypedValue, U16Value, U64Value } from "./abi"; -import { Address } from "./address"; -import { IAddress, ITokenTransfer } from "./interface"; -import { TokenTransfer } from "./tokens"; -import { TransactionPayload } from "./transactionPayload"; - -/** - * @deprecated Use {@link TransferTransactionsFactory} instead. - */ -export class ESDTTransferPayloadBuilder { - payment: ITokenTransfer = TokenTransfer.fungibleFromAmount("", "0", 0); - - setPayment(payment: ITokenTransfer): ESDTTransferPayloadBuilder { - this.payment = payment; - return this; - } - - build(): TransactionPayload { - let args: TypedValue[] = [ - // The token identifier - BytesValue.fromUTF8(this.payment.tokenIdentifier), - // The transfered amount - new BigUIntValue(this.payment.valueOf()), - ]; - - let { argumentsString } = new ArgSerializer().valuesToString(args); - let data = `ESDTTransfer@${argumentsString}`; - return new TransactionPayload(data); - } -} - -/** - * @deprecated Use {@link TransferTransactionsFactory} instead. - */ -export class ESDTNFTTransferPayloadBuilder { - payment: ITokenTransfer = TokenTransfer.nonFungible("", 0); - destination: IAddress = Address.empty(); - - setPayment(payment: ITokenTransfer): ESDTNFTTransferPayloadBuilder { - this.payment = payment; - return this; - } - - setDestination(destination: IAddress): ESDTNFTTransferPayloadBuilder { - this.destination = destination; - return this; - } - - build(): TransactionPayload { - let args: TypedValue[] = [ - // The token identifier - BytesValue.fromUTF8(this.payment.tokenIdentifier), - // The nonce of the token - new U64Value(this.payment.nonce), - // The transferred quantity - new BigUIntValue(this.payment.valueOf()), - // The destination address - new AddressValue(this.destination), - ]; - - let { argumentsString } = new ArgSerializer().valuesToString(args); - let data = `ESDTNFTTransfer@${argumentsString}`; - return new TransactionPayload(data); - } -} - -/** - * @deprecated Use {@link TransferTransactionsFactory} instead. - */ -export class MultiESDTNFTTransferPayloadBuilder { - payments: ITokenTransfer[] = []; - destination: IAddress = Address.empty(); - - setPayments(payments: ITokenTransfer[]): MultiESDTNFTTransferPayloadBuilder { - this.payments = payments; - return this; - } - - setDestination(destination: IAddress): MultiESDTNFTTransferPayloadBuilder { - this.destination = destination; - return this; - } - - build(): TransactionPayload { - let args: TypedValue[] = [ - // The destination address - new AddressValue(this.destination), - // Number of tokens - new U16Value(this.payments.length), - ]; - - for (const payment of this.payments) { - args.push( - ...[ - // The token identifier - BytesValue.fromUTF8(payment.tokenIdentifier), - // The nonce of the token - new U64Value(payment.nonce), - // The transfered quantity - new BigUIntValue(payment.valueOf()), - ], - ); - } - - let { argumentsString } = new ArgSerializer().valuesToString(args); - let data = `MultiESDTNFTTransfer@${argumentsString}`; - return new TransactionPayload(data); - } -} diff --git a/src/tokens.ts b/src/tokens.ts index b01c5edfc..f8c4a364f 100644 --- a/src/tokens.ts +++ b/src/tokens.ts @@ -339,17 +339,3 @@ export class TokenComputer { function decodeUnsignedNumber(arg: Buffer): number { return arg.readUIntBE(0, arg.length); } - -/** - * @deprecated use {@link TokenTransfer} instead. - */ -export class TokenPayment extends TokenTransfer { - constructor(tokenIdentifier: string, nonce: number, amountAsBigInteger: BigNumber.Value, numDecimals: number) { - super({ - tokenIdentifier, - nonce, - amountAsBigInteger, - numDecimals, - }); - } -} diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 10adef8c0..2a8ccbd5d 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -1,14 +1,10 @@ import { Address } from "./address"; -import { ITransaction, ITransactionNext } from "./networkProviders/interface"; +import { ITransaction } from "./interface"; import { TransactionLogs } from "./transactionLogs"; import { SmartContractResult } from "./transactionsOutcomeParsers"; import { TransactionStatus } from "./transactionStatus"; -export function prepareTransactionForBroadcasting(transaction: ITransaction | ITransactionNext): any { - if ("toSendable" in transaction) { - return transaction.toSendable(); - } - +export function prepareTransactionForBroadcasting(transaction: ITransaction): any { return { nonce: Number(transaction.nonce), value: transaction.value.toString(), From d74dc9476487f3b1d73175e990672e4966ada4cc Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 9 Dec 2024 16:23:32 +0200 Subject: [PATCH 069/214] Fix interaction tests --- src/abi/interaction.local.net.spec.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 298117045..7dbecbb03 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -113,11 +113,11 @@ describe("test smart contract interactor", function () { const executeTxHash = await provider.sendTransaction(transaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(executeTxHash); - const responseD = queryController.parseExecute(transactionOnNetwork); + const executeResponse = queryController.parseExecute(transactionOnNetwork); - assert.isTrue(response.contracts.length == 1); - assert.deepEqual(responseD.values[0], new BigNumber(42)); - assert.isTrue(response.returnCode == "ok"); + assert.isTrue(executeResponse.values.length == 1); + assert.deepEqual(executeResponse.values[0], new BigNumber(42)); + assert.isTrue(executeResponse.returnCode == "ok"); }); it("should interact with 'basic-features' (local testnet)", async function () { From cff78924541ae6008c73db9a442a85c73d1d643f Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 9 Dec 2024 16:28:11 +0200 Subject: [PATCH 070/214] code review follow up --- src/networkProviders/proxyNetworkProvider.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 1c2cbedef..6940bd0fa 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,3 +1,5 @@ +import { Address } from "../address"; +import { ESDT_CONTRACT_ADDRESS_HEX } from "../constants"; import { ErrContractQuery, ErrNetworkProvider } from "../errors"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; @@ -5,7 +7,7 @@ import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; -import { BaseUserAgent, EsdtContractAddress } from "./constants"; +import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; import { IAddress, INetworkProvider, IPagination, ITransaction, ITransactionNext } from "./interface"; import { NetworkConfig } from "./networkConfig"; @@ -182,7 +184,7 @@ export class ProxyNetworkProvider implements INetworkProvider { const encodedIdentifier = Buffer.from(identifier); const queryResponse = await this.queryContract({ - contract: EsdtContractAddress, + contract: Address.fromHex(ESDT_CONTRACT_ADDRESS_HEX), function: "getTokenProperties", arguments: [new Uint8Array(encodedIdentifier)], }); From 29c10e3d40e45c88ab90fca63887edd0553f1480 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 9 Dec 2024 16:35:43 +0200 Subject: [PATCH 071/214] Update to type SmartContractQueryInput --- src/abi/interaction.spec.ts | 34 +++++++++++++++------------------- src/smartContractQuery.ts | 12 ++---------- 2 files changed, 17 insertions(+), 29 deletions(-) diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 468d078a9..9d2cbade1 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -1,7 +1,7 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Address } from "../address"; -import { SmartContractQueryInput, SmartContractQueryResponse } from "../smartContractQuery"; +import { SmartContractQueryResponse } from "../smartContractQuery"; import { SmartContractController } from "../smartContracts"; import { loadAbiRegistry, @@ -228,15 +228,13 @@ describe("test smart contract interactor", function () { // Query; const interactionQuery = interaction.buildQuery(); - let response = await controller.query( - new SmartContractQueryInput({ - contract: interactionQuery.address, - arguments: interactionQuery.getEncodedArguments(), - function: interactionQuery.func.toString(), - caller: interactionQuery.caller, - value: BigInt(interactionQuery.value.toString()), - }), - ); + let response = await controller.query({ + contract: interactionQuery.address, + arguments: interactionQuery.getEncodedArguments(), + function: interactionQuery.func.toString(), + caller: interactionQuery.caller, + value: BigInt(interactionQuery.value.toString()), + }); assert.isTrue(response.length == 1); assert.deepEqual(response[0], new BigNumber(42)); @@ -299,15 +297,13 @@ describe("test smart contract interactor", function () { // Query "get()" const interactionQuery = getInteraction.buildQuery(); - let response = await controller.query( - new SmartContractQueryInput({ - contract: interactionQuery.address, - arguments: interactionQuery.getEncodedArguments(), - function: interactionQuery.func.toString(), - caller: interactionQuery.caller, - value: BigInt(interactionQuery.value.toString()), - }), - ); + let response = await controller.query({ + contract: interactionQuery.address, + arguments: interactionQuery.getEncodedArguments(), + function: interactionQuery.func.toString(), + caller: interactionQuery.caller, + value: BigInt(interactionQuery.value.toString()), + }); assert.deepEqual(response[0], new BigNumber(7)); let incrementTransaction = incrementInteraction diff --git a/src/smartContractQuery.ts b/src/smartContractQuery.ts index e2eea4836..1f0702d54 100644 --- a/src/smartContractQuery.ts +++ b/src/smartContractQuery.ts @@ -22,21 +22,13 @@ export class SmartContractQuery { } } -export class SmartContractQueryInput { +export type SmartContractQueryInput = { contract: Address; caller?: Address; value?: bigint; function: string; arguments: any[]; - - constructor(options: { contract: Address; caller?: Address; value?: bigint; function: string; arguments: any[] }) { - this.contract = options.contract; - this.caller = options.caller; - this.value = options.value; - this.function = options.function; - this.arguments = options.arguments; - } -} +}; export class SmartContractQueryResponse { function: string; From cbe8b5301a585a1efb7fe6838f97d73027ab8b54 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 9 Dec 2024 22:48:36 +0200 Subject: [PATCH 072/214] Fix integration tests --- src/testutils/wallets.ts | 5 +++++ src/transaction.local.net.spec.ts | 12 ++++++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index 0dac24a84..b66314447 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -116,4 +116,9 @@ export class TestWallet { this.account.nonce = accountOnNetwork.nonce; return this; } + + async getBalance(provider: IAccountFetcher) { + let accountOnNetwork = await provider.getAccount(this.address); + return accountOnNetwork.balance; + } } diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 8d8201dd9..45d3b8305 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -55,7 +55,7 @@ describe("test transaction", function () { await alice.sync(provider); await bob.sync(provider); - let initialBalanceOfBob = new BigNumber(bob.account.balance.toString()); + let initialBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); transactionOne.setNonce(alice.account.nonce); alice.account.incrementNonce(); @@ -71,7 +71,7 @@ describe("test transaction", function () { await watcher.awaitCompleted(transactionTwo.getHash().hex()); await bob.sync(provider); - let newBalanceOfBob = new BigNumber(bob.account.balance.toString()); + let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); assert.deepEqual(TokenTransfer.egldFromAmount(85).valueOf(), newBalanceOfBob.minus(initialBalanceOfBob)); }); @@ -94,7 +94,7 @@ describe("test transaction", function () { await alice.sync(provider); await bob.sync(provider); - let initialBalanceOfBob = new BigNumber(bob.account.balance.toString()); + let initialBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); transactionOne.setNonce(alice.account.nonce); await signTransaction({ transaction: transactionOne, wallet: alice }); @@ -102,7 +102,7 @@ describe("test transaction", function () { await watcher.awaitCompleted(transactionOne.getHash().hex()); await bob.sync(provider); - let newBalanceOfBob = new BigNumber(bob.account.balance.toString()); + let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); assert.deepEqual(TokenTransfer.egldFromAmount(42).valueOf(), newBalanceOfBob.minus(initialBalanceOfBob)); }); @@ -155,7 +155,7 @@ describe("test transaction", function () { await alice.sync(provider); await bob.sync(provider); - const initialBalanceOfBob = new BigNumber(bob.account.balance.toString()); + const initialBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); const transaction = factory.createTransactionForNativeTokenTransfer(alice.address, { receiver: bob.address, @@ -170,7 +170,7 @@ describe("test transaction", function () { await watcher.awaitCompleted(txHash); await bob.sync(provider); - const newBalanceOfBob = new BigNumber(bob.account.balance.toString()); + const newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); assert.deepEqual(TokenTransfer.egldFromAmount(42).valueOf(), newBalanceOfBob.minus(initialBalanceOfBob)); }); From 893d13a178fe4efb3f7641b2a3825f7bfa279199 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 10 Dec 2024 11:02:31 +0200 Subject: [PATCH 073/214] Update providers tests --- .../providers.dev.net.spec.ts | 45 +++++++++---------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 1b79d9d4e..6a164a0b8 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -192,7 +192,7 @@ describe("test network providers on devnet: Proxy and API", function () { proxyResponse.decimals = 0; } - it("should be able to send transaction(s)", async function () { + it.only("should be able to send transaction(s)", async function () { this.timeout(5000); const txs = [ @@ -203,40 +203,35 @@ describe("test network providers on devnet: Proxy and API", function () { sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", data: new Uint8Array(Buffer.from("test")), gasPrice: 1000000000n, - gasLimit: 50000n, + gasLimit: 100000n, chainID: "D", - version: 1, - signature: new Uint8Array( - Buffer.from( - "c8eb539e486db7d703d8c70cab3b7679113f77c4685d8fcc94db027ceacc6b8605115034355386dffd7aa12e63dbefa03251a2f1b1d971f52250187298d12900", - ), + version: 2, + signature: Buffer.from( + "c8eb539e486db7d703d8c70cab3b7679113f77c4685d8fcc94db027ceacc6b8605115034355386dffd7aa12e63dbefa03251a2f1b1d971f52250187298d12900", + "hex", ), - senderUsername: "", - receiverUsername: "", - guardian: "", - guardianSignature: new Uint8Array(), - options: 0, }, + { nonce: 43n, value: 1n, receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", gasPrice: 1000000000n, - gasLimit: 50000n, + gasLimit: 100000n, chainID: "D", - version: 1, - signature: new Uint8Array( - Buffer.from( - "9c4c22d0ae1b5a10c39583a5ab9020b00b27aa69d4ac8ab4922620dbf0df4036ed890f9946d38a9d0c85d6ac485c0d9b2eac0005e752f249fd0ad863b0471d02", - ), + version: 2, + signature: Buffer.from( + "9c4c22d0ae1b5a10c39583a5ab9020b00b27aa69d4ac8ab4922620dbf0df4036ed890f9946d38a9d0c85d6ac485c0d9b2eac0005e752f249fd0ad863b0471d02", + "hex", ), - senderUsername: "", - receiverUsername: "", - guardian: "", - guardianSignature: new Uint8Array(), - options: 0, - data: new Uint8Array(), + }, + { + nonce: 44n, + chainID: "D", + receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", + sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", + gasLimit: 100000n, }, ]; @@ -412,7 +407,7 @@ describe("test network providers on devnet: Proxy and API", function () { assert.deepEqual(proxyResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==", "base64")]); }); - it("should send both `Transaction` ", async function () { + it.only("should send both `Transaction` ", async function () { this.timeout(50000); const transaction: ITransaction = { From 5069158affabfa0b013783529fa146d9950c58b3 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 10 Dec 2024 11:13:39 +0200 Subject: [PATCH 074/214] Fix providers tests --- .../providers.dev.net.spec.ts | 35 +++++++++---------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 6a164a0b8..d0073b9ef 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -197,47 +197,44 @@ describe("test network providers on devnet: Proxy and API", function () { const txs = [ { - nonce: 42n, - value: 1n, - receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", - sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", - data: new Uint8Array(Buffer.from("test")), + nonce: 103n, + receiver: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", + sender: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", gasPrice: 1000000000n, - gasLimit: 100000n, + gasLimit: 50000n, chainID: "D", version: 2, signature: Buffer.from( - "c8eb539e486db7d703d8c70cab3b7679113f77c4685d8fcc94db027ceacc6b8605115034355386dffd7aa12e63dbefa03251a2f1b1d971f52250187298d12900", + "498d5abb9f8eb69cc75f24320e8929dadbfa855ffac220d5e92175a83be68e0437801af3a1411e3d839738230097a1c38da5c8c4df3f345defc5d40300675900", "hex", ), }, { - nonce: 43n, - value: 1n, - receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", - sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", + nonce: 104n, + receiver: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", + sender: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", gasPrice: 1000000000n, - gasLimit: 100000n, + gasLimit: 50000n, chainID: "D", version: 2, signature: Buffer.from( - "9c4c22d0ae1b5a10c39583a5ab9020b00b27aa69d4ac8ab4922620dbf0df4036ed890f9946d38a9d0c85d6ac485c0d9b2eac0005e752f249fd0ad863b0471d02", + "341a2f3b738fbd20692e3bbd1cb36cb5f4ce9c0a9acc0cf4322269c0fcf34fd6bb59cd94062a9a4730e47f41b1ef3e29b69c6ab2a2a4dca9c9a7724681bc1708", "hex", ), }, { - nonce: 44n, + nonce: 77n, chainID: "D", - receiver: "erd1testnlersh4z0wsv8kjx39me4rmnvjkwu8dsaea7ukdvvc9z396qykv7z7", - sender: "erd15x2panzqvfxul2lvstfrmdcl5t4frnsylfrhng8uunwdssxw4y9succ9sq", - gasLimit: 100000n, + receiver: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", + sender: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", + gasLimit: 50000n, }, ]; const expectedHashes = [ - "6e2fa63ea02937f00d7549f3e4eb9af241e4ac13027aa65a5300816163626c01", - "37d7e84313a5baea2a61c6ab10bb29b52bc54f7ac9e3918a9faeb1e08f42081c", + "61b4f2561fc57bfb8b8971ed23cd64259b664bc0404ea7a0449def8ceef24b08", + "30274b60b5635f981fa89ccfe726a34ca7121caa5d34123021c77a5c64cc9163", null, ]; From 3192410a505809f0583e1076e0522e4201020637 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 10 Dec 2024 11:50:29 +0200 Subject: [PATCH 075/214] Update providers tests --- .../providers.dev.net.spec.ts | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index d0073b9ef..258703685 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -192,7 +192,7 @@ describe("test network providers on devnet: Proxy and API", function () { proxyResponse.decimals = 0; } - it.only("should be able to send transaction(s)", async function () { + it("should be able to send transaction(s)", async function () { this.timeout(5000); const txs = [ @@ -208,6 +208,13 @@ describe("test network providers on devnet: Proxy and API", function () { "498d5abb9f8eb69cc75f24320e8929dadbfa855ffac220d5e92175a83be68e0437801af3a1411e3d839738230097a1c38da5c8c4df3f345defc5d40300675900", "hex", ), + senderUsername: "", + receiverUsername: "", + guardian: "", + guardianSignature: new Uint8Array(), + options: 0, + data: new Uint8Array(), + value: 0n, }, { @@ -222,6 +229,13 @@ describe("test network providers on devnet: Proxy and API", function () { "341a2f3b738fbd20692e3bbd1cb36cb5f4ce9c0a9acc0cf4322269c0fcf34fd6bb59cd94062a9a4730e47f41b1ef3e29b69c6ab2a2a4dca9c9a7724681bc1708", "hex", ), + value: 0n, + senderUsername: "", + receiverUsername: "", + guardian: "", + guardianSignature: new Uint8Array(), + options: 0, + data: new Uint8Array(), }, { nonce: 77n, @@ -229,6 +243,16 @@ describe("test network providers on devnet: Proxy and API", function () { receiver: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", sender: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", gasLimit: 50000n, + gasPrice: 1000000000n, + value: 0n, + senderUsername: "", + receiverUsername: "", + guardian: "", + guardianSignature: new Uint8Array(), + options: 0, + data: new Uint8Array(), + version: 1, + signature: new Uint8Array(), }, ]; @@ -404,7 +428,7 @@ describe("test network providers on devnet: Proxy and API", function () { assert.deepEqual(proxyResponse.logs.events[0].additionalData, [Buffer.from("dGVzdA==", "base64")]); }); - it.only("should send both `Transaction` ", async function () { + it("should send both `Transaction` ", async function () { this.timeout(50000); const transaction: ITransaction = { From 9916699e97b6106b90c90d87617905a0d104ec92 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 10 Dec 2024 15:22:24 +0200 Subject: [PATCH 076/214] Remove ITransaction interface and update Transaction to follow specs --- src/abi/interaction.spec.ts | 4 +- src/abi/interface.ts | 26 +- src/abi/nativeSerializer.ts | 6 +- src/abi/smartContract.spec.ts | 20 +- src/abi/smartContract.ts | 4 +- src/abi/typesystem/address.ts | 3 +- .../accountTransactionsFactory.spec.ts | 44 ++- .../accountTransactionsFactory.ts | 9 +- src/converters/transactionsConverter.ts | 17 +- src/converters/transactionsConverters.spec.ts | 11 +- .../delegationTransactionsFactory.spec.ts | 156 +++++++--- .../delegationTransactionsFactory.ts | 39 ++- src/entrypoints/entrypoints.spec.ts | 2 +- src/entrypoints/entrypoints.ts | 2 +- src/interface.ts | 18 -- src/networkProviders/apiNetworkProvider.ts | 8 +- src/networkProviders/interface.ts | 8 +- .../providers.dev.net.spec.ts | 64 ++-- src/networkProviders/proxyNetworkProvider.ts | 8 +- src/proto/serializer.spec.ts | 48 ++- src/proto/serializer.ts | 14 +- .../relayedTransactionsFactory.spec.ts | 39 +-- src/relayed/relayedTransactionsFactory.ts | 19 +- src/relayed/resources.ts | 6 +- .../smartContractTransactionsFactory.spec.ts | 114 +++++-- src/testutils/mockNetworkProvider.ts | 7 +- src/testutils/utils.ts | 5 +- src/tokenManagement/resources.ts | 7 +- .../tokenManagementTransactionFactory.spec.ts | 75 ++--- .../tokenManagementTransactionsFactory.ts | 63 ++-- src/tokenTransfersDataBuilder.ts | 6 +- src/transaction.local.net.spec.ts | 25 +- src/transaction.spec.ts | 291 +++++++++--------- src/transaction.ts | 102 +++--- src/transactionBuilder.ts | 15 +- src/transactionComputer.ts | 32 +- src/transactionOnNetwork.ts | 4 +- .../transferTransactionsFactory.spec.ts | 52 ++-- src/transfers/transferTransactionsFactory.ts | 110 +++---- 39 files changed, 788 insertions(+), 695 deletions(-) diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 75418b317..b3a79a7d7 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -190,8 +190,8 @@ describe("test smart contract interactor", function () { transaction, new Transaction({ chainID: "T", - sender: alice.toBech32(), - receiver: dummyAddress.toBech32(), + sender: alice, + receiver: dummyAddress, data: Buffer.from("ESDTTransfer@464f4f2d616263646566@64@676574556c74696d617465416e73776572"), gasLimit: 543210n, value: 0n, diff --git a/src/abi/interface.ts b/src/abi/interface.ts index e51c5b70b..9fc396566 100644 --- a/src/abi/interface.ts +++ b/src/abi/interface.ts @@ -1,5 +1,5 @@ import { Address } from "../address"; -import { IChainID, IGasLimit, IGasPrice, ITransactionValue } from "../interface"; +import { ITransactionValue } from "../interface"; import { Transaction } from "../transaction"; import { ReturnCode } from "./returnCode"; import { TypedValue } from "./typesystem"; @@ -33,10 +33,10 @@ export interface DeployArguments { code: ICode; codeMetadata?: ICodeMetadata; initArguments?: any[]; - value?: ITransactionValue; - gasLimit: IGasLimit; - gasPrice?: IGasPrice; - chainID: IChainID; + value?: bigint; + gasLimit: bigint; + gasPrice?: bigint; + chainID: string; deployer: Address; } @@ -44,21 +44,21 @@ export interface UpgradeArguments { code: ICode; codeMetadata?: ICodeMetadata; initArguments?: any[]; - value?: ITransactionValue; - gasLimit: IGasLimit; - gasPrice?: IGasPrice; - chainID: IChainID; + value?: bigint; + gasLimit: bigint; + gasPrice?: bigint; + chainID: string; caller: Address; } export interface CallArguments { func: IContractFunction; args?: any[]; - value?: ITransactionValue; - gasLimit: IGasLimit; + value?: bigint; + gasLimit: bigint; receiver?: Address; - gasPrice?: IGasPrice; - chainID: IChainID; + gasPrice?: bigint; + chainID: string; caller: Address; } diff --git a/src/abi/nativeSerializer.ts b/src/abi/nativeSerializer.ts index e1c10c610..85ba5b7cb 100644 --- a/src/abi/nativeSerializer.ts +++ b/src/abi/nativeSerializer.ts @@ -67,7 +67,7 @@ import { export namespace NativeTypes { export type NativeBuffer = Buffer | string; export type NativeBytes = Buffer | { valueOf(): Buffer } | string; - export type NativeAddress = string | Buffer | IAddress | { getAddress(): IAddress }; + export type NativeAddress = string | Buffer | Address | { getAddress(): IAddress }; export type NativeBigNumber = BigNumber.Value | bigint; } @@ -403,9 +403,9 @@ export namespace NativeSerializer { export function convertNativeToAddress( native: NativeTypes.NativeAddress, errorContext: ArgumentErrorContext, - ): IAddress { + ): Address { if ((native).bech32) { - return native; + return
native; } if ((native).getAddress) { return (native).getAddress(); diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index abbcef788..b6424fcd5 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -42,7 +42,7 @@ describe("test contract", () => { let contract = new SmartContract(); let deployTransaction = contract.deploy({ code: Code.fromBuffer(Buffer.from([1, 2, 3, 4])), - gasLimit: 1000000, + gasLimit: 1000000n, chainID: chainID, deployer: alice.address, }); @@ -97,7 +97,7 @@ describe("test contract", () => { let callTransactionOne = contract.call({ func: new ContractFunction("helloEarth"), args: [new U32Value(5), BytesValue.fromHex("0123")], - gasLimit: 150000, + gasLimit: 150000n, chainID: chainID, caller: alice.address, }); @@ -105,7 +105,7 @@ describe("test contract", () => { let callTransactionTwo = contract.call({ func: new ContractFunction("helloMars"), args: [new U32Value(5), BytesValue.fromHex("0123")], - gasLimit: 1500000, + gasLimit: 1500000n, chainID: chainID, caller: alice.address, }); @@ -161,7 +161,7 @@ describe("test contract", () => { let deployTransaction = contract.upgrade({ code: Code.fromBuffer(Buffer.from([1, 2, 3, 4])), - gasLimit: 1000000, + gasLimit: 1000000n, chainID: chainID, caller: alice.address, }); @@ -233,7 +233,7 @@ describe("test contract", () => { func: "foo", args: [new U8Value(1), new U8Value(2), new U8Value(3)], chainID: "D", - gasLimit: 1000000, + gasLimit: 1000000n, caller: callerAddress, }); }, "Wrong number of arguments for endpoint foo: expected between 0 and 1 arguments, have 3"); @@ -243,7 +243,7 @@ describe("test contract", () => { func: "foo", args: [[new U8Value(1), new U8Value(2), new U8Value(3)]], chainID: "D", - gasLimit: 1000000, + gasLimit: 1000000n, caller: callerAddress, }); @@ -252,7 +252,7 @@ describe("test contract", () => { func: "foo", args: [[1, 2, 3]], chainID: "D", - gasLimit: 1000000, + gasLimit: 1000000n, caller: callerAddress, }); @@ -302,7 +302,7 @@ describe("test contract", () => { func: "foo", args: [new U8Value(1), new U8Value(2), new U8Value(3)], chainID: "D", - gasLimit: 1000000, + gasLimit: 1000000n, caller: callerAddress, }); }, "Invalid argument: Wrong argument type for endpoint foo: typed value provided; expected variadic type, have U8Value"); @@ -312,7 +312,7 @@ describe("test contract", () => { func: "foo", args: [VariadicValue.fromItems(new U8Value(1), new U8Value(2), new U8Value(3))], chainID: "D", - gasLimit: 1000000, + gasLimit: 1000000n, caller: callerAddress, }); @@ -321,7 +321,7 @@ describe("test contract", () => { func: "foo", args: [1, 2, 3], chainID: "D", - gasLimit: 1000000, + gasLimit: 1000000n, caller: callerAddress, }); diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 6b1b4db08..7b5f40a58 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -247,12 +247,12 @@ export class SmartContract implements ISmartContract { }); args = args || []; - value = value || 0; + value = value || 0n; const transaction = factory.createTransactionForExecute(caller, { contract: receiver ? receiver : this.getAddress(), function: func.toString(), - gasLimit: BigInt(gasLimit.valueOf()), + gasLimit: gasLimit, arguments: args, }); diff --git a/src/abi/typesystem/address.ts b/src/abi/typesystem/address.ts index ef8db6d02..81d3c6750 100644 --- a/src/abi/typesystem/address.ts +++ b/src/abi/typesystem/address.ts @@ -1,5 +1,4 @@ import { Address } from "../../address"; -import { IAddress } from "../../interface"; import { PrimitiveType, PrimitiveValue } from "./types"; export class AddressType extends PrimitiveType { @@ -21,7 +20,7 @@ export class AddressValue extends PrimitiveValue { static ClassName = "AddressValue"; private readonly value: Address; - constructor(value: IAddress) { + constructor(value: Address) { super(new AddressType()); this.value = Address.newFromBech32(value.bech32()); } diff --git a/src/accountManagement/accountTransactionsFactory.spec.ts b/src/accountManagement/accountTransactionsFactory.spec.ts index 77ce1a041..43129eb6b 100644 --- a/src/accountManagement/accountTransactionsFactory.spec.ts +++ b/src/accountManagement/accountTransactionsFactory.spec.ts @@ -15,8 +15,14 @@ describe("test account transactions factory", function () { keyValuePairs: keyValuePairs, }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); assert.equal(Buffer.from(transaction.data).toString(), "SaveKeyValue@6b657930@76616c756530"); assert.equal(transaction.value, 0n); assert.equal(transaction.chainID, config.chainID); @@ -24,8 +30,8 @@ describe("test account transactions factory", function () { }); it("should create 'Transaction' for setting guardian", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const guardian = Address.fromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const guardian = Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); const serviceID = "MultiversXTCSService"; const transaction = factory.createTransactionForSettingGuardian(sender, { @@ -33,8 +39,14 @@ describe("test account transactions factory", function () { serviceID: serviceID, }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); assert.equal( Buffer.from(transaction.data).toString(), "SetGuardian@8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8@4d756c7469766572735854435353657276696365", @@ -49,8 +61,14 @@ describe("test account transactions factory", function () { const transaction = factory.createTransactionForGuardingAccount(sender); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); assert.equal(Buffer.from(transaction.data).toString(), "GuardAccount"); assert.equal(transaction.value, 0n); assert.equal(transaction.chainID, config.chainID); @@ -62,8 +80,14 @@ describe("test account transactions factory", function () { const transaction = factory.createTransactionForUnguardingAccount(sender); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); assert.equal(Buffer.from(transaction.data).toString(), "UnGuardAccount"); assert.equal(transaction.value, 0n); assert.equal(transaction.chainID, config.chainID); diff --git a/src/accountManagement/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts index 8fdeed7db..37b17662f 100644 --- a/src/accountManagement/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -1,5 +1,4 @@ import { Address } from "../address"; -import { IAddress } from "../interface"; import { Transaction } from "../transaction"; import { TransactionBuilder } from "../transactionBuilder"; import { SaveKeyValueInput, SetGuardianInput } from "./resources"; @@ -23,7 +22,7 @@ export class AccountTransactionsFactory { this.config = options.config; } - createTransactionForSavingKeyValue(sender: IAddress, options: SaveKeyValueInput): Transaction { + createTransactionForSavingKeyValue(sender: Address, options: SaveKeyValueInput): Transaction { const functionName = "SaveKeyValue"; const keyValueParts = this.computeDataPartsForSavingKeyValue(options.keyValuePairs); const dataParts = [functionName, ...keyValueParts]; @@ -61,7 +60,7 @@ export class AccountTransactionsFactory { return dataParts; } - createTransactionForSettingGuardian(sender: IAddress, options: SetGuardianInput): Transaction { + createTransactionForSettingGuardian(sender: Address, options: SetGuardianInput): Transaction { const dataParts = [ "SetGuardian", Address.fromBech32(options.guardianAddress.bech32()).toHex(), @@ -78,7 +77,7 @@ export class AccountTransactionsFactory { }).build(); } - createTransactionForGuardingAccount(sender: IAddress): Transaction { + createTransactionForGuardingAccount(sender: Address): Transaction { const dataParts = ["GuardAccount"]; return new TransactionBuilder({ @@ -91,7 +90,7 @@ export class AccountTransactionsFactory { }).build(); } - createTransactionForUnguardingAccount(sender: IAddress): Transaction { + createTransactionForUnguardingAccount(sender: Address): Transaction { const dataParts = ["UnGuardAccount"]; return new TransactionBuilder({ diff --git a/src/converters/transactionsConverter.ts b/src/converters/transactionsConverter.ts index 92cb6f757..93d70608f 100644 --- a/src/converters/transactionsConverter.ts +++ b/src/converters/transactionsConverter.ts @@ -1,13 +1,14 @@ -import { IPlainTransactionObject, ITransaction } from "../interface"; +import { Address } from "../address"; +import { IPlainTransactionObject } from "../interface"; import { Transaction } from "../transaction"; export class TransactionsConverter { - public transactionToPlainObject(transaction: ITransaction): IPlainTransactionObject { + public transactionToPlainObject(transaction: Transaction): IPlainTransactionObject { const plainObject = { nonce: Number(transaction.nonce), value: transaction.value.toString(), - receiver: transaction.receiver, - sender: transaction.sender, + receiver: transaction.receiver.bech32(), + sender: transaction.sender.bech32(), senderUsername: this.toBase64OrUndefined(transaction.senderUsername), receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), gasPrice: Number(transaction.gasPrice), @@ -16,7 +17,7 @@ export class TransactionsConverter { chainID: transaction.chainID.valueOf(), version: transaction.version, options: transaction.options == 0 ? undefined : transaction.options, - guardian: transaction.guardian ? transaction.guardian : undefined, + guardian: transaction.guardian.isEmpty() ? undefined : transaction.guardian.bech32(), signature: this.toHexOrUndefined(transaction.signature), guardianSignature: this.toHexOrUndefined(transaction.guardianSignature), }; @@ -36,11 +37,11 @@ export class TransactionsConverter { const transaction = new Transaction({ nonce: BigInt(object.nonce), value: BigInt(object.value || ""), - receiver: object.receiver, + receiver: Address.newFromBech32(object.receiver), receiverUsername: this.bufferFromBase64(object.receiverUsername).toString(), - sender: object.sender, + sender: Address.newFromBech32(object.sender), senderUsername: this.bufferFromBase64(object.senderUsername).toString(), - guardian: object.guardian, + guardian: object.guardian ? Address.newFromBech32(object.guardian) : Address.empty(), gasPrice: BigInt(object.gasPrice), gasLimit: BigInt(object.gasLimit), data: this.bufferFromBase64(object.data), diff --git a/src/converters/transactionsConverters.spec.ts b/src/converters/transactionsConverters.spec.ts index 2d91adf06..fe1fe20b2 100644 --- a/src/converters/transactionsConverters.spec.ts +++ b/src/converters/transactionsConverters.spec.ts @@ -1,4 +1,5 @@ import { assert } from "chai"; +import { Address } from "../address"; import { Transaction } from "../transaction"; import { TransactionsConverter } from "./transactionsConverter"; @@ -7,14 +8,14 @@ describe("test transactions converter", async () => { const converter = new TransactionsConverter(); const transaction = new Transaction({ - nonce: 90, + nonce: 90n, value: BigInt("123456789000000000000000000000"), - sender: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - receiver: "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", + sender: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + receiver: Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), senderUsername: "alice", receiverUsername: "bob", - gasPrice: 1000000000, - gasLimit: 80000, + gasPrice: 1000000000n, + gasLimit: 80000n, data: Buffer.from("hello"), chainID: "localnet", version: 2, diff --git a/src/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index 6a9e53f88..eece6f1cd 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -21,11 +21,11 @@ describe("test delegation transactions factory", function () { amount: value, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal( - transaction.receiver, - Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, config.addressHrp).bech32(), + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); + assert.deepEqual(transaction.receiver, Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, config.addressHrp)); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("createNewDelegationContract@010f0cf064dd59200000@0a")); assert.equal(transaction.gasLimit, 60126500n); @@ -57,8 +57,14 @@ describe("test delegation transactions factory", function () { signedMessages: [mockMessage.getSignature()], }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -84,8 +90,14 @@ describe("test delegation transactions factory", function () { publicKeys: [publicKey], }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -110,8 +122,14 @@ describe("test delegation transactions factory", function () { publicKeys: [publicKey], }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -136,8 +154,14 @@ describe("test delegation transactions factory", function () { publicKeys: [publicKey], }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -163,8 +187,14 @@ describe("test delegation transactions factory", function () { publicKeys: [publicKey], }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -177,8 +207,10 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for unjailing nodes", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const delegationContract = Address.newFromBech32( + "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc", + ); const publicKey = new ValidatorPublicKey( Buffer.from( "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", @@ -190,8 +222,14 @@ describe("test delegation transactions factory", function () { publicKeys: [publicKey], amount: 25000000000000000000n, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -203,8 +241,10 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for changing service fee", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const delegationContract = Address.newFromBech32( + "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc", + ); const serviceFee = 10n; const transaction = delegationFactory.createTransactionForChangingServiceFee(sender, { @@ -212,8 +252,14 @@ describe("test delegation transactions factory", function () { serviceFee: serviceFee, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("changeServiceFee@0a")); assert.equal(transaction.value, 0n); @@ -229,8 +275,14 @@ describe("test delegation transactions factory", function () { delegationCap: delegationCap, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("modifyTotalDelegationCap@010f0cf064dd59200000")); assert.equal(transaction.value, 0n); @@ -244,8 +296,14 @@ describe("test delegation transactions factory", function () { delegationContract: delegationContract, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setAutomaticActivation@74727565")); assert.equal(transaction.value, 0n); @@ -259,8 +317,14 @@ describe("test delegation transactions factory", function () { delegationContract: delegationContract, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setAutomaticActivation@66616c7365")); assert.equal(transaction.value, 0n); @@ -274,8 +338,14 @@ describe("test delegation transactions factory", function () { delegationContract: delegationContract, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setCheckCapOnReDelegateRewards@74727565")); assert.equal(transaction.value, 0n); @@ -289,16 +359,24 @@ describe("test delegation transactions factory", function () { delegationContract: delegationContract, }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setCheckCapOnReDelegateRewards@66616c7365")); assert.equal(transaction.value, 0n); }); it("should create 'Transaction' for setting metadata", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const delegationContract = Address.newFromBech32( + "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc", + ); const transaction = delegationFactory.createTransactionForSettingMetadata(sender, { delegationContract: delegationContract, @@ -307,8 +385,14 @@ describe("test delegation transactions factory", function () { identifier: "identifier", }); - assert.equal(transaction.sender, "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setMetaData@6e616d65@77656273697465@6964656e746966696572")); assert.equal(transaction.value, 0n); diff --git a/src/delegation/delegationTransactionsFactory.ts b/src/delegation/delegationTransactionsFactory.ts index 8aa26e38f..bd71fcd3b 100644 --- a/src/delegation/delegationTransactionsFactory.ts +++ b/src/delegation/delegationTransactionsFactory.ts @@ -2,7 +2,6 @@ import { ArgSerializer, BigUIntValue, BytesValue, StringValue } from "../abi"; import { Address } from "../address"; import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../constants"; import { Err } from "../errors"; -import { IAddress } from "../interface"; import { Transaction } from "../transaction"; import { TransactionBuilder } from "../transactionBuilder"; import * as resources from "./resources"; @@ -36,7 +35,7 @@ export class DelegationTransactionsFactory { } createTransactionForNewDelegationContract( - sender: IAddress, + sender: Address, options: resources.NewDelegationContractInput, ): Transaction { const dataParts = [ @@ -61,7 +60,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForAddingNodes(sender: IAddress, options: resources.AddNodesInput): Transaction { + createTransactionForAddingNodes(sender: Address, options: resources.AddNodesInput): Transaction { if (options.publicKeys.length !== options.signedMessages.length) { throw new Err("The number of public keys should match the number of signed messages"); } @@ -88,7 +87,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForRemovingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { + createTransactionForRemovingNodes(sender: Address, options: resources.ManageNodesInput): Transaction { const dataParts = ["removeNodes"]; for (const key of options.publicKeys) { @@ -106,7 +105,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForStakingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { + createTransactionForStakingNodes(sender: Address, options: resources.ManageNodesInput): Transaction { let dataParts = ["stakeNodes"]; for (const key of options.publicKeys) { @@ -129,7 +128,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnbondingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { + createTransactionForUnbondingNodes(sender: Address, options: resources.ManageNodesInput): Transaction { let dataParts = ["unBondNodes"]; for (const key of options.publicKeys) { @@ -152,7 +151,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnstakingNodes(sender: IAddress, options: resources.ManageNodesInput): Transaction { + createTransactionForUnstakingNodes(sender: Address, options: resources.ManageNodesInput): Transaction { let dataParts = ["unStakeNodes"]; for (const key of options.publicKeys) { @@ -175,7 +174,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForUnjailingNodes(sender: IAddress, options: resources.UnjailingNodesInput): Transaction { + createTransactionForUnjailingNodes(sender: Address, options: resources.UnjailingNodesInput): Transaction { const dataParts = ["unJailNodes"]; for (const key of options.publicKeys) { @@ -194,7 +193,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForChangingServiceFee(sender: IAddress, options: resources.ChangeServiceFee): Transaction { + createTransactionForChangingServiceFee(sender: Address, options: resources.ChangeServiceFee): Transaction { const dataParts = [ "changeServiceFee", this.argSerializer.valuesToStrings([new BigUIntValue(options.serviceFee)])[0], @@ -213,7 +212,7 @@ export class DelegationTransactionsFactory { } createTransactionForModifyingDelegationCap( - sender: IAddress, + sender: Address, options: resources.ModifyDelegationCapInput, ): Transaction { const dataParts = [ @@ -234,7 +233,7 @@ export class DelegationTransactionsFactory { } createTransactionForSettingAutomaticActivation( - sender: IAddress, + sender: Address, options: resources.ManageDelegationContractInput, ): Transaction { const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new StringValue("true")])[0]]; @@ -252,7 +251,7 @@ export class DelegationTransactionsFactory { } createTransactionForUnsettingAutomaticActivation( - sender: IAddress, + sender: Address, options: resources.ManageDelegationContractInput, ): Transaction { const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new StringValue("false")])[0]]; @@ -270,7 +269,7 @@ export class DelegationTransactionsFactory { } createTransactionForSettingCapCheckOnRedelegateRewards( - sender: IAddress, + sender: Address, options: resources.ManageDelegationContractInput, ): Transaction { const dataParts = [ @@ -291,7 +290,7 @@ export class DelegationTransactionsFactory { } createTransactionForUnsettingCapCheckOnRedelegateRewards( - sender: IAddress, + sender: Address, options: resources.ManageDelegationContractInput, ): Transaction { const dataParts = [ @@ -311,7 +310,7 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForSettingMetadata(sender: IAddress, options: resources.SetContractMetadataInput): Transaction { + createTransactionForSettingMetadata(sender: Address, options: resources.SetContractMetadataInput): Transaction { const dataParts = [ "setMetaData", ...this.argSerializer.valuesToStrings([ @@ -334,29 +333,29 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForWithdrawing(_sender: IAddress, _options: resources.ManageDelegationContractInput): Transaction { + createTransactionForWithdrawing(_sender: Address, _options: resources.ManageDelegationContractInput): Transaction { throw new Error("Method not implemented."); } - createTransactionForUndelegating(_sender: IAddress, _options: resources.DelegateActionsInput): Transaction { + createTransactionForUndelegating(_sender: Address, _options: resources.DelegateActionsInput): Transaction { throw new Error("Method not implemented."); } createTransactionForRedelegatingRewards( - _sender: IAddress, + _sender: Address, _options: resources.ManageDelegationContractInput, ): Transaction { throw new Error("Method not implemented."); } createTransactionForClaimingRewards( - _sender: IAddress, + _sender: Address, _options: resources.ManageDelegationContractInput, ): Transaction { throw new Error("Method not implemented."); } - createTransactionForDelegating(_sender: IAddress, _options: resources.DelegateActionsInput): Transaction { + createTransactionForDelegating(_sender: Address, _options: resources.DelegateActionsInput): Transaction { throw new Error("Method not implemented."); } diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index f0a850398..e2173e05f 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -115,7 +115,7 @@ describe("TestEntrypoint", () => { ); assert.equal(relayedTransaction.chainID, "D"); assert.deepEqual( - relayedTransaction.data, + Buffer.from(relayedTransaction.data), Buffer.from( "relayedTxV2@0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1@012fd1@68656c6c6f@c1eed3ac766d6b94aa53a1348d38eac8db60be0a1b2d0873247b61b8b25bbcb45bf9c1518227bcadd5044d4c027bdb935e0164243b2b2df9a5b250a10aca260e", ), diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 76e722548..7ee11e047 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -40,7 +40,7 @@ class NetworkEntrypoint { } verifyTransactionSignature(transaction: Transaction): boolean { - const verifier = UserVerifier.fromAddress(Address.fromBech32(transaction.sender)); + const verifier = UserVerifier.fromAddress(transaction.sender); const txComputer = new TransactionComputer(); return verifier.verify(txComputer.computeBytesForVerifying(transaction), transaction.signature); } diff --git a/src/interface.ts b/src/interface.ts index a3fb3b2c2..d1258c1ed 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -82,21 +82,3 @@ export interface ITokenTransfer { readonly amountAsBigInteger: BigNumber.Value; valueOf(): BigNumber.Value; } - -export interface ITransaction { - sender: string; - receiver: string; - gasLimit: bigint; - chainID: string; - nonce: bigint; - value: bigint; - senderUsername: string; - receiverUsername: string; - gasPrice: bigint; - data: Uint8Array; - version: number; - options: number; - guardian: string; - signature: Uint8Array; - guardianSignature: Uint8Array; -} diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index d6445a096..7b2bd6a4d 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,6 +1,6 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; -import { ITransaction } from "../interface"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; +import { Transaction } from "../transaction"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; @@ -147,17 +147,17 @@ export class ApiNetworkProvider implements INetworkProvider { return status; } - async sendTransaction(tx: ITransaction): Promise { + async sendTransaction(tx: Transaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transactions", transaction); return response.txHash; } - async sendTransactions(txs: ITransaction[]): Promise { + async sendTransactions(txs: Transaction[]): Promise { return await this.backingProxyNetworkProvider.sendTransactions(txs); } - async simulateTransaction(tx: ITransaction): Promise { + async simulateTransaction(tx: Transaction): Promise { return await this.backingProxyNetworkProvider.simulateTransaction(tx); } diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 675f27db2..2ddd3b5bd 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,5 +1,5 @@ -import { ITransaction } from "../interface"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; +import { Transaction } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { AccountOnNetwork } from "./accounts"; @@ -79,18 +79,18 @@ export interface INetworkProvider { /** * Broadcasts an already-signed transaction. */ - sendTransaction(tx: ITransaction): Promise; + sendTransaction(tx: Transaction): Promise; /** * Broadcasts a list of already-signed transactions. */ - sendTransactions(txs: ITransaction[]): Promise; + sendTransactions(txs: Transaction[]): Promise; /** * Simulates the processing of an already-signed transaction. * */ - simulateTransaction(tx: ITransaction): Promise; + simulateTransaction(tx: Transaction): Promise; /** * Queries a Smart Contract - runs a pure function defined by the contract and returns its results. diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 258703685..9d9ee763e 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -1,8 +1,8 @@ import { AxiosHeaders } from "axios"; import { assert } from "chai"; import { Address } from "../address"; -import { ITransaction } from "../interface"; import { SmartContractQuery } from "../smartContractQuery"; +import { Transaction } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { ApiNetworkProvider } from "./apiNetworkProvider"; import { INetworkProvider } from "./interface"; @@ -196,10 +196,10 @@ describe("test network providers on devnet: Proxy and API", function () { this.timeout(5000); const txs = [ - { + new Transaction({ nonce: 103n, - receiver: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", - sender: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), gasPrice: 1000000000n, gasLimit: 50000n, chainID: "D", @@ -208,19 +208,12 @@ describe("test network providers on devnet: Proxy and API", function () { "498d5abb9f8eb69cc75f24320e8929dadbfa855ffac220d5e92175a83be68e0437801af3a1411e3d839738230097a1c38da5c8c4df3f345defc5d40300675900", "hex", ), - senderUsername: "", - receiverUsername: "", - guardian: "", - guardianSignature: new Uint8Array(), - options: 0, - data: new Uint8Array(), - value: 0n, - }, - - { + }), + + new Transaction({ nonce: 104n, - receiver: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", - sender: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), gasPrice: 1000000000n, gasLimit: 50000n, chainID: "D", @@ -229,31 +222,15 @@ describe("test network providers on devnet: Proxy and API", function () { "341a2f3b738fbd20692e3bbd1cb36cb5f4ce9c0a9acc0cf4322269c0fcf34fd6bb59cd94062a9a4730e47f41b1ef3e29b69c6ab2a2a4dca9c9a7724681bc1708", "hex", ), - value: 0n, - senderUsername: "", - receiverUsername: "", - guardian: "", - guardianSignature: new Uint8Array(), - options: 0, - data: new Uint8Array(), - }, - { + }), + new Transaction({ nonce: 77n, chainID: "D", - receiver: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", - sender: "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl", + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), gasLimit: 50000n, gasPrice: 1000000000n, - value: 0n, - senderUsername: "", - receiverUsername: "", - guardian: "", - guardianSignature: new Uint8Array(), - options: 0, - data: new Uint8Array(), - version: 1, - signature: new Uint8Array(), - }, + }), ]; const expectedHashes = [ @@ -431,11 +408,11 @@ describe("test network providers on devnet: Proxy and API", function () { it("should send both `Transaction` ", async function () { this.timeout(50000); - const transaction: ITransaction = { + const transaction = new Transaction({ nonce: BigInt(8), value: BigInt(0), - receiver: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - sender: "erd1zztjf9fhwvuvquzsllknq4qcmffwad6n0hjtn5dyzytr5tgz7uas0mkgrq", + receiver: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + sender: Address.newFromBech32("erd1zztjf9fhwvuvquzsllknq4qcmffwad6n0hjtn5dyzytr5tgz7uas0mkgrq"), data: new Uint8Array(Buffer.from("test")), gasPrice: BigInt(1000000000), gasLimit: BigInt(80000), @@ -445,12 +422,7 @@ describe("test network providers on devnet: Proxy and API", function () { "3fa42d97b4f85442850340a11411a3cbd63885e06ff3f84c7a75d0ef59c780f7a18aa4f331cf460300bc8bd99352aea10b7c3bc17e40287337ae9f9842470205", "hex", ), - senderUsername: "", - receiverUsername: "", - guardian: "", - guardianSignature: new Uint8Array(), - options: 0, - }; + }); const apiTxNextHash = await apiProvider.sendTransaction(transaction); diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 855f391ff..07808c50d 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,6 +1,6 @@ import { ErrContractQuery, ErrNetworkProvider } from "../errors"; -import { ITransaction } from "../interface"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; +import { Transaction } from "../transaction"; import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { getAxios } from "../utils"; @@ -135,13 +135,13 @@ export class ProxyNetworkProvider implements INetworkProvider { return status; } - async sendTransaction(tx: ITransaction): Promise { + async sendTransaction(tx: Transaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transaction/send", transaction); return response.txHash; } - async sendTransactions(txs: ITransaction[]): Promise { + async sendTransactions(txs: Transaction[]): Promise { const data = txs.map((tx) => prepareTransactionForBroadcasting(tx)); const response = await this.doPostGeneric("transaction/send-multiple", data); @@ -154,7 +154,7 @@ export class ProxyNetworkProvider implements INetworkProvider { return hashes; } - async simulateTransaction(tx: ITransaction): Promise { + async simulateTransaction(tx: Transaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transaction/simulate", transaction); return response; diff --git a/src/proto/serializer.spec.ts b/src/proto/serializer.spec.ts index 97a88b5ca..9a6b693e6 100644 --- a/src/proto/serializer.spec.ts +++ b/src/proto/serializer.spec.ts @@ -1,11 +1,9 @@ import { assert } from "chai"; import { Address } from "../address"; -import { TransactionVersion } from "../networkParams"; import { Signature } from "../signature"; import { loadTestWallets, TestWallet } from "../testutils"; import { TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; -import { TransactionPayload } from "../transactionPayload"; import { ProtoSerializer } from "./serializer"; describe("serialize transactions", () => { @@ -18,11 +16,11 @@ describe("serialize transactions", () => { it("with no data, no value", async () => { let transaction = new Transaction({ - nonce: 89, - value: 0, + nonce: 89n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasLimit: 50000, + gasLimit: 50000n, chainID: "local-testnet", }); @@ -38,12 +36,12 @@ describe("serialize transactions", () => { it("with data, no value", async () => { let transaction = new Transaction({ - nonce: 90, - value: 0, + nonce: 90n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", }); @@ -59,12 +57,12 @@ describe("serialize transactions", () => { it("with data, with value", async () => { let transaction = new Transaction({ - nonce: 91, - value: TokenTransfer.egldFromAmount(10), + nonce: 91n, + value: TokenTransfer.egldFromAmount(10).amount, sender: wallets.alice.address, receiver: wallets.bob.address, - gasLimit: 100000, - data: new TransactionPayload("for the book"), + gasLimit: 100000n, + data: Buffer.from("for the book"), chainID: "local-testnet", }); @@ -80,12 +78,12 @@ describe("serialize transactions", () => { it("with data, with large value", async () => { let transaction = new Transaction({ - nonce: 92, - value: "123456789000000000000000000000", + nonce: 92n, + value: 123456789000000000000000000000n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasLimit: 100000, - data: new TransactionPayload("for the spaceship"), + gasLimit: 100000n, + data: Buffer.from("for the spaceship"), chainID: "local-testnet", }); @@ -101,14 +99,14 @@ describe("serialize transactions", () => { it("with nonce = 0", async () => { let transaction = new Transaction({ - nonce: 0, - value: "0", + nonce: 0n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", - version: new TransactionVersion(1), + version: 1, }); transaction.applySignature( @@ -126,13 +124,13 @@ describe("serialize transactions", () => { it("with usernames", async () => { const transaction = new Transaction({ - nonce: 204, - value: "1000000000000000000", + nonce: 204n, + value: 1000000000000000000n, sender: Address.fromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"), receiver: Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), senderUsername: "carol", receiverUsername: "alice", - gasLimit: 50000, + gasLimit: 50000n, chainID: "T", }); diff --git a/src/proto/serializer.ts b/src/proto/serializer.ts index c690b5e4d..9c0f90631 100644 --- a/src/proto/serializer.ts +++ b/src/proto/serializer.ts @@ -3,7 +3,7 @@ import { bigIntToBuffer } from "../abi/codec/utils"; import { Address } from "../address"; import { TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_OPTIONS_TX_GUARDED } from "../constants"; import * as errors from "../errors"; -import { ITransaction, ITransactionValue } from "../interface"; +import { ITransactionValue } from "../interface"; import { Transaction } from "../transaction"; /** @@ -25,11 +25,11 @@ export class ProtoSerializer { return buffer; } - private convertToProtoMessage(transaction: ITransaction) { + private convertToProtoMessage(transaction: Transaction) { const proto = require("./compiled").proto; - const receiverPubkey = new Address(transaction.receiver).getPublicKey(); - const senderPubkey = new Address(transaction.sender).getPublicKey(); + const receiverPubkey = transaction.receiver.getPublicKey(); + const senderPubkey = transaction.sender.getPublicKey(); let protoTransaction = new proto.Transaction({ // mx-chain-go's serializer handles nonce == 0 differently, thus we treat 0 as "undefined". @@ -79,13 +79,13 @@ export class ProtoSerializer { return buffer; } - private isGuardedTransaction(transaction: ITransaction): boolean { - const hasGuardian = transaction.guardian.length > 0; + private isGuardedTransaction(transaction: Transaction): boolean { + const hasGuardian = !transaction.guardian.isEmpty(); const hasGuardianSignature = transaction.guardianSignature.length > 0; return this.isWithGuardian(transaction) && hasGuardian && hasGuardianSignature; } - private isWithGuardian(transaction: ITransaction): boolean { + private isWithGuardian(transaction: Transaction): boolean { return (transaction.options & TRANSACTION_OPTIONS_TX_GUARDED) == TRANSACTION_OPTIONS_TX_GUARDED; } diff --git a/src/relayed/relayedTransactionsFactory.spec.ts b/src/relayed/relayedTransactionsFactory.spec.ts index 0be7b0d43..aed994fa2 100644 --- a/src/relayed/relayedTransactionsFactory.spec.ts +++ b/src/relayed/relayedTransactionsFactory.spec.ts @@ -1,4 +1,5 @@ import { assert } from "chai"; +import { Address } from "../address"; import { TestWallet, loadTestWallets } from "../testutils"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; @@ -17,8 +18,8 @@ describe("test relayed transactions factory", function () { it("should throw exception when creating relayed v1 transaction with invalid inner transaction", async function () { let innerTransaction = new Transaction({ - sender: alice.address.bech32(), - receiver: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", + sender: alice.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), gasLimit: 10000000n, data: Buffer.from("getContractConfig"), chainID: config.chainID, @@ -40,8 +41,8 @@ describe("test relayed transactions factory", function () { it("should create relayed v1 transaction", async function () { let innerTransaction = new Transaction({ - sender: bob.address.bech32(), - receiver: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", + sender: bob.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), gasLimit: 60000000n, data: Buffer.from("getContractConfig"), chainID: config.chainID, @@ -71,8 +72,8 @@ describe("test relayed transactions factory", function () { it("should create relayed v1 transaction with usernames", async function () { let innerTransaction = new Transaction({ - sender: carol.address.bech32(), - receiver: alice.address.bech32(), + sender: carol.address, + receiver: alice.address, gasLimit: 50000n, chainID: config.chainID, nonce: 208n, @@ -104,8 +105,8 @@ describe("test relayed transactions factory", function () { it("should create relayed v1 transaction with big value", async function () { let innerTransaction = new Transaction({ - sender: carol.address.bech32(), - receiver: alice.address.bech32(), + sender: carol.address, + receiver: alice.address, gasLimit: 50000n, chainID: config.chainID, nonce: 208n, @@ -137,15 +138,15 @@ describe("test relayed transactions factory", function () { it("should create relayed v1 transaction with guarded inner transaction", async function () { let innerTransaction = new Transaction({ - sender: bob.address.bech32(), - receiver: "erd1qqqqqqqqqqqqqpgq54tsxmej537z9leghvp69hfu4f8gg5eu396q83gnnz", + sender: bob.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqpgq54tsxmej537z9leghvp69hfu4f8gg5eu396q83gnnz"), gasLimit: 60000000n, chainID: config.chainID, data: Buffer.from("getContractConfig"), nonce: 198n, version: 2, options: 2, - guardian: grace.address.bech32(), + guardian: grace.address, }); const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); @@ -172,15 +173,15 @@ describe("test relayed transactions factory", function () { it("should create guarded relayed v1 transaction with guarded inner transaction", async function () { let innerTransaction = new Transaction({ - sender: bob.address.bech32(), - receiver: "erd1qqqqqqqqqqqqqpgq54tsxmej537z9leghvp69hfu4f8gg5eu396q83gnnz", + sender: bob.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqpgq54tsxmej537z9leghvp69hfu4f8gg5eu396q83gnnz"), gasLimit: 60000000n, chainID: config.chainID, data: Buffer.from("addNumber"), nonce: 198n, version: 2, options: 2, - guardian: grace.address.bech32(), + guardian: grace.address, }); const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); @@ -192,7 +193,7 @@ describe("test relayed transactions factory", function () { }); relayedTransaction.nonce = 2627n; relayedTransaction.options = 2; - relayedTransaction.guardian = frank.address.bech32(); + relayedTransaction.guardian = frank.address; const serializedRelayedTransaction = transactionComputer.computeBytesForSigning(relayedTransaction); relayedTransaction.signature = await alice.signer.sign(serializedRelayedTransaction); @@ -210,8 +211,8 @@ describe("test relayed transactions factory", function () { it("should throw exception when creating relayed v2 transaction with invalid inner transaction", async function () { let innerTransaction = new Transaction({ - sender: bob.address.bech32(), - receiver: bob.address.bech32(), + sender: bob.address, + receiver: bob.address, gasLimit: 50000n, chainID: config.chainID, }); @@ -237,8 +238,8 @@ describe("test relayed transactions factory", function () { it("should create relayed v2 transaction", async function () { let innerTransaction = new Transaction({ - sender: bob.address.bech32(), - receiver: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u", + sender: bob.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), gasLimit: 0n, chainID: config.chainID, data: Buffer.from("getContractConfig"), diff --git a/src/relayed/relayedTransactionsFactory.ts b/src/relayed/relayedTransactionsFactory.ts index 52f008536..fbe70c473 100644 --- a/src/relayed/relayedTransactionsFactory.ts +++ b/src/relayed/relayedTransactionsFactory.ts @@ -2,7 +2,6 @@ import BigNumber from "bignumber.js"; import { AddressValue, ArgSerializer, BytesValue, U64Value } from "../abi"; import { Address } from "../address"; import { ErrInvalidInnerTransaction } from "../errors"; -import { ITransaction } from "../interface"; import { Transaction } from "../transaction"; const JSONbig = require("json-bigint"); @@ -23,7 +22,7 @@ export class RelayedTransactionsFactory { this.config = options.config; } - createRelayedV1Transaction(relayerAddress: Address, options: { innerTransaction: ITransaction }): Transaction { + createRelayedV1Transaction(relayerAddress: Address, options: { innerTransaction: Transaction }): Transaction { if (!options.innerTransaction.gasLimit) { throw new ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction"); } @@ -40,7 +39,7 @@ export class RelayedTransactionsFactory { return new Transaction({ chainID: this.config.chainID, - sender: relayerAddress.bech32(), + sender: relayerAddress, receiver: options.innerTransaction.sender, gasLimit: gasLimit, data: Buffer.from(data), @@ -50,7 +49,7 @@ export class RelayedTransactionsFactory { createRelayedV2Transaction( relayerAddress: Address, options: { - innerTransaction: ITransaction; + innerTransaction: Transaction; innerTransactionGasLimit: bigint; }, ): Transaction { @@ -63,7 +62,7 @@ export class RelayedTransactionsFactory { } const { argumentsString } = new ArgSerializer().valuesToString([ - new AddressValue(Address.fromBech32(options.innerTransaction.receiver)), + new AddressValue(options.innerTransaction.receiver), new U64Value(new BigNumber(options.innerTransaction.nonce.toString())), new BytesValue(Buffer.from(options.innerTransaction.data)), new BytesValue(Buffer.from(options.innerTransaction.signature)), @@ -75,7 +74,7 @@ export class RelayedTransactionsFactory { const gasLimit = options.innerTransactionGasLimit + this.config.minGasLimit + additionalGasForDataLength; return new Transaction({ - sender: relayerAddress.bech32(), + sender: relayerAddress, receiver: options.innerTransaction.sender, value: 0n, gasLimit: gasLimit, @@ -86,11 +85,11 @@ export class RelayedTransactionsFactory { }); } - private prepareInnerTransactionForRelayedV1(innerTransaction: ITransaction): string { + private prepareInnerTransactionForRelayedV1(innerTransaction: Transaction): string { const txObject = { nonce: innerTransaction.nonce, - sender: Address.newFromBech32(innerTransaction.sender).getPublicKey().toString("base64"), - receiver: Address.newFromBech32(innerTransaction.receiver).getPublicKey().toString("base64"), + sender: innerTransaction.sender.getPublicKey().toString("base64"), + receiver: innerTransaction.receiver.getPublicKey().toString("base64"), value: innerTransaction.value, gasPrice: innerTransaction.gasPrice, gasLimit: innerTransaction.gasLimit, @@ -100,7 +99,7 @@ export class RelayedTransactionsFactory { version: innerTransaction.version, options: innerTransaction.options.valueOf() == 0 ? undefined : innerTransaction.options, guardian: innerTransaction.guardian - ? Address.newFromBech32(innerTransaction.guardian).getPublicKey().toString("base64") + ? innerTransaction.guardian.getPublicKey().toString("base64") : undefined, guardianSignature: innerTransaction.guardianSignature.length ? Buffer.from(innerTransaction.guardianSignature).toString("base64") diff --git a/src/relayed/resources.ts b/src/relayed/resources.ts index cb0494653..e4d0589fa 100644 --- a/src/relayed/resources.ts +++ b/src/relayed/resources.ts @@ -1,7 +1,7 @@ -import { ITransaction } from "../interface"; +import { Transaction } from "../transaction"; -export type RelayedV1TransactionInput = { innerTransaction: ITransaction }; +export type RelayedV1TransactionInput = { innerTransaction: Transaction }; export type RelayedV2TransactionInput = { - innerTransaction: ITransaction; + innerTransaction: Transaction; innerTransactionGasLimit: bigint; }; diff --git a/src/smartContracts/smartContractTransactionsFactory.spec.ts b/src/smartContracts/smartContractTransactionsFactory.spec.ts index eae01d4c0..7e72d63dc 100644 --- a/src/smartContracts/smartContractTransactionsFactory.spec.ts +++ b/src/smartContracts/smartContractTransactionsFactory.spec.ts @@ -62,8 +62,14 @@ describe("test smart contract transactions factory", function () { arguments: args, }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu"), + ); assert.deepEqual(transaction.data, Buffer.from(`${bytecode}@0500@0504@01`)); assert.equal(transaction.gasLimit.valueOf(), gasLimit); assert.equal(transaction.value, 0n); @@ -92,8 +98,14 @@ describe("test smart contract transactions factory", function () { arguments: args, }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"), + ); assert.deepEqual(transaction.data, Buffer.from("add@07")); assert.equal(transaction.gasLimit, gasLimit); assert.equal(transaction.value, 0n); @@ -124,8 +136,14 @@ describe("test smart contract transactions factory", function () { nativeTransferAmount: egldAmount, }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"), + ); assert.deepEqual(transaction.data, Buffer.from("add@07")); assert.equal(transaction.gasLimit, gasLimit); assert.equal(transaction.value, 1000000000000000000n); @@ -158,8 +176,14 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [transfer], }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"), + ); assert.deepEqual(transaction.data, Buffer.from("ESDTTransfer@464f4f2d366365313762@0a@616464@07")); assert.equal(transaction.gasLimit, gasLimit); assert.equal(transaction.value, 0n); @@ -195,8 +219,14 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [fooTransfer, barTransfer], }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); assert.deepEqual( transaction.data, @@ -237,8 +267,14 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [transfer], }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); assert.isDefined(transaction.data); assert.deepEqual( @@ -282,8 +318,14 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [firstTransfer, secondTransfer], }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); assert.isDefined(transaction.data); assert.deepEqual( @@ -329,8 +371,14 @@ describe("test smart contract transactions factory", function () { tokenTransfers: [firstTransfer, secondTransfer], }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); assert.isDefined(transaction.data); assert.deepEqual( @@ -366,8 +414,14 @@ describe("test smart contract transactions factory", function () { arguments: args, }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"), + ); assert.deepEqual(transaction.data!, Buffer.from(`upgradeContract@${bytecode}@0504@07`)); assert.equal(transaction.gasLimit, gasLimit); assert.equal(transaction.value, 0n); @@ -472,16 +526,22 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for claiming developer rewards", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const transaction = factory.createTransactionForClaimingDeveloperRewards({ sender: sender, contract: contract, }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"), + ); assert.equal(Buffer.from(transaction.data).toString(), "ClaimDeveloperRewards"); assert.equal(transaction.gasLimit, 6000000n); assert.equal(transaction.value, 0n); @@ -498,8 +558,14 @@ describe("test smart contract transactions factory", function () { newOwner: newOwner, }); - assert.equal(transaction.sender, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + ); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"), + ); assert.equal( Buffer.from(transaction.data).toString(), "ChangeOwnerAddress@8049d639e5a6980d1cd2392abcce41029cda74a1563523a202f09641cc2618f8", diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index b73f48d53..f5c63d9b7 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -2,7 +2,6 @@ import { Address } from "../address"; import { AsyncTimer } from "../asyncTimer"; import * as errors from "../errors"; import { ErrMock } from "../errors"; -import { ITransaction } from "../interface"; import { IAccountOnNetwork } from "../interfaceOfNetwork"; import { AccountOnNetwork, @@ -88,7 +87,7 @@ export class MockNetworkProvider implements INetworkProvider { ): Promise { throw new Error("Method not implemented."); } - sendTransactions(_txs: ITransaction[]): Promise { + sendTransactions(_txs: Transaction[]): Promise { throw new Error("Method not implemented."); } getDefinitionOfFungibleToken(_tokenIdentifier: string): Promise { @@ -173,7 +172,7 @@ export class MockNetworkProvider implements INetworkProvider { } } - async getAccount(address: IAddress): Promise { + async getAccount(address: Address): Promise { let account = this.accounts.get(address.bech32()); if (account) { return account; @@ -188,7 +187,7 @@ export class MockNetworkProvider implements INetworkProvider { new TransactionOnNetwork({ sender: transaction.getSender(), receiver: transaction.getReceiver(), - data: transaction.getData().valueOf(), + data: Buffer.from(transaction.data), status: new TransactionStatus("pending"), }), ); diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index b6d90eac1..636c107ad 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -2,7 +2,6 @@ import BigNumber from "bignumber.js"; import * as fs from "fs"; import { PathLike } from "fs"; import { AbiRegistry, Code, SmartContract, TypedValue } from "../abi"; -import { IChainID, IGasLimit } from "../interface"; import { Transaction } from "../transaction"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; @@ -13,8 +12,8 @@ export async function prepareDeployment(obj: { contract: SmartContract; codePath: string; initArguments: TypedValue[]; - gasLimit: IGasLimit; - chainID: IChainID; + gasLimit: bigint; + chainID: string; }): Promise { let contract = obj.contract; let deployer = obj.deployer; diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 1297652e6..90c38eb3d 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -1,5 +1,4 @@ import { Address } from "../address"; -import { IAddress } from "../interface"; export type IssueFungibleInput = IssueInput & { initialSupply: bigint; numDecimals: bigint }; @@ -19,7 +18,7 @@ export type IssueInput = { }; export type FungibleSpecialRoleInput = { - user: IAddress; + user: Address; tokenIdentifier: string; addRoleLocalMint: boolean; addRoleLocalBurn: boolean; @@ -28,7 +27,7 @@ export type FungibleSpecialRoleInput = { export type SemiFungibleSpecialRoleInput = SpecialRoleInput & { addRoleNFTAddQuantity: boolean }; export type SpecialRoleInput = { - user: IAddress; + user: Address; tokenIdentifier: string; addRoleNFTCreate: boolean; addRoleNFTBurn: boolean; @@ -50,7 +49,7 @@ export type MintInput = { attributes: Uint8Array; uris: string[]; }; -export type ManagementInput = { user: IAddress; tokenIdentifier: string }; +export type ManagementInput = { user: Address; tokenIdentifier: string }; export type PausingInput = { tokenIdentifier: string }; export type LocalBurnInput = { tokenIdentifier: string; supplyToBurn: bigint }; export type LocalMintInput = { tokenIdentifier: string; supplyToMint: bigint }; diff --git a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts index 9808d41ae..904fa4f2e 100644 --- a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts @@ -25,8 +25,11 @@ describe("test token management transactions factory", () => { }); assert.deepEqual(transaction.data, Buffer.from("registerAndSetAllRoles@54455354@54455354@464e47@02")); - assert.equal(transaction.sender, frank.address.toString()); - assert.equal(transaction.receiver, "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual( + transaction.receiver, + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), + ); assert.deepEqual(transaction.value, config.issueCost); assert.deepEqual(transaction.gasLimit, 60125000n); }); @@ -51,8 +54,8 @@ describe("test token management transactions factory", () => { "issue@4652414e4b@4652414e4b@64@@63616e467265657a65@74727565@63616e57697065@74727565@63616e5061757365@74727565@63616e4368616e67654f776e6572@74727565@63616e55706772616465@66616c7365@63616e4164645370656369616c526f6c6573@66616c7365", ), ); - assert.equal(transaction.sender, frank.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.deepEqual(transaction.value, config.issueCost); }); @@ -75,8 +78,8 @@ describe("test token management transactions factory", () => { "issueSemiFungible@4652414e4b@4652414e4b@63616e467265657a65@74727565@63616e57697065@74727565@63616e5061757365@74727565@63616e5472616e736665724e4654437265617465526f6c65@74727565@63616e4368616e67654f776e6572@74727565@63616e55706772616465@66616c7365@63616e4164645370656369616c526f6c6573@66616c7365", ), ); - assert.equal(transaction.sender, frank.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.deepEqual(transaction.value, config.issueCost); }); @@ -99,8 +102,8 @@ describe("test token management transactions factory", () => { "issueNonFungible@4652414e4b@4652414e4b@63616e467265657a65@74727565@63616e57697065@74727565@63616e5061757365@74727565@63616e5472616e736665724e4654437265617465526f6c65@74727565@63616e4368616e67654f776e6572@74727565@63616e55706772616465@66616c7365@63616e4164645370656369616c526f6c6573@66616c7365", ), ); - assert.equal(transaction.sender, frank.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.deepEqual(transaction.value, config.issueCost); }); @@ -124,8 +127,8 @@ describe("test token management transactions factory", () => { "registerMetaESDT@4652414e4b@4652414e4b@0a@63616e467265657a65@74727565@63616e57697065@74727565@63616e5061757365@74727565@63616e5472616e736665724e4654437265617465526f6c65@74727565@63616e4368616e67654f776e6572@74727565@63616e55706772616465@66616c7365@63616e4164645370656369616c526f6c6573@66616c7365", ), ); - assert.equal(transaction.sender, frank.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.deepEqual(transaction.value, config.issueCost); }); @@ -147,8 +150,8 @@ describe("test token management transactions factory", () => { "setSpecialRole@4652414e4b2d313163653365@1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13@45534454526f6c654c6f63616c4d696e74", ), ); - assert.equal(transaction.sender, frank.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.equal(transaction.value, 0n); }); @@ -170,8 +173,8 @@ describe("test token management transactions factory", () => { "setSpecialRole@4652414e4b2d313163653365@1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13@45534454526f6c654c6f63616c4d696e74@45534454526f6c654c6f63616c4275726e@455344545472616e73666572526f6c65", ), ); - assert.equal(transaction.sender, frank.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.equal(transaction.value, 0n); }); @@ -197,8 +200,8 @@ describe("test token management transactions factory", () => { "setSpecialRole@4652414e4b2d313163653365@1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13@45534454526f6c654e4654437265617465@45534454526f6c654e465455706461746541747472696275746573@45534454526f6c654e4654416464555249@45534454526f6c654d6f6469667943726561746f72@45534454526f6c654e46545265637265617465", ), ); - assert.equal(transaction.sender, frank.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.equal(transaction.value, 0n); }); @@ -217,8 +220,8 @@ describe("test token management transactions factory", () => { transaction.data, Buffer.from("ESDTNFTCreate@4652414e4b2d616139653864@01@74657374@03e8@61626261@74657374@61@62"), ); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, grace.address.toString()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, grace.address); assert.equal(transaction.value, 0n); }); @@ -230,8 +233,8 @@ describe("test token management transactions factory", () => { }); assert.deepEqual(transaction.data, Buffer.from("ESDTModifyRoyalties@544553542d313233343536@01@04d2")); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, grace.address.toString()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, grace.address); assert.equal(transaction.value, 0n); assert.equal(transaction.gasLimit, 60125000n); }); @@ -247,8 +250,8 @@ describe("test token management transactions factory", () => { transaction.data, Buffer.from("ESDTSetNewURIs@544553542d313233343536@01@6669727374555249@7365636f6e64555249"), ); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, grace.address.toString()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, grace.address); assert.equal(transaction.value, 0n); assert.equal(transaction.gasLimit, 60164000n); }); @@ -260,8 +263,8 @@ describe("test token management transactions factory", () => { }); assert.deepEqual(transaction.data, Buffer.from("ESDTModifyCreator@544553542d313233343536@01")); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, grace.address.toString()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, grace.address); assert.equal(transaction.value, 0n); assert.equal(transaction.gasLimit, 60114500n); }); @@ -283,8 +286,8 @@ describe("test token management transactions factory", () => { "ESDTMetaDataUpdate@544553542d313233343536@01@54657374@04d2@61626261@74657374@6669727374555249@7365636f6e64555249", ), ); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, grace.address.toString()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, grace.address); assert.equal(transaction.value, 0n); assert.equal(transaction.gasLimit, 60218000n); }); @@ -306,8 +309,8 @@ describe("test token management transactions factory", () => { "ESDTMetaDataRecreate@544553542d313233343536@01@54657374@04d2@61626261@74657374@6669727374555249@7365636f6e64555249", ), ); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, grace.address.toString()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, grace.address); assert.equal(transaction.value, 0n); assert.equal(transaction.gasLimit, 60221000n); }); @@ -318,8 +321,8 @@ describe("test token management transactions factory", () => { }); assert.deepEqual(transaction.data, Buffer.from("changeToDynamic@544553542d313233343536")); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.equal(transaction.value, 0n); assert.equal(transaction.gasLimit, 60107000n); }); @@ -330,8 +333,8 @@ describe("test token management transactions factory", () => { }); assert.deepEqual(transaction.data, Buffer.from("updateTokenID@544553542d313233343536")); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.equal(transaction.value, 0n); assert.equal(transaction.gasLimit, 60104000n); }); @@ -344,8 +347,8 @@ describe("test token management transactions factory", () => { }); assert.deepEqual(transaction.data, Buffer.from("registerDynamic@54657374@544553542d313233343536@464e47")); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.equal(transaction.value, 50000000000000000n); assert.equal(transaction.gasLimit, 60131000n); }); @@ -364,8 +367,8 @@ describe("test token management transactions factory", () => { transaction.data, Buffer.from("registerAndSetAllRolesDynamic@54657374@544553542d313233343536@464e47"), ); - assert.equal(transaction.sender, grace.address.toString()); - assert.equal(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp).toBech32()); + assert.deepEqual(transaction.sender, grace.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); assert.equal(transaction.value, 50000000000000000n); assert.equal(transaction.gasLimit, 60152000n); }); diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index 2b161ee2b..b87ab9fb1 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -2,7 +2,6 @@ import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, StringValue } fr import { Address } from "../address"; import { ESDT_CONTRACT_ADDRESS_HEX } from "../constants"; import { ErrBadUsage } from "../errors"; -import { IAddress } from "../interface"; import { Logger } from "../logger"; import { Transaction } from "../transaction"; import { TransactionBuilder } from "../transactionBuilder"; @@ -55,7 +54,7 @@ export class TokenManagementTransactionsFactory { this.esdtContractAddress = Address.fromHex(ESDT_CONTRACT_ADDRESS_HEX, this.config.addressHrp); } - createTransactionForIssuingFungible(sender: IAddress, options: resources.IssueFungibleInput): Transaction { + createTransactionForIssuingFungible(sender: Address, options: resources.IssueFungibleInput): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const args = [ @@ -90,7 +89,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForIssuingSemiFungible(sender: IAddress, options: resources.IssueSemiFungibleInput): Transaction { + createTransactionForIssuingSemiFungible(sender: Address, options: resources.IssueSemiFungibleInput): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const args = [ @@ -125,7 +124,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForIssuingNonFungible(sender: IAddress, options: resources.IssueNonFungibleInput): Transaction { + createTransactionForIssuingNonFungible(sender: Address, options: resources.IssueNonFungibleInput): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const args = [ @@ -160,7 +159,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForRegisteringMetaESDT(sender: IAddress, options: resources.RegisterMetaESDTInput): Transaction { + createTransactionForRegisteringMetaESDT(sender: Address, options: resources.RegisterMetaESDTInput): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); const args = [ @@ -197,7 +196,7 @@ export class TokenManagementTransactionsFactory { } createTransactionForRegisteringAndSettingRoles( - sender: IAddress, + sender: Address, options: resources.RegisterRolesInput, ): Transaction { this.notifyAboutUnsettingBurnRoleGlobally(); @@ -224,7 +223,7 @@ export class TokenManagementTransactionsFactory { } createTransactionForSettingBurnRoleGlobally( - sender: IAddress, + sender: Address, options: resources.BurnRoleGloballyInput, ): Transaction { const dataParts = [ @@ -243,7 +242,7 @@ export class TokenManagementTransactionsFactory { } createTransactionForUnsettingBurnRoleGlobally( - sender: IAddress, + sender: Address, options: resources.BurnRoleGloballyInput, ): Transaction { const dataParts = [ @@ -262,7 +261,7 @@ export class TokenManagementTransactionsFactory { } createTransactionForSettingSpecialRoleOnFungibleToken( - sender: IAddress, + sender: Address, options: resources.FungibleSpecialRoleInput, ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; @@ -284,7 +283,7 @@ export class TokenManagementTransactionsFactory { } createTransactionForSettingSpecialRoleOnSemiFungibleToken( - sender: IAddress, + sender: Address, options: resources.SemiFungibleSpecialRoleInput, ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; @@ -308,14 +307,14 @@ export class TokenManagementTransactionsFactory { } createTransactionForSettingSpecialRoleOnMetaESDT( - sender: IAddress, + sender: Address, options: resources.SemiFungibleSpecialRoleInput, ): Transaction { return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(sender, options); } createTransactionForSettingSpecialRoleOnNonFungibleToken( - sender: IAddress, + sender: Address, options: resources.SpecialRoleInput, ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; @@ -342,7 +341,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForCreatingNFT(sender: IAddress, options: resources.MintInput): Transaction { + createTransactionForCreatingNFT(sender: Address, options: resources.MintInput): Transaction { const dataParts = [ "ESDTNFTCreate", ...this.argSerializer.valuesToStrings([ @@ -370,7 +369,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForPausing(sender: IAddress, options: resources.PausingInput): Transaction { + createTransactionForPausing(sender: Address, options: resources.PausingInput): Transaction { const dataParts = ["pause", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)])]; return new TransactionBuilder({ @@ -383,7 +382,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUnpausing(sender: IAddress, options: resources.PausingInput): Transaction { + createTransactionForUnpausing(sender: Address, options: resources.PausingInput): Transaction { const dataParts = [ "unPause", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), @@ -399,7 +398,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForFreezing(sender: IAddress, options: resources.ManagementInput): Transaction { + createTransactionForFreezing(sender: Address, options: resources.ManagementInput): Transaction { const dataParts = [ "freeze", ...this.argSerializer.valuesToStrings([ @@ -418,7 +417,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUnfreezing(sender: IAddress, options: resources.ManagementInput): Transaction { + createTransactionForUnfreezing(sender: Address, options: resources.ManagementInput): Transaction { const dataParts = [ "UnFreeze", ...this.argSerializer.valuesToStrings([ @@ -437,7 +436,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForWiping(sender: IAddress, options: resources.ManagementInput): Transaction { + createTransactionForWiping(sender: Address, options: resources.ManagementInput): Transaction { const dataParts = [ "wipe", ...this.argSerializer.valuesToStrings([ @@ -456,7 +455,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForLocalMint(sender: IAddress, options: resources.LocalMintInput): Transaction { + createTransactionForLocalMint(sender: Address, options: resources.LocalMintInput): Transaction { const dataParts = [ "ESDTLocalMint", ...this.argSerializer.valuesToStrings([ @@ -475,7 +474,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForLocalBurning(sender: IAddress, options: resources.LocalBurnInput): Transaction { + createTransactionForLocalBurning(sender: Address, options: resources.LocalBurnInput): Transaction { const dataParts = [ "ESDTLocalBurn", ...this.argSerializer.valuesToStrings([ @@ -494,7 +493,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUpdatingAttributes(sender: IAddress, options: resources.UpdateAttributesInput): Transaction { + createTransactionForUpdatingAttributes(sender: Address, options: resources.UpdateAttributesInput): Transaction { const dataParts = [ "ESDTNFTUpdateAttributes", ...this.argSerializer.valuesToStrings([ @@ -514,7 +513,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForAddingQuantity(sender: IAddress, options: resources.UpdateQuantityInput): Transaction { + createTransactionForAddingQuantity(sender: Address, options: resources.UpdateQuantityInput): Transaction { const dataParts = [ "ESDTNFTAddQuantity", ...this.argSerializer.valuesToStrings([ @@ -534,7 +533,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForBurningQuantity(sender: IAddress, options: resources.UpdateQuantityInput): Transaction { + createTransactionForBurningQuantity(sender: Address, options: resources.UpdateQuantityInput): Transaction { const dataParts = [ "ESDTNFTBurn", ...this.argSerializer.valuesToStrings([ @@ -554,7 +553,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForModifyingRoyalties(sender: IAddress, options: resources.ModifyRoyaltiesInput): Transaction { + createTransactionForModifyingRoyalties(sender: Address, options: resources.ModifyRoyaltiesInput): Transaction { const dataParts = [ "ESDTModifyRoyalties", ...this.argSerializer.valuesToStrings([ @@ -574,7 +573,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForSettingNewUris(sender: IAddress, options: resources.SetNewUriInput): Transaction { + createTransactionForSettingNewUris(sender: Address, options: resources.SetNewUriInput): Transaction { if (!options.newUris.length) { throw new ErrBadUsage("No URIs provided"); } @@ -598,7 +597,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForModifyingCreator(sender: IAddress, options: resources.ModifyCreatorInput): Transaction { + createTransactionForModifyingCreator(sender: Address, options: resources.ModifyCreatorInput): Transaction { const dataParts = [ "ESDTModifyCreator", ...this.argSerializer.valuesToStrings([ @@ -617,7 +616,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUpdatingMetadata(sender: IAddress, options: resources.ManageMetadataInput): Transaction { + createTransactionForUpdatingMetadata(sender: Address, options: resources.ManageMetadataInput): Transaction { const dataParts = [ "ESDTMetaDataUpdate", ...this.argSerializer.valuesToStrings([ @@ -641,7 +640,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForMetadataRecreate(sender: IAddress, options: resources.ManageMetadataInput): Transaction { + createTransactionForMetadataRecreate(sender: Address, options: resources.ManageMetadataInput): Transaction { const dataParts = [ "ESDTMetaDataRecreate", ...this.argSerializer.valuesToStrings([ @@ -666,7 +665,7 @@ export class TokenManagementTransactionsFactory { } createTransactionForChangingTokenToDynamic( - sender: IAddress, + sender: Address, options: resources.ChangeTokenToDynamicInput, ): Transaction { const dataParts = [ @@ -684,7 +683,7 @@ export class TokenManagementTransactionsFactory { }).build(); } - createTransactionForUpdatingTokenId(sender: IAddress, options: resources.UpdateTokenIDInput): Transaction { + createTransactionForUpdatingTokenId(sender: Address, options: resources.UpdateTokenIDInput): Transaction { const dataParts = [ "updateTokenID", ...this.argSerializer.valuesToStrings([new StringValue(options.tokenIdentifier)]), @@ -701,7 +700,7 @@ export class TokenManagementTransactionsFactory { } createTransactionForRegisteringDynamicToken( - sender: IAddress, + sender: Address, options: resources.RegisteringDynamicTokenInput, ): Transaction { const dataParts = [ @@ -725,7 +724,7 @@ export class TokenManagementTransactionsFactory { } createTransactionForRegisteringDynamicAndSettingRoles( - sender: IAddress, + sender: Address, options: resources.RegisteringDynamicTokenInput, ): Transaction { const dataParts = [ diff --git a/src/tokenTransfersDataBuilder.ts b/src/tokenTransfersDataBuilder.ts index 17e416d13..e2a2b2c17 100644 --- a/src/tokenTransfersDataBuilder.ts +++ b/src/tokenTransfersDataBuilder.ts @@ -1,5 +1,5 @@ import { AddressValue, ArgSerializer, BigUIntValue, TokenIdentifierValue, TypedValue, U32Value } from "./abi"; -import { IAddress } from "./interface"; +import { Address } from "./address"; import { TokenComputer, TokenTransfer } from "./tokens"; export class TokenTransfersDataBuilder { @@ -20,7 +20,7 @@ export class TokenTransfersDataBuilder { return ["ESDTTransfer", ...args]; } - buildDataPartsForSingleESDTNFTTransfer(transfer: TokenTransfer, receiver: IAddress) { + buildDataPartsForSingleESDTNFTTransfer(transfer: TokenTransfer, receiver: Address) { const token = transfer.token; const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(token.identifier); @@ -34,7 +34,7 @@ export class TokenTransfersDataBuilder { return ["ESDTNFTTransfer", ...args]; } - buildDataPartsForMultiESDTNFTTransfer(receiver: IAddress, transfers: TokenTransfer[]) { + buildDataPartsForMultiESDTNFTTransfer(receiver: Address, transfers: TokenTransfer[]) { const argsTyped: TypedValue[] = [new AddressValue(receiver), new U32Value(transfers.length)]; for (const transfer of transfers) { diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 45d3b8305..b21667def 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -7,7 +7,6 @@ import { createLocalnetProvider } from "./testutils/networkProviders"; import { TokenTransfer } from "./tokens"; import { Transaction } from "./transaction"; import { TransactionComputer } from "./transactionComputer"; -import { TransactionPayload } from "./transactionPayload"; import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; import { TransactionWatcher } from "./transactionWatcher"; import { TransferTransactionsFactory } from "./transfers/transferTransactionsFactory"; @@ -40,16 +39,16 @@ describe("test transaction", function () { let transactionOne = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.egldFromAmount(42), - gasLimit: network.MinGasLimit, + value: TokenTransfer.egldFromAmount(42).amount, + gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); let transactionTwo = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.egldFromAmount(43), - gasLimit: network.MinGasLimit, + value: TokenTransfer.egldFromAmount(43).amount, + gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -87,8 +86,8 @@ describe("test transaction", function () { let transactionOne = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.egldFromAmount(42), - gasLimit: network.MinGasLimit, + value: TokenTransfer.egldFromAmount(42).amount, + gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -116,19 +115,19 @@ describe("test transaction", function () { let transactionOne = new Transaction({ sender: alice.address, - data: new TransactionPayload("helloWorld"), - gasLimit: 70000, + data: Buffer.from("helloWorld"), + gasLimit: 70000n, receiver: alice.address, - value: TokenTransfer.egldFromAmount(1000), + value: TokenTransfer.egldFromAmount(1000).amount, chainID: network.ChainID, }); let transactionTwo = new Transaction({ sender: alice.address, - data: new TransactionPayload("helloWorld"), - gasLimit: 70000, + data: Buffer.from("helloWorld"), + gasLimit: 70000n, receiver: alice.address, - value: TokenTransfer.egldFromAmount(1000000), + value: TokenTransfer.egldFromAmount(1000000).amount, chainID: network.ChainID, }); diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index ecf98d5c0..b7d9484ac 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -1,15 +1,12 @@ -import { UserPublicKey, UserVerifier } from "./wallet"; -import BigNumber from "bignumber.js"; +import { Buffer } from "buffer"; import { assert } from "chai"; import { Address } from "./address"; -import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS } from "./constants"; -import { TransactionOptions, TransactionVersion } from "./networkParams"; +import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, TRANSACTION_OPTIONS_DEFAULT } from "./constants"; import { ProtoSerializer } from "./proto"; import { TestWallet, loadTestWallets } from "./testutils"; -import { TokenTransfer } from "./tokens"; import { Transaction } from "./transaction"; import { TransactionComputer } from "./transactionComputer"; -import { TransactionPayload } from "./transactionPayload"; +import { UserPublicKey, UserVerifier } from "./wallet"; describe("test transaction", async () => { let wallets: Record; @@ -32,8 +29,8 @@ describe("test transaction", async () => { it("should serialize transaction for signing (without data)", async () => { const transaction = new Transaction({ chainID: networkConfig.ChainID, - sender: wallets.alice.address.bech32(), - receiver: wallets.bob.address.bech32(), + sender: wallets.alice.address, + receiver: wallets.bob.address, gasLimit: 50000n, value: 0n, version: 2, @@ -52,8 +49,8 @@ describe("test transaction", async () => { it("should serialize transaction for signing (with data)", async () => { const transaction = new Transaction({ chainID: networkConfig.ChainID, - sender: wallets.alice.address.bech32(), - receiver: wallets.bob.address.bech32(), + sender: wallets.alice.address, + receiver: wallets.bob.address, gasLimit: 70000n, value: 1000000000000000000n, version: 2, @@ -72,12 +69,12 @@ describe("test transaction", async () => { it("should sign transaction (with no data, no value) (legacy)", async () => { const transaction = new Transaction({ - nonce: 89, - value: "0", + nonce: 89n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: minGasLimit, + gasPrice: BigInt(minGasPrice), + gasLimit: BigInt(minGasLimit), chainID: "local-testnet", }); @@ -95,13 +92,13 @@ describe("test transaction", async () => { it("should sign transaction (with data, no value) (legacy)", async () => { const transaction = new Transaction({ - nonce: 90, - value: "0", + nonce: 90n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasPrice: BigInt(minGasPrice), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", }); @@ -120,8 +117,8 @@ describe("test transaction", async () => { it("should sign transaction (with usernames)", async () => { const transaction = new Transaction({ chainID: "T", - sender: wallets.carol.address.bech32(), - receiver: wallets.alice.address.bech32(), + sender: wallets.carol.address, + receiver: wallets.alice.address, gasLimit: 50000n, value: 1000000000000000000n, version: 2, @@ -143,8 +140,8 @@ describe("test transaction", async () => { it("should compute hash", async () => { const transaction = new Transaction({ chainID: networkConfig.ChainID, - sender: wallets.alice.address.bech32(), - receiver: wallets.alice.address.bech32(), + sender: wallets.alice.address, + receiver: wallets.alice.address, gasLimit: 100000n, value: 1000000000000n, version: 2, @@ -168,8 +165,8 @@ describe("test transaction", async () => { it("should compute hash (with usernames)", async () => { const transaction = new Transaction({ chainID: networkConfig.ChainID, - sender: wallets.alice.address.bech32(), - receiver: wallets.alice.address.bech32(), + sender: wallets.alice.address, + receiver: wallets.alice.address, gasLimit: 100000n, value: 1000000000000n, version: 2, @@ -194,16 +191,16 @@ describe("test transaction", async () => { it("should sign & compute hash (with data, with opaque, unused options) (legacy)", async () => { const transaction = new Transaction({ - nonce: 89, - value: "0", + nonce: 89n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: minGasLimit, + gasPrice: BigInt(minGasPrice), + gasLimit: BigInt(minGasLimit), chainID: "local-testnet", // The protocol ignores the options when version == 1 - version: new TransactionVersion(1), - options: new TransactionOptions(1), + version: 1, + options: 1, }); assert.throws(() => { @@ -213,13 +210,13 @@ describe("test transaction", async () => { it("should sign & compute hash (with data, with value) (legacy)", async () => { const transaction = new Transaction({ - nonce: 91, - value: TokenTransfer.egldFromAmount(10), + nonce: 91n, + value: 1000000000000000000n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: 100000, - data: new TransactionPayload("for the book"), + gasPrice: BigInt(minGasPrice), + gasLimit: 100000n, + data: Buffer.from("for the book"), chainID: "local-testnet", }); @@ -237,13 +234,13 @@ describe("test transaction", async () => { it("should sign & compute hash (with data, with large value) (legacy)", async () => { const transaction = new Transaction({ - nonce: 92, - value: TokenTransfer.egldFromBigInteger("123456789000000000000000000000"), + nonce: 92n, + value: BigInt("123456789000000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: 100000, - data: new TransactionPayload("for the spaceship"), + gasPrice: BigInt(minGasPrice), + gasLimit: 100000n, + data: Buffer.from("for the spaceship"), chainID: "local-testnet", }); @@ -261,15 +258,15 @@ describe("test transaction", async () => { it("should sign & compute hash (with nonce = 0) (legacy)", async () => { const transaction = new Transaction({ - nonce: 0, - value: 0, + nonce: 0n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasPrice: BigInt(minGasPrice), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", - version: new TransactionVersion(1), + version: 1, }); transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); @@ -286,12 +283,12 @@ describe("test transaction", async () => { it("should sign & compute hash (without options field, should be omitted) (legacy)", async () => { const transaction = new Transaction({ - nonce: 89, - value: 0, + nonce: 89n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: minGasLimit, + gasPrice: BigInt(minGasPrice), + gasLimit: BigInt(minGasLimit), chainID: "local-testnet", }); @@ -312,12 +309,12 @@ describe("test transaction", async () => { it("should sign & compute hash (with guardian field, should be omitted) (legacy)", async () => { const transaction = new Transaction({ - nonce: 89, - value: 0, + nonce: 89n, + value: 0n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: minGasLimit, + gasPrice: BigInt(minGasPrice), + gasLimit: BigInt(minGasLimit), chainID: "local-testnet", }); @@ -338,13 +335,13 @@ describe("test transaction", async () => { it("should sign & compute hash (with usernames) (legacy)", async () => { const transaction = new Transaction({ - nonce: 204, - value: "1000000000000000000", + nonce: 204n, + value: 1000000000000000000n, sender: Address.fromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"), receiver: Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), senderUsername: "carol", receiverUsername: "alice", - gasLimit: 50000, + gasLimit: 50000n, chainID: "T", }); @@ -365,8 +362,8 @@ describe("test transaction", async () => { const transaction = new Transaction({ chainID: "local-testnet", - sender: alice.address.bech32(), - receiver: wallets.bob.address.bech32(), + sender: alice.address, + receiver: wallets.bob.address, gasLimit: 150000n, gasPrice: 1000000000n, data: new Uint8Array(Buffer.from("test data field")), @@ -374,7 +371,7 @@ describe("test transaction", async () => { options: 2, nonce: 92n, value: 123456789000000000000000000000n, - guardian: "erd1x23lzn8483xs2su4fak0r0dqx6w38enpmmqf2yrkylwq7mfnvyhsxqw57y", + guardian: Address.fromBech32("erd1x23lzn8483xs2su4fak0r0dqx6w38enpmmqf2yrkylwq7mfnvyhsxqw57y"), }); transaction.guardianSignature = new Uint8Array(64); transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); @@ -396,12 +393,12 @@ describe("test transaction", async () => { it("computes fee (legacy)", () => { const transaction = new Transaction({ - nonce: 92, - value: TokenTransfer.egldFromBigInteger("123456789000000000000000000000"), + nonce: 92n, + value: BigInt("123456789000000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: minGasLimit, + gasPrice: BigInt(minGasPrice), + gasLimit: BigInt(minGasLimit), chainID: "local-testnet", }); @@ -412,10 +409,10 @@ describe("test transaction", async () => { it("computes fee", async () => { const transaction = new Transaction({ chainID: "D", - sender: wallets.alice.address.bech32(), - receiver: wallets.alice.address.bech32(), + sender: wallets.alice.address, + receiver: wallets.alice.address, gasLimit: 50000n, - gasPrice: minGasPrice, + gasPrice: BigInt(minGasPrice), }); const gasLimit = transactionComputer.computeTransactionFee(transaction, networkConfig); @@ -425,8 +422,8 @@ describe("test transaction", async () => { it("computes fee, but should throw `NotEnoughGas` error", async () => { const transaction = new Transaction({ chainID: networkConfig.ChainID, - sender: wallets.alice.address.bech32(), - receiver: wallets.alice.address.bech32(), + sender: wallets.alice.address, + receiver: wallets.alice.address, gasLimit: 50000n, data: Buffer.from("toolittlegaslimit"), }); @@ -438,13 +435,13 @@ describe("test transaction", async () => { it("computes fee (with data field) (legacy)", () => { let transaction = new Transaction({ - nonce: 92, - value: TokenTransfer.egldFromBigInteger("123456789000000000000000000000"), + nonce: 92n, + value: BigInt("123456789000000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - data: new TransactionPayload("testdata"), - gasPrice: minGasPrice, - gasLimit: minGasLimit + 12010, + data: Buffer.from("testdata"), + gasPrice: BigInt(minGasPrice), + gasLimit: BigInt(minGasLimit + 12010), chainID: "local-testnet", }); @@ -455,10 +452,10 @@ describe("test transaction", async () => { it("computes fee (with data field)", async () => { const transaction = new Transaction({ chainID: networkConfig.ChainID, - sender: wallets.alice.address.bech32(), - receiver: wallets.alice.address.bech32(), + sender: wallets.alice.address, + receiver: wallets.alice.address, gasLimit: 50000n + 12010n, - gasPrice: minGasPrice, + gasPrice: BigInt(minGasPrice), data: Buffer.from("testdata"), }); @@ -469,15 +466,15 @@ describe("test transaction", async () => { it("should convert transaction to plain object and back", () => { const sender = wallets.alice.address; const transaction = new Transaction({ - nonce: 90, - value: "123456789000000000000000000000", + nonce: 90n, + value: 123456789000000000000000000000n, sender: sender, receiver: wallets.bob.address, senderUsername: "alice", receiverUsername: "bob", - gasPrice: minGasPrice, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasPrice: BigInt(minGasPrice), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", }); @@ -488,19 +485,19 @@ describe("test transaction", async () => { it("should handle large values", () => { const tx1 = new Transaction({ - value: "123456789000000000000000000000", + value: 123456789000000000000000000000n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasLimit: 50000, + gasLimit: 50000n, chainID: "local-testnet", }); assert.equal(tx1.getValue().toString(), "123456789000000000000000000000"); const tx2 = new Transaction({ - value: TokenTransfer.egldFromBigInteger("123456789000000000000000000000"), + value: 123456789000000000000000000000n, sender: wallets.alice.address, receiver: wallets.bob.address, - gasLimit: 50000, + gasLimit: 50000n, chainID: "local-testnet", }); assert.equal(tx2.getValue().toString(), "123456789000000000000000000000"); @@ -509,10 +506,10 @@ describe("test transaction", async () => { // Passing a BigNumber is not recommended. // However, ITransactionValue interface is permissive, and developers may mistakenly pass such objects as values. // TokenTransfer objects or simple strings (see above) are preferred, instead. - value: new BigNumber("123456789000000000000000000000"), + value: BigInt("123456789000000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasLimit: 50000, + gasLimit: 50000n, chainID: "local-testnet", }); assert.equal(tx3.getValue().toString(), "123456789000000000000000000000"); @@ -520,88 +517,88 @@ describe("test transaction", async () => { it("checks correctly the version and options of the transaction", async () => { let transaction = new Transaction({ - nonce: 90, - value: new BigNumber("1000000000000000000"), + nonce: 90n, + value: BigInt("1000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasPrice: BigInt(minGasPrice), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", - version: new TransactionVersion(1), - options: TransactionOptions.withDefaultOptions(), + version: 1, + options: TRANSACTION_OPTIONS_DEFAULT, }); assert.isFalse(transaction.isGuardedTransaction()); transaction = new Transaction({ - nonce: 90, - value: new BigNumber("1000000000000000000"), + nonce: 90n, + value: BigInt("1000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasPrice: BigInt(minGasPrice), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", - version: new TransactionVersion(1), - options: TransactionOptions.withOptions({ guarded: true }), + version: 1, + options: 2, }); assert.isFalse(transaction.isGuardedTransaction()); transaction = new Transaction({ - nonce: 90, - value: new BigNumber("1000000000000000000"), + nonce: 90n, + value: BigInt("1000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasPrice: BigInt(minGasPrice), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", - version: new TransactionVersion(2), - options: TransactionOptions.withOptions({ guarded: true }), + version: 2, + options: 2, }); assert.isFalse(transaction.isGuardedTransaction()); transaction = new Transaction({ - nonce: 90, - value: new BigNumber("1000000000000000000"), + nonce: 90n, + value: BigInt("1000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasPrice: BigInt(minGasPrice), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", - version: new TransactionVersion(2), - options: TransactionOptions.withOptions({ guarded: true }), + version: 2, + options: 2, }); assert.isFalse(transaction.isGuardedTransaction()); transaction = new Transaction({ - nonce: 90, - value: new BigNumber("1000000000000000000"), + nonce: 90n, + value: BigInt("1000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, + gasPrice: BigInt(minGasPrice), guardian: wallets.bob.address, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", - version: new TransactionVersion(2), - options: TransactionOptions.withOptions({ guarded: true }), + version: 2, + options: 2, }); assert.isFalse(transaction.isGuardedTransaction()); transaction = new Transaction({ - nonce: 90, - value: new BigNumber("1000000000000000000"), + nonce: 90n, + value: BigInt("1000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, - gasPrice: minGasPrice, + gasPrice: BigInt(minGasPrice), guardian: wallets.bob.address, - gasLimit: 80000, - data: new TransactionPayload("hello"), + gasLimit: 80000n, + data: Buffer.from("hello"), chainID: "local-testnet", - version: new TransactionVersion(2), - options: TransactionOptions.withOptions({ guarded: true }), + version: 2, + options: 2, }); transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); transaction.applyGuardianSignature(transaction.getSignature()); @@ -612,8 +609,8 @@ describe("test transaction", async () => { let transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address.toBech32(), - receiver: wallets.bob.address.toBech32(), + sender: wallets.alice.address, + receiver: wallets.bob.address, gasLimit: 50000n, gasPrice: 1000000000n, chainID: "integration tests chain ID", @@ -633,25 +630,25 @@ describe("test transaction", async () => { let transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address.toBech32(), - receiver: wallets.bob.address.toBech32(), + sender: wallets.alice.address, + receiver: wallets.bob.address, gasLimit: 50000n, chainID: "localnet", }); - transactionComputer.applyGuardian(transaction, wallets.carol.address.toBech32()); + transactionComputer.applyGuardian(transaction, wallets.carol.address); assert.equal(transaction.version, 2); assert.equal(transaction.options, 2); - assert.equal(transaction.guardian, wallets.carol.address.toBech32()); + assert.equal(transaction.guardian, wallets.carol.address); }); it("should apply guardian with options set for hash signing", async () => { let transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address.toBech32(), - receiver: wallets.bob.address.toBech32(), + sender: wallets.alice.address, + receiver: wallets.bob.address, gasLimit: 50000n, chainID: "localnet", version: 1, @@ -661,20 +658,20 @@ describe("test transaction", async () => { assert.equal(transaction.version, 2); assert.equal(transaction.options, 1); - transactionComputer.applyGuardian(transaction, wallets.carol.address.toBech32()); + transactionComputer.applyGuardian(transaction, wallets.carol.address); assert.equal(transaction.version, 2); assert.equal(transaction.options, 3); }); it("should ensure transaction is valid", async () => { let transaction = new Transaction({ - sender: "invalidAddress", - receiver: wallets.bob.address.toBech32(), + sender: Address.empty(), + receiver: wallets.bob.address, gasLimit: 50000n, chainID: "", }); - transaction.sender = wallets.alice.address.toBech32(); + transaction.sender = wallets.alice.address; assert.throws(() => { transactionComputer.computeBytesForSigning(transaction); @@ -696,8 +693,8 @@ describe("test transaction", async () => { it("should compute bytes to verify transaction signature", async () => { let transaction = new Transaction({ - sender: wallets.alice.address.toBech32(), - receiver: wallets.bob.address.toBech32(), + sender: wallets.alice.address, + receiver: wallets.bob.address, gasLimit: 50000n, chainID: "D", nonce: 7n, @@ -725,8 +722,8 @@ describe("test transaction", async () => { it("should compute bytes to verify transaction signature (signed by hash)", async () => { let transaction = new Transaction({ - sender: wallets.alice.address.toBech32(), - receiver: wallets.bob.address.toBech32(), + sender: wallets.alice.address, + receiver: wallets.bob.address, gasLimit: 50000n, chainID: "D", nonce: 7n, diff --git a/src/transaction.ts b/src/transaction.ts index 0921bfcb7..ad477e095 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -3,24 +3,10 @@ import { Address } from "./address"; import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; import { TransactionsConverter } from "./converters/transactionsConverter"; import { Hash } from "./hash"; -import { - IAddress, - IChainID, - IGasLimit, - IGasPrice, - INonce, - IPlainTransactionObject, - ISignature, - ITransactionOptions, - ITransactionPayload, - ITransactionValue, - ITransactionVersion, -} from "./interface"; +import { IGasLimit, IGasPrice, INonce, IPlainTransactionObject, ISignature, ITransactionValue } from "./interface"; import { INetworkConfig } from "./interfaceOfNetwork"; -import { TransactionOptions, TransactionVersion } from "./networkParams"; import { interpretSignatureAsBuffer } from "./signature"; import { TransactionComputer } from "./transactionComputer"; -import { TransactionPayload } from "./transactionPayload"; /** * An abstraction for creating and signing transactions. @@ -37,14 +23,14 @@ export class Transaction { public value: bigint; /** - * The address of the sender, in bech32 format. + * The address of the sender. */ - public sender: string; + public sender: Address; /** - * The address of the receiver, in bech32 format. + * The address of the receiver. */ - public receiver: string; + public receiver: Address; /** * The username of the sender. @@ -89,7 +75,7 @@ export class Transaction { /** * The address of the guardian, in bech32 format. */ - public guardian: string; + public guardian: Address; /** * The signature. @@ -105,19 +91,19 @@ export class Transaction { * Creates a new Transaction object. */ public constructor(options: { - nonce?: INonce | bigint; - value?: ITransactionValue | bigint; - sender: IAddress | string; - receiver: IAddress | string; + nonce?: bigint; + value?: bigint; + sender: Address; + receiver: Address; senderUsername?: string; receiverUsername?: string; - gasPrice?: IGasPrice | bigint; - gasLimit: IGasLimit | bigint; - data?: ITransactionPayload | Uint8Array; - chainID: IChainID | string; - version?: ITransactionVersion | number; - options?: ITransactionOptions | number; - guardian?: IAddress | string; + gasPrice?: bigint; + gasLimit: bigint; + data?: Uint8Array; + chainID: string; + version?: number; + options?: number; + guardian?: Address; signature?: Uint8Array; guardianSignature?: Uint8Array; }) { @@ -125,8 +111,8 @@ export class Transaction { // We still rely on "bigNumber" for value, because client code might be passing a BigNumber object as a legacy "ITransactionValue", // and we want to keep compatibility. this.value = options.value ? BigInt(new BigNumber(options.value.toString()).toFixed(0)) : 0n; - this.sender = this.addressAsBech32(options.sender); - this.receiver = this.addressAsBech32(options.receiver); + this.sender = options.sender; + this.receiver = options.receiver; this.senderUsername = options.senderUsername || ""; this.receiverUsername = options.receiverUsername || ""; this.gasPrice = BigInt(options.gasPrice?.valueOf() || TRANSACTION_MIN_GAS_PRICE); @@ -135,16 +121,12 @@ export class Transaction { this.chainID = options.chainID.valueOf(); this.version = Number(options.version?.valueOf() || TRANSACTION_VERSION_DEFAULT); this.options = Number(options.options?.valueOf() || TRANSACTION_OPTIONS_DEFAULT); - this.guardian = options.guardian ? this.addressAsBech32(options.guardian) : ""; + this.guardian = options.guardian ?? Address.empty(); this.signature = options.signature || Buffer.from([]); this.guardianSignature = options.guardianSignature || Buffer.from([]); } - private addressAsBech32(address: IAddress | string): string { - return typeof address === "string" ? address : address.bech32(); - } - /** * Legacy method, use the "nonce" property instead. */ @@ -178,21 +160,21 @@ export class Transaction { * Legacy method, use the "sender" property instead. */ getSender(): Address { - return Address.fromBech32(this.sender); + return this.sender; } /** * Legacy method, use the "sender" property instead. */ - setSender(sender: Address | string) { - this.sender = typeof sender === "string" ? sender : sender.bech32(); + setSender(sender: Address) { + this.sender = sender; } /** * Legacy method, use the "receiver" property instead. */ getReceiver(): Address { - return Address.fromBech32(this.receiver); + return this.receiver; } /** @@ -227,7 +209,7 @@ export class Transaction { * Legacy method, use the "guardian" property instead. */ getGuardian(): Address { - return new Address(this.guardian); + return this.guardian; } /** @@ -261,43 +243,43 @@ export class Transaction { /** * Legacy method, use the "data" property instead. */ - getData(): ITransactionPayload { - return new TransactionPayload(Buffer.from(this.data)); + getData(): Uint8Array { + return this.data; } /** * Legacy method, use the "chainID" property instead. */ - getChainID(): IChainID { + getChainID(): string { return this.chainID; } /** * Legacy method, use the "chainID" property instead. */ - setChainID(chainID: IChainID | string) { - this.chainID = chainID.valueOf(); + setChainID(chainID: string) { + this.chainID = chainID; } /** * Legacy method, use the "version" property instead. */ - getVersion(): TransactionVersion { - return new TransactionVersion(this.version); + getVersion(): number { + return this.version; } /** * Legacy method, use the "version" property instead. */ - setVersion(version: ITransactionVersion | number) { - this.version = version.valueOf(); + setVersion(version: number) { + this.version = version; } /** * Legacy method, use the "options" property instead. */ - getOptions(): TransactionOptions { - return new TransactionOptions(this.options.valueOf()); + getOptions(): number { + return this.options; } /** @@ -305,8 +287,8 @@ export class Transaction { * * Question for review: check how the options are set by sdk-dapp, wallet, ledger, extension. */ - setOptions(options: ITransactionOptions | number) { - this.options = options.valueOf(); + setOptions(options: number) { + this.options = options; } /** @@ -326,8 +308,8 @@ export class Transaction { /** * Legacy method, use the "guardian" property instead. */ - setGuardian(guardian: IAddress | string) { - this.guardian = typeof guardian === "string" ? guardian : guardian.bech32(); + setGuardian(guardian: Address) { + this.guardian = guardian; } /** @@ -352,9 +334,9 @@ export class Transaction { * Checks the integrity of the guarded transaction */ isGuardedTransaction(): boolean { - const hasGuardian = this.guardian.length > 0; + const hasGuardian = !this.guardian.isEmpty; const hasGuardianSignature = this.guardianSignature.length > 0; - return this.getOptions().isWithGuardian() && hasGuardian && hasGuardianSignature; + return hasGuardian && hasGuardianSignature; } /** diff --git a/src/transactionBuilder.ts b/src/transactionBuilder.ts index d4b684a6b..2ef3b64b5 100644 --- a/src/transactionBuilder.ts +++ b/src/transactionBuilder.ts @@ -1,5 +1,6 @@ +import { Address } from "./address"; import { ARGUMENTS_SEPARATOR } from "./constants"; -import { IAddress, ITransactionPayload } from "./interface"; +import { ITransactionPayload } from "./interface"; import { Transaction } from "./transaction"; import { TransactionPayload } from "./transactionPayload"; @@ -14,8 +15,8 @@ interface Config { */ export class TransactionBuilder { private config: Config; - private sender: IAddress; - private receiver: IAddress; + private sender: Address; + private receiver: Address; private dataParts: string[]; private providedGasLimit: bigint; private addDataMovementGas: boolean; @@ -23,8 +24,8 @@ export class TransactionBuilder { constructor(options: { config: Config; - sender: IAddress; - receiver: IAddress; + sender: Address; + receiver: Address; dataParts: string[]; gasLimit: bigint; addDataMovementGas: boolean; @@ -59,8 +60,8 @@ export class TransactionBuilder { const gasLimit = this.computeGasLimit(data); return new Transaction({ - sender: this.sender.bech32(), - receiver: this.receiver.bech32(), + sender: this.sender, + receiver: this.receiver, gasLimit: gasLimit, value: this.amount || 0n, data: data.valueOf(), diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index da365e7b2..069c1b64f 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -1,11 +1,11 @@ import BigNumber from "bignumber.js"; +import { Address } from "./address"; import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, TRANSACTION_OPTIONS_TX_GUARDED, TRANSACTION_OPTIONS_TX_HASH_SIGN, } from "./constants"; import * as errors from "./errors"; -import { ITransaction } from "./interface"; import { INetworkConfig } from "./interfaceOfNetwork"; import { ProtoSerializer } from "./proto"; import { Transaction } from "./transaction"; @@ -46,15 +46,16 @@ export class TransactionComputer { return feeForMove + processingFee; } - computeBytesForSigning(transaction: ITransaction): Uint8Array { + computeBytesForSigning(transaction: Transaction): Uint8Array { this.ensureValidTransactionFields(transaction); const plainTransaction = this.toPlainObject(transaction); + console.log({ plainTransaction }); const serialized = JSON.stringify(plainTransaction); return new Uint8Array(Buffer.from(serialized)); } - computeBytesForVerifying(transaction: ITransaction): Uint8Array { + computeBytesForVerifying(transaction: Transaction): Uint8Array { const isTxSignedByHash = this.hasOptionsSetForHashSigning(transaction); if (isTxSignedByHash) { @@ -63,13 +64,13 @@ export class TransactionComputer { return this.computeBytesForSigning(transaction); } - computeHashForSigning(transaction: ITransaction): Uint8Array { + computeHashForSigning(transaction: Transaction): Uint8Array { const plainTransaction = this.toPlainObject(transaction); const signable = Buffer.from(JSON.stringify(plainTransaction)); return createKeccakHash("keccak256").update(signable).digest(); } - computeTransactionHash(transaction: ITransaction): Uint8Array { + computeTransactionHash(transaction: Transaction): Uint8Array { const serializer = new ProtoSerializer(); const buffer = serializer.serializeTransaction(new Transaction(transaction)); const hash = createTransactionHasher(TRANSACTION_HASH_LENGTH).update(buffer).digest("hex"); @@ -77,15 +78,15 @@ export class TransactionComputer { return Buffer.from(hash, "hex"); } - hasOptionsSetForGuardedTransaction(transaction: ITransaction): boolean { + hasOptionsSetForGuardedTransaction(transaction: Transaction): boolean { return (transaction.options & TRANSACTION_OPTIONS_TX_GUARDED) == TRANSACTION_OPTIONS_TX_GUARDED; } - hasOptionsSetForHashSigning(transaction: ITransaction): boolean { + hasOptionsSetForHashSigning(transaction: Transaction): boolean { return (transaction.options & TRANSACTION_OPTIONS_TX_HASH_SIGN) == TRANSACTION_OPTIONS_TX_HASH_SIGN; } - applyGuardian(transaction: ITransaction, guardian: string) { + applyGuardian(transaction: Transaction, guardian: Address) { if (transaction.version < MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { transaction.version = MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; } @@ -94,24 +95,24 @@ export class TransactionComputer { transaction.guardian = guardian; } - applyOptionsForHashSigning(transaction: ITransaction) { + applyOptionsForHashSigning(transaction: Transaction) { if (transaction.version < MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { transaction.version = MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; } transaction.options = transaction.options | TRANSACTION_OPTIONS_TX_HASH_SIGN; } - private toPlainObject(transaction: ITransaction, withSignature?: boolean) { + private toPlainObject(transaction: Transaction, withSignature?: boolean) { let obj: any = { nonce: Number(transaction.nonce), value: transaction.value.toString(), - receiver: transaction.receiver, - sender: transaction.sender, + receiver: transaction.receiver.bech32(), + sender: transaction.sender.bech32(), senderUsername: this.toBase64OrUndefined(transaction.senderUsername), receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), gasPrice: Number(transaction.gasPrice), gasLimit: Number(transaction.gasLimit), - data: this.toBase64OrUndefined(transaction.data), + data: transaction.data.length > 0 ? Buffer.from(transaction.data).toString("base64") : undefined, }; if (withSignature) { @@ -121,7 +122,7 @@ export class TransactionComputer { obj.chainID = transaction.chainID; obj.version = transaction.version; obj.options = transaction.options ? transaction.options : undefined; - obj.guardian = transaction.guardian ? transaction.guardian : undefined; + obj.guardian = transaction.guardian.isEmpty() ? undefined : transaction.guardian; return obj; } @@ -131,10 +132,11 @@ export class TransactionComputer { } private toBase64OrUndefined(value?: string | Uint8Array) { + console.log(1121, value && value.length ? Buffer.from(value).toString("base64") : undefined); return value && value.length ? Buffer.from(value).toString("base64") : undefined; } - private ensureValidTransactionFields(transaction: ITransaction) { + private ensureValidTransactionFields(transaction: Transaction) { if (!transaction.chainID.length) { throw new errors.ErrBadUsage("The `chainID` field is not set"); } diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 2a8ccbd5d..6718d6682 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -1,10 +1,10 @@ import { Address } from "./address"; -import { ITransaction } from "./interface"; +import { Transaction } from "./transaction"; import { TransactionLogs } from "./transactionLogs"; import { SmartContractResult } from "./transactionsOutcomeParsers"; import { TransactionStatus } from "./transactionStatus"; -export function prepareTransactionForBroadcasting(transaction: ITransaction): any { +export function prepareTransactionForBroadcasting(transaction: Transaction): any { return { nonce: Number(transaction.nonce), value: transaction.value.toString(), diff --git a/src/transfers/transferTransactionsFactory.spec.ts b/src/transfers/transferTransactionsFactory.spec.ts index b4cda39f9..e753db24e 100644 --- a/src/transfers/transferTransactionsFactory.spec.ts +++ b/src/transfers/transferTransactionsFactory.spec.ts @@ -36,8 +36,8 @@ describe("test transfer transactions factory", function () { nativeAmount: 1000000000000000000n, }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, bob.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, bob); assert.equal(transaction.value.valueOf(), 1000000000000000000n); assert.equal(transaction.gasLimit.valueOf(), 50000n); assert.deepEqual(transaction.data, new Uint8Array()); @@ -50,8 +50,8 @@ describe("test transfer transactions factory", function () { data: Buffer.from("test data"), }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, bob.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, bob); assert.equal(transaction.value.valueOf(), 1000000000000000000n); assert.equal(transaction.gasLimit.valueOf(), 63500n); assert.deepEqual(transaction.data, Buffer.from("test data")); @@ -66,8 +66,8 @@ describe("test transfer transactions factory", function () { tokenTransfers: [transfer], }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, bob.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, bob); assert.equal(transaction.value.valueOf(), 0n); assert.equal(transaction.gasLimit.valueOf(), 410000n); assert.deepEqual(transaction.data.toString(), "ESDTTransfer@464f4f2d313233343536@0f4240"); @@ -82,8 +82,8 @@ describe("test transfer transactions factory", function () { tokenTransfers: [transfer], }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, alice.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, alice); assert.equal(transaction.value.valueOf(), 0n); assert.equal(transaction.gasLimit.valueOf(), 1210500n); assert.deepEqual( @@ -101,8 +101,8 @@ describe("test transfer transactions factory", function () { tokenTransfers: [transfer], }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, alice.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, alice); assert.equal(transaction.value.valueOf(), 0n); assert.equal(transaction.gasLimit.valueOf(), 1219500n); assert.deepEqual( @@ -123,8 +123,8 @@ describe("test transfer transactions factory", function () { tokenTransfers: [firstTransfer, secondTransfer], }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, alice.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, alice); assert.equal(transaction.value.valueOf(), 0n); assert.equal(transaction.gasLimit.valueOf(), 1466000n); assert.deepEqual( @@ -152,8 +152,8 @@ describe("test transfer transactions factory", function () { tokenTransfers: [firstTransfer, secondTransfer], }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, alice.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, alice); assert.equal(transaction.value.valueOf(), 0n); assert.equal(transaction.gasLimit.valueOf(), 1484000n); assert.deepEqual( @@ -188,8 +188,8 @@ describe("test transfer transactions factory", function () { nativeAmount: 1000000000000000000n, }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, bob.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, bob); assert.equal(transaction.value.valueOf(), 1000000000000000000n); assert.equal(transaction.gasLimit.valueOf(), 50000n); }); @@ -201,8 +201,8 @@ describe("test transfer transactions factory", function () { data: Buffer.from("hello"), }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, bob.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, bob); assert.equal(transaction.value.valueOf(), 1000000000000000000n); assert.equal(transaction.gasLimit.valueOf(), 57500n); assert.deepEqual(transaction.data, Buffer.from("hello")); @@ -214,8 +214,8 @@ describe("test transfer transactions factory", function () { data: Buffer.from("hello"), }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, bob.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, bob); assert.equal(transaction.gasLimit.valueOf(), 57500n); assert.deepEqual(transaction.data, Buffer.from("hello")); }); @@ -233,8 +233,8 @@ describe("test transfer transactions factory", function () { tokenTransfers: [firstTransfer, secondTransfer], }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, alice.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, alice); assert.equal(transaction.value.valueOf(), 0n); assert.equal(transaction.gasLimit.valueOf(), 1727500n); assert.deepEqual( @@ -256,8 +256,8 @@ describe("test transfer transactions factory", function () { tokenTransfers: [firstTransfer, secondTransfer], }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, alice.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, alice); assert.equal(transaction.value.valueOf(), 0n); assert.equal(transaction.gasLimit.valueOf(), 1745500n); assert.deepEqual( @@ -275,8 +275,8 @@ describe("test transfer transactions factory", function () { tokenTransfers: [firstTransfer], }); - assert.equal(transaction.sender, alice.toBech32()); - assert.equal(transaction.receiver, alice.toBech32()); + assert.equal(transaction.sender, alice); + assert.equal(transaction.receiver, alice); assert.equal(transaction.value.valueOf(), 0n); assert.equal(transaction.gasLimit.valueOf(), 1_243_500n); assert.deepEqual( diff --git a/src/transfers/transferTransactionsFactory.ts b/src/transfers/transferTransactionsFactory.ts index 8bb64c41d..b2b69fd52 100644 --- a/src/transfers/transferTransactionsFactory.ts +++ b/src/transfers/transferTransactionsFactory.ts @@ -1,21 +1,12 @@ import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, TypedValue, U16Value, U64Value } from "../abi"; +import { Address } from "../address"; import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../constants"; import { Err, ErrBadUsage } from "../errors"; -import { - IAddress, - IChainID, - IGasLimit, - IGasPrice, - INonce, - ITokenTransfer, - ITransactionPayload, - ITransactionValue, -} from "../interface"; +import { ITokenTransfer } from "../interface"; import { TokenComputer, TokenTransfer } from "../tokens"; import { TokenTransfersDataBuilder } from "../tokenTransfersDataBuilder"; import { Transaction } from "../transaction"; import { TransactionBuilder } from "../transactionBuilder"; -import { TransactionPayload } from "../transactionPayload"; import * as resources from "./resources"; const ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 100000; @@ -82,17 +73,14 @@ export class TransferTransactionsFactory { } } - createTransactionForNativeTokenTransfer( - sender: IAddress, - options: resources.NativeTokenTransferInput, - ): Transaction { + createTransactionForNativeTokenTransfer(sender: Address, options: resources.NativeTokenTransferInput): Transaction { this.ensureConfigIsDefined(); const data = options.data || new Uint8Array(); return new Transaction({ - sender: sender.bech32(), - receiver: options.receiver.bech32(), + sender: sender, + receiver: options.receiver, chainID: this.config!.chainID, gasLimit: this.computeGasForMoveBalance(this.config!, data), data: data, @@ -100,7 +88,7 @@ export class TransferTransactionsFactory { }); } - createTransactionForESDTTokenTransfer(sender: IAddress, options: resources.CustomTokenTransferInput): Transaction { + createTransactionForESDTTokenTransfer(sender: Address, options: resources.CustomTokenTransferInput): Transaction { this.ensureConfigIsDefined(); const numberOfTransfers = options.tokenTransfers.length; @@ -128,7 +116,7 @@ export class TransferTransactionsFactory { }).build(); } - createTransactionForTransfer(sender: IAddress, options: resources.CreateTransferTransactionInput): Transaction { + createTransactionForTransfer(sender: Address, options: resources.CreateTransferTransactionInput): Transaction { const nativeAmount = options.nativeAmount ?? 0n; let tokenTransfers = options.tokenTransfers ? [...options.tokenTransfers] : []; const numberOfTokens = tokenTransfers.length; @@ -161,14 +149,14 @@ export class TransferTransactionsFactory { * Use {@link createTransactionForNativeTokenTransfer} instead. */ createEGLDTransfer(args: { - nonce?: INonce; - value: ITransactionValue; - receiver: IAddress; - sender: IAddress; - gasPrice?: IGasPrice; - gasLimit?: IGasLimit; - data?: ITransactionPayload; - chainID: IChainID; + nonce?: bigint; + value: bigint; + receiver: Address; + sender: Address; + gasPrice?: bigint; + gasLimit?: bigint; + data?: Uint8Array; + chainID: string; }) { if (!this.isGasEstimatorDefined()) { throw new Err( @@ -176,7 +164,7 @@ export class TransferTransactionsFactory { ); } - const dataLength = args.data?.length() || 0; + const dataLength = args.data?.length || 0; const estimatedGasLimit = this.gasEstimator!.forEGLDTransfer(dataLength); return new Transaction({ @@ -185,7 +173,7 @@ export class TransferTransactionsFactory { receiver: args.receiver, sender: args.sender, gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, + gasLimit: args.gasLimit || BigInt(estimatedGasLimit), data: args.data, chainID: args.chainID, }); @@ -197,12 +185,12 @@ export class TransferTransactionsFactory { */ createESDTTransfer(args: { tokenTransfer: ITokenTransfer; - nonce?: INonce; - receiver: IAddress; - sender: IAddress; - gasPrice?: IGasPrice; - gasLimit?: IGasLimit; - chainID: IChainID; + nonce?: bigint; + receiver: Address; + sender: Address; + gasPrice?: bigint; + gasLimit?: bigint; + chainID: string; }) { if (!this.isGasEstimatorDefined()) { throw new Err( @@ -218,8 +206,8 @@ export class TransferTransactionsFactory { ]); const data = `ESDTTransfer@${argumentsString}`; - const transactionPayload = new TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; + const transactionPayload = Buffer.from(data); + const dataLength = transactionPayload.length || 0; const estimatedGasLimit = this.gasEstimator!.forESDTTransfer(dataLength); return new Transaction({ @@ -227,7 +215,7 @@ export class TransferTransactionsFactory { receiver: args.receiver, sender: args.sender, gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, + gasLimit: args.gasLimit || BigInt(estimatedGasLimit), data: transactionPayload, chainID: args.chainID, }); @@ -239,12 +227,12 @@ export class TransferTransactionsFactory { */ createESDTNFTTransfer(args: { tokenTransfer: ITokenTransfer; - nonce?: INonce; - destination: IAddress; - sender: IAddress; - gasPrice?: IGasPrice; - gasLimit?: IGasLimit; - chainID: IChainID; + nonce?: bigint; + destination: Address; + sender: Address; + gasPrice?: bigint; + gasLimit?: bigint; + chainID: string; }) { if (!this.isGasEstimatorDefined()) { throw new Err( @@ -264,8 +252,8 @@ export class TransferTransactionsFactory { ]); const data = `ESDTNFTTransfer@${argumentsString}`; - const transactionPayload = new TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; + const transactionPayload = Buffer.from(data); + const dataLength = transactionPayload.length || 0; const estimatedGasLimit = this.gasEstimator!.forESDTNFTTransfer(dataLength); return new Transaction({ @@ -273,7 +261,7 @@ export class TransferTransactionsFactory { receiver: args.sender, sender: args.sender, gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, + gasLimit: args.gasLimit || BigInt(estimatedGasLimit), data: transactionPayload, chainID: args.chainID, }); @@ -285,12 +273,12 @@ export class TransferTransactionsFactory { */ createMultiESDTNFTTransfer(args: { tokenTransfers: ITokenTransfer[]; - nonce?: INonce; - destination: IAddress; - sender: IAddress; - gasPrice?: IGasPrice; - gasLimit?: IGasLimit; - chainID: IChainID; + nonce?: bigint; + destination: Address; + sender: Address; + gasPrice?: bigint; + gasLimit?: bigint; + chainID: string; }) { if (!this.isGasEstimatorDefined()) { throw new Err( @@ -320,8 +308,8 @@ export class TransferTransactionsFactory { const { argumentsString } = new ArgSerializer().valuesToString(parts); const data = `MultiESDTNFTTransfer@${argumentsString}`; - const transactionPayload = new TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; + const transactionPayload = Buffer.from(data); + const dataLength = transactionPayload.length || 0; const estimatedGasLimit = this.gasEstimator!.forMultiESDTNFTTransfer(dataLength, args.tokenTransfers.length); return new Transaction({ @@ -329,16 +317,16 @@ export class TransferTransactionsFactory { receiver: args.sender, sender: args.sender, gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, + gasLimit: args.gasLimit || BigInt(estimatedGasLimit), data: transactionPayload, chainID: args.chainID, }); } private createSingleESDTTransferTransaction( - sender: IAddress, + sender: Address, options: { - receiver: IAddress; + receiver: Address; tokenTransfers: TokenTransfer[]; }, ): Transaction { @@ -360,7 +348,7 @@ export class TransferTransactionsFactory { }).build(); } - private buildTransferData(transfer: TokenTransfer, options: { sender: IAddress; receiver: IAddress }) { + private buildTransferData(transfer: TokenTransfer, options: { sender: Address; receiver: Address }) { let dataParts: string[] = []; let extraGasForTransfer: bigint; let receiver = options.receiver; @@ -379,7 +367,7 @@ export class TransferTransactionsFactory { return { dataParts, extraGasForTransfer, receiver }; } - private buildMultiESDTNFTTransferData(transfer: TokenTransfer[], receiver: IAddress) { + private buildMultiESDTNFTTransferData(transfer: TokenTransfer[], receiver: Address) { return { dataParts: this.tokenTransfersDataBuilder!.buildDataPartsForMultiESDTNFTTransfer(receiver, transfer), extraGasForTransfer: @@ -395,7 +383,7 @@ export class TransferTransactionsFactory { }; } - private buildSingleESDTNFTTransferData(transfer: TokenTransfer, receiver: IAddress) { + private buildSingleESDTNFTTransferData(transfer: TokenTransfer, receiver: Address) { return { dataParts: this.tokenTransfersDataBuilder!.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver), extraGasForTransfer: this.config!.gasLimitESDTNFTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER), From 992e0ed990c2eaf7144266a38b0d7fa0aca90f97 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 10 Dec 2024 23:05:49 +0200 Subject: [PATCH 077/214] Fixed Relayed tests --- src/relayed/relayedTransactionsFactory.ts | 17 ++++++++--------- src/transactionComputer.ts | 1 - 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/relayed/relayedTransactionsFactory.ts b/src/relayed/relayedTransactionsFactory.ts index fbe70c473..12e878cd6 100644 --- a/src/relayed/relayedTransactionsFactory.ts +++ b/src/relayed/relayedTransactionsFactory.ts @@ -87,20 +87,20 @@ export class RelayedTransactionsFactory { private prepareInnerTransactionForRelayedV1(innerTransaction: Transaction): string { const txObject = { - nonce: innerTransaction.nonce, + nonce: Number(innerTransaction.nonce), sender: innerTransaction.sender.getPublicKey().toString("base64"), receiver: innerTransaction.receiver.getPublicKey().toString("base64"), - value: innerTransaction.value, - gasPrice: innerTransaction.gasPrice, - gasLimit: innerTransaction.gasLimit, + value: innerTransaction.value.toString(), + gasPrice: Number(innerTransaction.gasPrice), + gasLimit: Number(innerTransaction.gasLimit), data: Buffer.from(innerTransaction.data).toString("base64"), signature: Buffer.from(innerTransaction.signature).toString("base64"), chainID: Buffer.from(innerTransaction.chainID).toString("base64"), version: innerTransaction.version, - options: innerTransaction.options.valueOf() == 0 ? undefined : innerTransaction.options, - guardian: innerTransaction.guardian - ? innerTransaction.guardian.getPublicKey().toString("base64") - : undefined, + options: innerTransaction.options == 0 ? undefined : innerTransaction.options, + guardian: innerTransaction.guardian.isEmpty() + ? undefined + : innerTransaction.guardian.getPublicKey().toString("base64"), guardianSignature: innerTransaction.guardianSignature.length ? Buffer.from(innerTransaction.guardianSignature).toString("base64") : undefined, @@ -111,7 +111,6 @@ export class RelayedTransactionsFactory { ? Buffer.from(innerTransaction.receiverUsername).toString("base64") : undefined, }; - return JSONbig.stringify(txObject); } } diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index 069c1b64f..a9cbec3b5 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -50,7 +50,6 @@ export class TransactionComputer { this.ensureValidTransactionFields(transaction); const plainTransaction = this.toPlainObject(transaction); - console.log({ plainTransaction }); const serialized = JSON.stringify(plainTransaction); return new Uint8Array(Buffer.from(serialized)); } From b7ab17fba35a25ff654f52939ec274b5411a65a3 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 10 Dec 2024 23:07:55 +0200 Subject: [PATCH 078/214] Fix compile issues on integration tests --- src/abi/interaction.local.net.spec.ts | 2 +- src/abi/smartContractResults.local.net.spec.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 298117045..39af45ae1 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -139,7 +139,7 @@ describe("test smart contract interactor", function () { contract: contract, deployer: alice, codePath: "src/testdata/basic-features.wasm", - gasLimit: 600000000, + gasLimit: 600000000n, initArguments: [], chainID: network.ChainID, }); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 87201fa5e..a2f34ad0e 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -42,7 +42,7 @@ describe("fetch transactions from local testnet", function () { contract: contract, deployer: alice, codePath: "src/testdata/counter.wasm", - gasLimit: 3000000, + gasLimit: 3000000n, initArguments: [], chainID: network.ChainID, }); @@ -50,7 +50,7 @@ describe("fetch transactions from local testnet", function () { // ++ let transactionIncrement = contract.call({ func: new ContractFunction("increment"), - gasLimit: 3000000, + gasLimit: 3000000n, chainID: network.ChainID, caller: alice.address, }); From ca9e3cb9ac8701cd508d835cbf283bfa5a6a56a4 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 10 Dec 2024 23:13:07 +0200 Subject: [PATCH 079/214] Fix devnet tests --- src/transactionOnNetwork.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 6718d6682..9260c5625 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -8,8 +8,8 @@ export function prepareTransactionForBroadcasting(transaction: Transaction): any return { nonce: Number(transaction.nonce), value: transaction.value.toString(), - receiver: transaction.receiver, - sender: transaction.sender, + receiver: transaction.receiver.bech32(), + sender: transaction.sender.bech32(), senderUsername: transaction.senderUsername ? Buffer.from(transaction.senderUsername).toString("base64") : undefined, @@ -22,7 +22,7 @@ export function prepareTransactionForBroadcasting(transaction: Transaction): any chainID: transaction.chainID, version: transaction.version, options: transaction.options, - guardian: transaction.guardian || undefined, + guardian: transaction.guardian.isEmpty() ? undefined : transaction.guardian.bech32(), signature: Buffer.from(transaction.signature).toString("hex"), guardianSignature: transaction.guardianSignature.length === 0 From b99bfaaec2af11a1c30ab5b4c550a88238768256 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 11 Dec 2024 11:19:28 +0200 Subject: [PATCH 080/214] Fixed relayed transactions tests --- src/relayed/relayedTransactionsFactory.ts | 8 ++++---- src/transactionComputer.ts | 3 +-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/relayed/relayedTransactionsFactory.ts b/src/relayed/relayedTransactionsFactory.ts index 12e878cd6..71f6a440e 100644 --- a/src/relayed/relayedTransactionsFactory.ts +++ b/src/relayed/relayedTransactionsFactory.ts @@ -87,12 +87,12 @@ export class RelayedTransactionsFactory { private prepareInnerTransactionForRelayedV1(innerTransaction: Transaction): string { const txObject = { - nonce: Number(innerTransaction.nonce), + nonce: innerTransaction.nonce, sender: innerTransaction.sender.getPublicKey().toString("base64"), receiver: innerTransaction.receiver.getPublicKey().toString("base64"), - value: innerTransaction.value.toString(), - gasPrice: Number(innerTransaction.gasPrice), - gasLimit: Number(innerTransaction.gasLimit), + value: innerTransaction.value, + gasPrice: innerTransaction.gasPrice, + gasLimit: innerTransaction.gasLimit, data: Buffer.from(innerTransaction.data).toString("base64"), signature: Buffer.from(innerTransaction.signature).toString("base64"), chainID: Buffer.from(innerTransaction.chainID).toString("base64"), diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index a9cbec3b5..47846b34d 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -121,7 +121,7 @@ export class TransactionComputer { obj.chainID = transaction.chainID; obj.version = transaction.version; obj.options = transaction.options ? transaction.options : undefined; - obj.guardian = transaction.guardian.isEmpty() ? undefined : transaction.guardian; + obj.guardian = transaction.guardian.isEmpty() ? undefined : transaction.guardian.bech32(); return obj; } @@ -131,7 +131,6 @@ export class TransactionComputer { } private toBase64OrUndefined(value?: string | Uint8Array) { - console.log(1121, value && value.length ? Buffer.from(value).toString("base64") : undefined); return value && value.length ? Buffer.from(value).toString("base64") : undefined; } From ebac363c257d3ed833c4285e05e61b204fe3da37 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 11 Dec 2024 14:20:32 +0200 Subject: [PATCH 081/214] Fix transactions tests --- src/proto/serializer.ts | 3 +-- src/transaction.spec.ts | 2 +- src/transaction.ts | 12 +++++++++--- src/transactionComputer.ts | 2 +- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/proto/serializer.ts b/src/proto/serializer.ts index 9c0f90631..f38426179 100644 --- a/src/proto/serializer.ts +++ b/src/proto/serializer.ts @@ -3,7 +3,6 @@ import { bigIntToBuffer } from "../abi/codec/utils"; import { Address } from "../address"; import { TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_OPTIONS_TX_GUARDED } from "../constants"; import * as errors from "../errors"; -import { ITransactionValue } from "../interface"; import { Transaction } from "../transaction"; /** @@ -66,7 +65,7 @@ export class ProtoSerializer { /** * Custom serialization, compatible with mx-chain-go. */ - private serializeTransactionValue(transactionValue: ITransactionValue): Buffer { + private serializeTransactionValue(transactionValue: bigint): Buffer { let value = new BigNumber(transactionValue.toString()); if (value.isZero()) { return Buffer.from([0, 0]); diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index b7d9484ac..b68d12c5f 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -211,7 +211,7 @@ describe("test transaction", async () => { it("should sign & compute hash (with data, with value) (legacy)", async () => { const transaction = new Transaction({ nonce: 91n, - value: 1000000000000000000n, + value: 10000000000000000000n, sender: wallets.alice.address, receiver: wallets.bob.address, gasPrice: BigInt(minGasPrice), diff --git a/src/transaction.ts b/src/transaction.ts index ad477e095..2309b527c 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,6 +1,11 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; -import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; +import { + TRANSACTION_MIN_GAS_PRICE, + TRANSACTION_OPTIONS_DEFAULT, + TRANSACTION_OPTIONS_TX_GUARDED, + TRANSACTION_VERSION_DEFAULT, +} from "./constants"; import { TransactionsConverter } from "./converters/transactionsConverter"; import { Hash } from "./hash"; import { IGasLimit, IGasPrice, INonce, IPlainTransactionObject, ISignature, ITransactionValue } from "./interface"; @@ -334,9 +339,10 @@ export class Transaction { * Checks the integrity of the guarded transaction */ isGuardedTransaction(): boolean { - const hasGuardian = !this.guardian.isEmpty; + const hasGuardian = !this.guardian.isEmpty(); const hasGuardianSignature = this.guardianSignature.length > 0; - return hasGuardian && hasGuardianSignature; + const isGuardedSet = (this.options & TRANSACTION_OPTIONS_TX_GUARDED) == TRANSACTION_OPTIONS_TX_GUARDED; + return isGuardedSet && hasGuardian && hasGuardianSignature; } /** diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index 47846b34d..d47b5ae93 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -71,7 +71,7 @@ export class TransactionComputer { computeTransactionHash(transaction: Transaction): Uint8Array { const serializer = new ProtoSerializer(); - const buffer = serializer.serializeTransaction(new Transaction(transaction)); + const buffer = serializer.serializeTransaction(transaction); const hash = createTransactionHasher(TRANSACTION_HASH_LENGTH).update(buffer).digest("hex"); return Buffer.from(hash, "hex"); From 83ac284623ade29c5a1c7190478796639c992677 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 11 Dec 2024 14:46:59 +0200 Subject: [PATCH 082/214] Update transaction mapping --- src/transactionComputer.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index d47b5ae93..ab3a63b63 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -111,7 +111,7 @@ export class TransactionComputer { receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), gasPrice: Number(transaction.gasPrice), gasLimit: Number(transaction.gasLimit), - data: transaction.data.length > 0 ? Buffer.from(transaction.data).toString("base64") : undefined, + data: this.toBase64OrUndefined(transaction.data), }; if (withSignature) { From 7585eb94ba9dcd276f5d2055d25f5ddade84ce44 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 11 Dec 2024 22:50:28 +0200 Subject: [PATCH 083/214] Update bech32 to new method toBech32 --- src/abi/interaction.spec.ts | 34 +++++++++---------- src/abi/smartContract.spec.ts | 12 +++++-- src/abi/smartContract.ts | 4 +-- src/abi/typesystem/address.ts | 2 +- .../accountTransactionsFactory.ts | 2 +- src/accounts/account.ts | 2 +- src/address.spec.ts | 2 +- src/compatibility.ts | 4 +-- src/converters/transactionsConverter.ts | 6 ++-- src/message.ts | 2 +- src/networkProviders/apiNetworkProvider.ts | 10 +++--- .../providers.dev.net.spec.ts | 2 +- src/networkProviders/proxyNetworkProvider.ts | 12 +++---- .../smartContractTransactionsFactory.ts | 2 +- src/testutils/mockNetworkProvider.ts | 10 +++--- src/transactionComputer.ts | 6 ++-- src/transactionOnNetwork.ts | 6 ++-- src/wallet/pem.spec.ts | 2 +- src/wallet/userSigner.ts | 2 +- 19 files changed, 64 insertions(+), 58 deletions(-) diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index b3a79a7d7..eed4731d8 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -59,7 +59,7 @@ describe("test smart contract interactor", function () { const hexBar = "4241522d356263303866"; const hexLKMEX = "4c4b4d45582d616162393130"; const hexNFT = "4d4f532d623962346232"; - const hexContractAddress = new Address(contract.getAddress().bech32()).hex(); + const hexContractAddress = new Address(contract.getAddress().toBech32()).hex(); const hexDummyFunction = "64756d6d79"; // ESDT, single @@ -76,8 +76,8 @@ describe("test smart contract interactor", function () { .withSingleESDTNFTTransfer(LKMEX(123456, 123.456)) .buildTransaction(); - assert.equal(transaction.getSender().bech32(), alice.bech32()); - assert.equal(transaction.getReceiver().bech32(), alice.bech32()); + assert.equal(transaction.getSender().toBech32(), alice.toBech32()); + assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); assert.equal( transaction.getData().toString(), `ESDTNFTTransfer@${hexLKMEX}@01e240@06b14bd1e6eea00000@${hexContractAddress}@${hexDummyFunction}`, @@ -89,8 +89,8 @@ describe("test smart contract interactor", function () { .withSender(alice) .buildTransaction(); - assert.equal(transaction.getSender().bech32(), alice.bech32()); - assert.equal(transaction.getReceiver().bech32(), alice.bech32()); + assert.equal(transaction.getSender().toBech32(), alice.toBech32()); + assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); assert.equal( transaction.getData().toString(), `ESDTNFTTransfer@${hexLKMEX}@01e240@06b14bd1e6eea00000@${hexContractAddress}@${hexDummyFunction}`, @@ -102,8 +102,8 @@ describe("test smart contract interactor", function () { .withSingleESDTNFTTransfer(nonFungibleToken(1)) .buildTransaction(); - assert.equal(transaction.getSender().bech32(), alice.bech32()); - assert.equal(transaction.getReceiver().bech32(), alice.bech32()); + assert.equal(transaction.getSender().toBech32(), alice.toBech32()); + assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); assert.equal( transaction.getData().toString(), `ESDTNFTTransfer@${hexNFT}@01@01@${hexContractAddress}@${hexDummyFunction}`, @@ -115,8 +115,8 @@ describe("test smart contract interactor", function () { .withSender(alice) .buildTransaction(); - assert.equal(transaction.getSender().bech32(), alice.bech32()); - assert.equal(transaction.getReceiver().bech32(), alice.bech32()); + assert.equal(transaction.getSender().toBech32(), alice.toBech32()); + assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); assert.equal( transaction.getData().toString(), `ESDTNFTTransfer@${hexNFT}@01@01@${hexContractAddress}@${hexDummyFunction}`, @@ -128,8 +128,8 @@ describe("test smart contract interactor", function () { .withMultiESDTNFTTransfer([TokenFoo(3), TokenBar(3.14)]) .buildTransaction(); - assert.equal(transaction.getSender().bech32(), alice.bech32()); - assert.equal(transaction.getReceiver().bech32(), alice.bech32()); + assert.equal(transaction.getSender().toBech32(), alice.toBech32()); + assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); assert.equal( transaction.getData().toString(), `MultiESDTNFTTransfer@${hexContractAddress}@02@${hexFoo}@@03@${hexBar}@@0c44@${hexDummyFunction}`, @@ -141,8 +141,8 @@ describe("test smart contract interactor", function () { .withSender(alice) .buildTransaction(); - assert.equal(transaction.getSender().bech32(), alice.bech32()); - assert.equal(transaction.getReceiver().bech32(), alice.bech32()); + assert.equal(transaction.getSender().toBech32(), alice.toBech32()); + assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); assert.equal( transaction.getData().toString(), `MultiESDTNFTTransfer@${hexContractAddress}@02@${hexFoo}@@03@${hexBar}@@0c44@${hexDummyFunction}`, @@ -154,8 +154,8 @@ describe("test smart contract interactor", function () { .withMultiESDTNFTTransfer([nonFungibleToken(1), nonFungibleToken(42)]) .buildTransaction(); - assert.equal(transaction.getSender().bech32(), alice.bech32()); - assert.equal(transaction.getReceiver().bech32(), alice.bech32()); + assert.equal(transaction.getSender().toBech32(), alice.toBech32()); + assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); assert.equal( transaction.getData().toString(), `MultiESDTNFTTransfer@${hexContractAddress}@02@${hexNFT}@01@01@${hexNFT}@2a@01@${hexDummyFunction}`, @@ -167,8 +167,8 @@ describe("test smart contract interactor", function () { .withSender(alice) .buildTransaction(); - assert.equal(transaction.getSender().bech32(), alice.bech32()); - assert.equal(transaction.getReceiver().bech32(), alice.bech32()); + assert.equal(transaction.getSender().toBech32(), alice.toBech32()); + assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); }); it("should create transaction, with ABI, with transfer & execute", async function () { diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index b6424fcd5..cc4944511 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -29,10 +29,13 @@ describe("test contract", () => { let owner = new Address("93ee6143cdc10ce79f15b2a6c2ad38e9b6021c72a1779051f47154fd54cfbd5e"); let firstContractAddress = SmartContract.computeAddress(owner, 0); - assert.equal(firstContractAddress.bech32(), "erd1qqqqqqqqqqqqqpgqhdjjyq8dr7v5yq9tv6v5vt9tfvd00vg7h40q6779zn"); + assert.equal(firstContractAddress.toBech32(), "erd1qqqqqqqqqqqqqpgqhdjjyq8dr7v5yq9tv6v5vt9tfvd00vg7h40q6779zn"); let secondContractAddress = SmartContract.computeAddress(owner, 1); - assert.equal(secondContractAddress.bech32(), "erd1qqqqqqqqqqqqqpgqde8eqjywyu6zlxjxuxqfg5kgtmn3setxh40qen8egy"); + assert.equal( + secondContractAddress.toBech32(), + "erd1qqqqqqqqqqqqqpgqde8eqjywyu6zlxjxuxqfg5kgtmn3setxh40qen8egy", + ); }); it("should deploy", async () => { @@ -60,7 +63,10 @@ describe("test contract", () => { // Compute & set the contract address contract.setAddress(SmartContract.computeAddress(alice.address, 42)); - assert.equal(contract.getAddress().bech32(), "erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q"); + assert.equal( + contract.getAddress().toBech32(), + "erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q", + ); // Sign the transaction deployTransaction.applySignature(await alice.signer.sign(deployTransaction.serializeForSigning())); diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 7b5f40a58..b8fb5fe75 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -276,7 +276,7 @@ export class SmartContract implements ISmartContract { } private ensureHasAddress() { - if (!this.getAddress().bech32()) { + if (!this.getAddress().toBech32()) { throw new ErrContractHasNoAddress(); } } @@ -289,7 +289,7 @@ export class SmartContract implements ISmartContract { * @param nonce The owner nonce used for the deployment transaction */ static computeAddress(owner: Address, nonce: INonce): Address { - const deployer = Address.fromBech32(owner.bech32()); + const deployer = Address.fromBech32(owner.toBech32()); const addressComputer = new AddressComputer(); return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); } diff --git a/src/abi/typesystem/address.ts b/src/abi/typesystem/address.ts index 81d3c6750..7fc34fe90 100644 --- a/src/abi/typesystem/address.ts +++ b/src/abi/typesystem/address.ts @@ -22,7 +22,7 @@ export class AddressValue extends PrimitiveValue { constructor(value: Address) { super(new AddressType()); - this.value = Address.newFromBech32(value.bech32()); + this.value = Address.newFromBech32(value.toBech32()); } getClassName(): string { diff --git a/src/accountManagement/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts index 37b17662f..6104ddf89 100644 --- a/src/accountManagement/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -63,7 +63,7 @@ export class AccountTransactionsFactory { createTransactionForSettingGuardian(sender: Address, options: SetGuardianInput): Transaction { const dataParts = [ "SetGuardian", - Address.fromBech32(options.guardianAddress.bech32()).toHex(), + Address.fromBech32(options.guardianAddress.toBech32()).toHex(), Buffer.from(options.serviceID).toString("hex"), ]; diff --git a/src/accounts/account.ts b/src/accounts/account.ts index 126e194d3..4f6060a32 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -52,7 +52,7 @@ export class Account implements IAccount { */ toJSON(): any { return { - address: this.address.bech32(), + address: this.address.toBech32(), nonce: this.nonce.valueOf(), }; } diff --git a/src/address.spec.ts b/src/address.spec.ts index 46552556a..ee7546755 100644 --- a/src/address.spec.ts +++ b/src/address.spec.ts @@ -35,7 +35,7 @@ describe("test address", () => { const nobody = Address.empty(); assert.isEmpty(nobody.hex()); - assert.isEmpty(nobody.bech32()); + assert.isEmpty(nobody.toBech32()); assert.deepEqual(nobody.toJSON(), { bech32: "", pubkey: "" }); }); diff --git a/src/compatibility.ts b/src/compatibility.ts index 9caf1977a..37c2d5bc1 100644 --- a/src/compatibility.ts +++ b/src/compatibility.ts @@ -9,11 +9,11 @@ export class Compatibility { * For internal use only. */ static guardAddressIsSetAndNonZero(address: IAddress | undefined, context: string, resolution: string) { - if (!address || address.bech32() == "") { + if (!address || address.toBech32() == "") { 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()) { + } else if (address.toBech32() == Address.Zero().toBech32()) { 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/converters/transactionsConverter.ts b/src/converters/transactionsConverter.ts index 93d70608f..ba6d7649b 100644 --- a/src/converters/transactionsConverter.ts +++ b/src/converters/transactionsConverter.ts @@ -7,8 +7,8 @@ export class TransactionsConverter { const plainObject = { nonce: Number(transaction.nonce), value: transaction.value.toString(), - receiver: transaction.receiver.bech32(), - sender: transaction.sender.bech32(), + receiver: transaction.receiver.toBech32(), + sender: transaction.sender.toBech32(), senderUsername: this.toBase64OrUndefined(transaction.senderUsername), receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), gasPrice: Number(transaction.gasPrice), @@ -17,7 +17,7 @@ export class TransactionsConverter { chainID: transaction.chainID.valueOf(), version: transaction.version, options: transaction.options == 0 ? undefined : transaction.options, - guardian: transaction.guardian.isEmpty() ? undefined : transaction.guardian.bech32(), + guardian: transaction.guardian.isEmpty() ? undefined : transaction.guardian.toBech32(), signature: this.toHexOrUndefined(transaction.signature), guardianSignature: this.toHexOrUndefined(transaction.guardianSignature), }; diff --git a/src/message.ts b/src/message.ts index 8b2dbfce1..4d10df6cd 100644 --- a/src/message.ts +++ b/src/message.ts @@ -65,7 +65,7 @@ export class MessageComputer { return { message: Buffer.from(message.data).toString("hex"), signature: message.signature ? Buffer.from(message.signature).toString("hex") : "", - address: message.address ? message.address.bech32() : "", + address: message.address ? message.address.toBech32() : "", version: message.version, signer: message.signer, }; diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 7b2bd6a4d..5ce410267 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -65,7 +65,7 @@ export class ApiNetworkProvider implements INetworkProvider { } async getAccount(address: IAddress): Promise { - const response = await this.doGetGeneric(`accounts/${address.bech32()}`); + const response = await this.doGetGeneric(`accounts/${address.toBech32()}`); const account = AccountOnNetwork.fromHttpResponse(response); return account; } @@ -80,7 +80,7 @@ export class ApiNetworkProvider implements INetworkProvider { ): Promise { pagination = pagination || defaultPagination; - const url = `accounts/${address.bech32()}/tokens?${this.buildPaginationParams(pagination)}`; + const url = `accounts/${address.toBech32()}/tokens?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); const tokens = response.map((item) => FungibleTokenOfAccountOnNetwork.fromHttpResponse(item)); @@ -95,7 +95,7 @@ export class ApiNetworkProvider implements INetworkProvider { ): Promise { pagination = pagination || defaultPagination; - const url = `accounts/${address.bech32()}/nfts?${this.buildPaginationParams(pagination)}`; + const url = `accounts/${address.toBech32()}/nfts?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); const tokens = response.map((item) => NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(item)); @@ -108,7 +108,7 @@ export class ApiNetworkProvider implements INetworkProvider { address: IAddress, tokenIdentifier: string, ): Promise { - const response = await this.doGetGeneric(`accounts/${address.bech32()}/tokens/${tokenIdentifier}`); + const response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${tokenIdentifier}`); const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response); return tokenData; } @@ -119,7 +119,7 @@ export class ApiNetworkProvider implements INetworkProvider { nonce: number, ): Promise { const nonceAsHex = numberToPaddedHex(nonce); - const response = await this.doGetGeneric(`accounts/${address.bech32()}/nfts/${collection}-${nonceAsHex}`); + const response = await this.doGetGeneric(`accounts/${address.toBech32()}/nfts/${collection}-${nonceAsHex}`); const tokenData = NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(response); return tokenData; } diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 9d9ee763e..3c5a09e7e 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -175,7 +175,7 @@ describe("test network providers on devnet: Proxy and API", function () { let proxyItemResponse = await proxyProvider.getNonFungibleTokenOfAccount(dan, item.collection, item.nonce); removeInconsistencyForNonFungibleTokenOfAccount(apiItemResponse, proxyItemResponse); - assert.deepEqual(apiResponse, proxyResponse, `user: ${dan.bech32()}, token: ${item.identifier}`); + assert.deepEqual(apiResponse, proxyResponse, `user: ${dan.toBech32()}, token: ${item.identifier}`); }); // TODO: Strive to have as little differences as possible between Proxy and API. diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 07808c50d..85e601ca1 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -57,13 +57,13 @@ export class ProxyNetworkProvider implements INetworkProvider { } async getAccount(address: IAddress): Promise { - const response = await this.doGetGeneric(`address/${address.bech32()}`); + const response = await this.doGetGeneric(`address/${address.toBech32()}`); const account = AccountOnNetwork.fromHttpResponse(response.account); return account; } async getGuardianData(address: IAddress): Promise { - const response = await this.doGetGeneric(`address/${address.bech32()}/guardian-data`); + const response = await this.doGetGeneric(`address/${address.toBech32()}/guardian-data`); const accountGuardian = GuardianData.fromHttpResponse(response.guardianData); return accountGuardian; } @@ -72,7 +72,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: IAddress, _pagination?: IPagination, ): Promise { - const url = `address/${address.bech32()}/esdt`; + const url = `address/${address.toBech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); // Skip NFTs / SFTs. @@ -88,7 +88,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: IAddress, _pagination?: IPagination, ): Promise { - const url = `address/${address.bech32()}/esdt`; + const url = `address/${address.toBech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); // Skip fungible tokens. @@ -106,7 +106,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: IAddress, tokenIdentifier: string, ): Promise { - const response = await this.doGetGeneric(`address/${address.bech32()}/esdt/${tokenIdentifier}`); + const response = await this.doGetGeneric(`address/${address.toBech32()}/esdt/${tokenIdentifier}`); const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response.tokenData); return tokenData; } @@ -117,7 +117,7 @@ export class ProxyNetworkProvider implements INetworkProvider { nonce: number, ): Promise { const response = await this.doGetGeneric( - `address/${address.bech32()}/nft/${collection}/nonce/${nonce.valueOf()}`, + `address/${address.toBech32()}/nft/${collection}/nonce/${nonce.valueOf()}`, ); const tokenData = NonFungibleTokenOfAccountOnNetwork.fromProxyHttpResponseByNonce(response.tokenData); return tokenData; diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index 899904d0c..dd0cb2617 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -185,7 +185,7 @@ export class SmartContractTransactionsFactory { contract: Address; newOwner: Address; }): Transaction { - const dataParts = ["ChangeOwnerAddress", Address.fromBech32(options.newOwner.bech32()).toHex()]; + const dataParts = ["ChangeOwnerAddress", Address.fromBech32(options.newOwner.toBech32()).toHex()]; return new TransactionBuilder({ config: this.config, diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index f5c63d9b7..053b7754e 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -38,18 +38,18 @@ export class MockNetworkProvider implements INetworkProvider { this.accounts = new Map(); this.accounts.set( - MockNetworkProvider.AddressOfAlice.bech32(), + MockNetworkProvider.AddressOfAlice.toBech32(), new AccountOnNetwork({ nonce: 0, balance: createAccountBalance(1000), }), ); this.accounts.set( - MockNetworkProvider.AddressOfBob.bech32(), + MockNetworkProvider.AddressOfBob.toBech32(), new AccountOnNetwork({ nonce: 5, balance: createAccountBalance(500) }), ); this.accounts.set( - MockNetworkProvider.AddressOfCarol.bech32(), + MockNetworkProvider.AddressOfCarol.toBech32(), new AccountOnNetwork({ nonce: 42, balance: createAccountBalance(300), @@ -107,7 +107,7 @@ export class MockNetworkProvider implements INetworkProvider { } mockUpdateAccount(address: Address, mutate: (item: IAccountOnNetwork) => void) { - let account = this.accounts.get(address.bech32()); + let account = this.accounts.get(address.toBech32()); if (account) { mutate(account); } @@ -173,7 +173,7 @@ export class MockNetworkProvider implements INetworkProvider { } async getAccount(address: Address): Promise { - let account = this.accounts.get(address.bech32()); + let account = this.accounts.get(address.toBech32()); if (account) { return account; } diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index ab3a63b63..52bd568ef 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -105,8 +105,8 @@ export class TransactionComputer { let obj: any = { nonce: Number(transaction.nonce), value: transaction.value.toString(), - receiver: transaction.receiver.bech32(), - sender: transaction.sender.bech32(), + receiver: transaction.receiver.toBech32(), + sender: transaction.sender.toBech32(), senderUsername: this.toBase64OrUndefined(transaction.senderUsername), receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), gasPrice: Number(transaction.gasPrice), @@ -121,7 +121,7 @@ export class TransactionComputer { obj.chainID = transaction.chainID; obj.version = transaction.version; obj.options = transaction.options ? transaction.options : undefined; - obj.guardian = transaction.guardian.isEmpty() ? undefined : transaction.guardian.bech32(); + obj.guardian = transaction.guardian.isEmpty() ? undefined : transaction.guardian.toBech32(); return obj; } diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 9260c5625..0e7b4f496 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -8,8 +8,8 @@ export function prepareTransactionForBroadcasting(transaction: Transaction): any return { nonce: Number(transaction.nonce), value: transaction.value.toString(), - receiver: transaction.receiver.bech32(), - sender: transaction.sender.bech32(), + receiver: transaction.receiver.toBech32(), + sender: transaction.sender.toBech32(), senderUsername: transaction.senderUsername ? Buffer.from(transaction.senderUsername).toString("base64") : undefined, @@ -22,7 +22,7 @@ export function prepareTransactionForBroadcasting(transaction: Transaction): any chainID: transaction.chainID, version: transaction.version, options: transaction.options, - guardian: transaction.guardian.isEmpty() ? undefined : transaction.guardian.bech32(), + guardian: transaction.guardian.isEmpty() ? undefined : transaction.guardian.toBech32(), signature: Buffer.from(transaction.signature).toString("hex"), guardianSignature: transaction.guardianSignature.length === 0 diff --git a/src/wallet/pem.spec.ts b/src/wallet/pem.spec.ts index 73eda6b96..3c4557ae1 100644 --- a/src/wallet/pem.spec.ts +++ b/src/wallet/pem.spec.ts @@ -18,7 +18,7 @@ describe("test PEMs", () => { let aliceKey = parseUserKey(alice.pemFileText); assert.equal(aliceKey.hex(), alice.secretKeyHex); - assert.equal(aliceKey.generatePublicKey().toAddress().bech32(), alice.address.bech32()); + assert.equal(aliceKey.generatePublicKey().toAddress().toBech32(), alice.address.toBech32()); }); it("should parseValidatorKey", async () => { diff --git a/src/wallet/userSigner.ts b/src/wallet/userSigner.ts index acc8f6f09..f0652a791 100644 --- a/src/wallet/userSigner.ts +++ b/src/wallet/userSigner.ts @@ -45,7 +45,7 @@ export class UserSigner { * Gets the address of the signer. */ getAddress(hrp?: string): Address { - const bech32 = this.secretKey.generatePublicKey().toAddress(hrp).bech32(); + const bech32 = this.secretKey.generatePublicKey().toAddress(hrp).toBech32(); return Address.newFromBech32(bech32); } } From 6345f3723596f7f662b5868d9eb22eabbd2d84a8 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 11 Dec 2024 23:06:09 +0200 Subject: [PATCH 084/214] Code review follow up --- .../accountTransactionsFactory.ts | 2 +- src/compatibility.ts | 4 +- .../delegationTransactionsFactory.spec.ts | 97 +++++-------------- src/networkProviders/apiNetworkProvider.ts | 10 +- src/networkProviders/proxyNetworkProvider.ts | 12 +-- src/transaction.ts | 11 +-- src/wallet/userSigner.ts | 2 +- 7 files changed, 44 insertions(+), 94 deletions(-) diff --git a/src/accountManagement/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts index 6104ddf89..37b17662f 100644 --- a/src/accountManagement/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -63,7 +63,7 @@ export class AccountTransactionsFactory { createTransactionForSettingGuardian(sender: Address, options: SetGuardianInput): Transaction { const dataParts = [ "SetGuardian", - Address.fromBech32(options.guardianAddress.toBech32()).toHex(), + Address.fromBech32(options.guardianAddress.bech32()).toHex(), Buffer.from(options.serviceID).toString("hex"), ]; diff --git a/src/compatibility.ts b/src/compatibility.ts index 37c2d5bc1..7fb18b5a8 100644 --- a/src/compatibility.ts +++ b/src/compatibility.ts @@ -9,11 +9,11 @@ export class Compatibility { * For internal use only. */ static guardAddressIsSetAndNonZero(address: IAddress | undefined, context: string, resolution: string) { - if (!address || address.toBech32() == "") { + 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.`, ); - } else if (address.toBech32() == Address.Zero().toBech32()) { + } else if (address.bech32() == Address.Zero().toBech32()) { 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/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index eece6f1cd..65a11930d 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -35,7 +35,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for adding nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( "e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208", @@ -61,10 +61,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -77,7 +74,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for removing nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( @@ -94,10 +91,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -110,7 +104,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for staking nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", @@ -126,10 +120,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -142,7 +133,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for unbonding nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", @@ -158,10 +149,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -175,7 +163,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for unstaking nodes", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", @@ -191,10 +179,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -208,9 +193,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for unjailing nodes", async function () { const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.newFromBech32( - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc", - ); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", @@ -226,10 +209,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual( transaction.data, @@ -242,9 +222,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for changing service fee", async function () { const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.newFromBech32( - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc", - ); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const serviceFee = 10n; const transaction = delegationFactory.createTransactionForChangingServiceFee(sender, { @@ -256,10 +234,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("changeServiceFee@0a")); assert.equal(transaction.value, 0n); @@ -267,7 +242,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for changing delegation cap", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const delegationCap = 5000000000000000000000n; const transaction = delegationFactory.createTransactionForModifyingDelegationCap(sender, { @@ -279,10 +254,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("modifyTotalDelegationCap@010f0cf064dd59200000")); assert.equal(transaction.value, 0n); @@ -290,7 +262,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for setting automatic activation", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForSettingAutomaticActivation(sender, { delegationContract: delegationContract, @@ -300,10 +272,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setAutomaticActivation@74727565")); assert.equal(transaction.value, 0n); @@ -311,7 +280,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for unsetting automatic activation", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForUnsettingAutomaticActivation(sender, { delegationContract: delegationContract, @@ -321,10 +290,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setAutomaticActivation@66616c7365")); assert.equal(transaction.value, 0n); @@ -332,7 +298,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for setting cap check on redelegate rewards", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForSettingCapCheckOnRedelegateRewards(sender, { delegationContract: delegationContract, @@ -342,10 +308,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setCheckCapOnReDelegateRewards@74727565")); assert.equal(transaction.value, 0n); @@ -353,7 +316,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for unsetting cap check on redelegate rewards", async function () { const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForUnsettingCapCheckOnRedelegateRewards(sender, { delegationContract: delegationContract, @@ -363,10 +326,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setCheckCapOnReDelegateRewards@66616c7365")); assert.equal(transaction.value, 0n); @@ -374,9 +334,7 @@ describe("test delegation transactions factory", function () { it("should create 'Transaction' for setting metadata", async function () { const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); - const delegationContract = Address.newFromBech32( - "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc", - ); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForSettingMetadata(sender, { delegationContract: delegationContract, @@ -389,10 +347,7 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual( - transaction.receiver, - Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqtllllls002zgc"), - ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("setMetaData@6e616d65@77656273697465@6964656e746966696572")); assert.equal(transaction.value, 0n); diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 5ce410267..7b2bd6a4d 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -65,7 +65,7 @@ export class ApiNetworkProvider implements INetworkProvider { } async getAccount(address: IAddress): Promise { - const response = await this.doGetGeneric(`accounts/${address.toBech32()}`); + const response = await this.doGetGeneric(`accounts/${address.bech32()}`); const account = AccountOnNetwork.fromHttpResponse(response); return account; } @@ -80,7 +80,7 @@ export class ApiNetworkProvider implements INetworkProvider { ): Promise { pagination = pagination || defaultPagination; - const url = `accounts/${address.toBech32()}/tokens?${this.buildPaginationParams(pagination)}`; + const url = `accounts/${address.bech32()}/tokens?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); const tokens = response.map((item) => FungibleTokenOfAccountOnNetwork.fromHttpResponse(item)); @@ -95,7 +95,7 @@ export class ApiNetworkProvider implements INetworkProvider { ): Promise { pagination = pagination || defaultPagination; - const url = `accounts/${address.toBech32()}/nfts?${this.buildPaginationParams(pagination)}`; + const url = `accounts/${address.bech32()}/nfts?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); const tokens = response.map((item) => NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(item)); @@ -108,7 +108,7 @@ export class ApiNetworkProvider implements INetworkProvider { address: IAddress, tokenIdentifier: string, ): Promise { - const response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${tokenIdentifier}`); + const response = await this.doGetGeneric(`accounts/${address.bech32()}/tokens/${tokenIdentifier}`); const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response); return tokenData; } @@ -119,7 +119,7 @@ export class ApiNetworkProvider implements INetworkProvider { nonce: number, ): Promise { const nonceAsHex = numberToPaddedHex(nonce); - const response = await this.doGetGeneric(`accounts/${address.toBech32()}/nfts/${collection}-${nonceAsHex}`); + const response = await this.doGetGeneric(`accounts/${address.bech32()}/nfts/${collection}-${nonceAsHex}`); const tokenData = NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(response); return tokenData; } diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 85e601ca1..07808c50d 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -57,13 +57,13 @@ export class ProxyNetworkProvider implements INetworkProvider { } async getAccount(address: IAddress): Promise { - const response = await this.doGetGeneric(`address/${address.toBech32()}`); + const response = await this.doGetGeneric(`address/${address.bech32()}`); const account = AccountOnNetwork.fromHttpResponse(response.account); return account; } async getGuardianData(address: IAddress): Promise { - const response = await this.doGetGeneric(`address/${address.toBech32()}/guardian-data`); + const response = await this.doGetGeneric(`address/${address.bech32()}/guardian-data`); const accountGuardian = GuardianData.fromHttpResponse(response.guardianData); return accountGuardian; } @@ -72,7 +72,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: IAddress, _pagination?: IPagination, ): Promise { - const url = `address/${address.toBech32()}/esdt`; + const url = `address/${address.bech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); // Skip NFTs / SFTs. @@ -88,7 +88,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: IAddress, _pagination?: IPagination, ): Promise { - const url = `address/${address.toBech32()}/esdt`; + const url = `address/${address.bech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); // Skip fungible tokens. @@ -106,7 +106,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: IAddress, tokenIdentifier: string, ): Promise { - const response = await this.doGetGeneric(`address/${address.toBech32()}/esdt/${tokenIdentifier}`); + const response = await this.doGetGeneric(`address/${address.bech32()}/esdt/${tokenIdentifier}`); const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response.tokenData); return tokenData; } @@ -117,7 +117,7 @@ export class ProxyNetworkProvider implements INetworkProvider { nonce: number, ): Promise { const response = await this.doGetGeneric( - `address/${address.toBech32()}/nft/${collection}/nonce/${nonce.valueOf()}`, + `address/${address.bech32()}/nft/${collection}/nonce/${nonce.valueOf()}`, ); const tokenData = NonFungibleTokenOfAccountOnNetwork.fromProxyHttpResponseByNonce(response.tokenData); return tokenData; diff --git a/src/transaction.ts b/src/transaction.ts index 2309b527c..60ba73e07 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,11 +1,6 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; -import { - TRANSACTION_MIN_GAS_PRICE, - TRANSACTION_OPTIONS_DEFAULT, - TRANSACTION_OPTIONS_TX_GUARDED, - TRANSACTION_VERSION_DEFAULT, -} from "./constants"; +import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; import { TransactionsConverter } from "./converters/transactionsConverter"; import { Hash } from "./hash"; import { IGasLimit, IGasPrice, INonce, IPlainTransactionObject, ISignature, ITransactionValue } from "./interface"; @@ -339,10 +334,10 @@ export class Transaction { * Checks the integrity of the guarded transaction */ isGuardedTransaction(): boolean { + const computer = new TransactionComputer(); const hasGuardian = !this.guardian.isEmpty(); const hasGuardianSignature = this.guardianSignature.length > 0; - const isGuardedSet = (this.options & TRANSACTION_OPTIONS_TX_GUARDED) == TRANSACTION_OPTIONS_TX_GUARDED; - return isGuardedSet && hasGuardian && hasGuardianSignature; + return computer.hasOptionsSetForGuardedTransaction(this) && hasGuardian && hasGuardianSignature; } /** diff --git a/src/wallet/userSigner.ts b/src/wallet/userSigner.ts index f0652a791..acc8f6f09 100644 --- a/src/wallet/userSigner.ts +++ b/src/wallet/userSigner.ts @@ -45,7 +45,7 @@ export class UserSigner { * Gets the address of the signer. */ getAddress(hrp?: string): Address { - const bech32 = this.secretKey.generatePublicKey().toAddress(hrp).toBech32(); + const bech32 = this.secretKey.generatePublicKey().toAddress(hrp).bech32(); return Address.newFromBech32(bech32); } } From 2553c87a1c0bdfb4936b20add497a40d37127e34 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 12 Dec 2024 14:00:03 +0200 Subject: [PATCH 085/214] Remove Transaction converter --- src/converters/index.ts | 1 - src/converters/transactionsConverter.ts | 65 ------------------ src/converters/transactionsConverters.spec.ts | 48 ------------- src/index.ts | 1 - src/transaction.spec.ts | 40 +++++++++++ src/transaction.ts | 68 ++++++++++++++++--- 6 files changed, 97 insertions(+), 126 deletions(-) delete mode 100644 src/converters/index.ts delete mode 100644 src/converters/transactionsConverter.ts delete mode 100644 src/converters/transactionsConverters.spec.ts diff --git a/src/converters/index.ts b/src/converters/index.ts deleted file mode 100644 index f43e67fcc..000000000 --- a/src/converters/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./transactionsConverter"; diff --git a/src/converters/transactionsConverter.ts b/src/converters/transactionsConverter.ts deleted file mode 100644 index ba6d7649b..000000000 --- a/src/converters/transactionsConverter.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { Address } from "../address"; -import { IPlainTransactionObject } from "../interface"; -import { Transaction } from "../transaction"; - -export class TransactionsConverter { - public transactionToPlainObject(transaction: Transaction): IPlainTransactionObject { - const plainObject = { - nonce: Number(transaction.nonce), - value: transaction.value.toString(), - receiver: transaction.receiver.toBech32(), - sender: transaction.sender.toBech32(), - senderUsername: this.toBase64OrUndefined(transaction.senderUsername), - receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), - gasPrice: Number(transaction.gasPrice), - gasLimit: Number(transaction.gasLimit), - data: this.toBase64OrUndefined(transaction.data), - chainID: transaction.chainID.valueOf(), - version: transaction.version, - options: transaction.options == 0 ? undefined : transaction.options, - guardian: transaction.guardian.isEmpty() ? undefined : transaction.guardian.toBech32(), - signature: this.toHexOrUndefined(transaction.signature), - guardianSignature: this.toHexOrUndefined(transaction.guardianSignature), - }; - - return plainObject; - } - - private toBase64OrUndefined(value?: string | Uint8Array) { - return value && value.length ? Buffer.from(value).toString("base64") : undefined; - } - - private toHexOrUndefined(value?: Uint8Array) { - return value && value.length ? Buffer.from(value).toString("hex") : undefined; - } - - public plainObjectToTransaction(object: IPlainTransactionObject): Transaction { - const transaction = new Transaction({ - nonce: BigInt(object.nonce), - value: BigInt(object.value || ""), - receiver: Address.newFromBech32(object.receiver), - receiverUsername: this.bufferFromBase64(object.receiverUsername).toString(), - sender: Address.newFromBech32(object.sender), - senderUsername: this.bufferFromBase64(object.senderUsername).toString(), - guardian: object.guardian ? Address.newFromBech32(object.guardian) : Address.empty(), - gasPrice: BigInt(object.gasPrice), - gasLimit: BigInt(object.gasLimit), - data: this.bufferFromBase64(object.data), - chainID: String(object.chainID), - version: Number(object.version), - options: Number(object.options), - signature: this.bufferFromHex(object.signature), - guardianSignature: this.bufferFromHex(object.guardianSignature), - }); - - return transaction; - } - - private bufferFromBase64(value?: string) { - return Buffer.from(value || "", "base64"); - } - - private bufferFromHex(value?: string) { - return Buffer.from(value || "", "hex"); - } -} diff --git a/src/converters/transactionsConverters.spec.ts b/src/converters/transactionsConverters.spec.ts deleted file mode 100644 index fe1fe20b2..000000000 --- a/src/converters/transactionsConverters.spec.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { assert } from "chai"; -import { Address } from "../address"; -import { Transaction } from "../transaction"; -import { TransactionsConverter } from "./transactionsConverter"; - -describe("test transactions converter", async () => { - it("converts transaction to plain object and back", () => { - const converter = new TransactionsConverter(); - - const transaction = new Transaction({ - nonce: 90n, - value: BigInt("123456789000000000000000000000"), - sender: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), - receiver: Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), - senderUsername: "alice", - receiverUsername: "bob", - gasPrice: 1000000000n, - gasLimit: 80000n, - data: Buffer.from("hello"), - chainID: "localnet", - version: 2, - }); - - const plainObject = converter.transactionToPlainObject(transaction); - const restoredTransaction = converter.plainObjectToTransaction(plainObject); - - assert.deepEqual(plainObject, transaction.toPlainObject()); - assert.deepEqual(restoredTransaction, Transaction.fromPlainObject(plainObject)); - assert.deepEqual(restoredTransaction, transaction); - assert.deepEqual(plainObject, { - nonce: 90, - value: "123456789000000000000000000000", - sender: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", - receiver: "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", - senderUsername: "YWxpY2U=", - receiverUsername: "Ym9i", - gasPrice: 1000000000, - gasLimit: 80000, - data: "aGVsbG8=", - chainID: "localnet", - version: 2, - options: undefined, - guardian: undefined, - signature: undefined, - guardianSignature: undefined, - }); - }); -}); diff --git a/src/index.ts b/src/index.ts index 9917a1971..fd82a4eb7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,7 +12,6 @@ export * from "./accounts"; export * from "./address"; export * from "./asyncTimer"; export * from "./config"; -export * from "./converters"; export * from "./delegation"; export * from "./entrypoints"; export * from "./errors"; diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index b68d12c5f..4d1042f1e 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -748,4 +748,44 @@ describe("test transaction", async () => { assert.equal(isSignedByAlice, true); assert.equal(isSignedByBob, false); }); + + it("converts transaction to plain object and back", () => { + const transaction = new Transaction({ + nonce: 90n, + value: BigInt("123456789000000000000000000000"), + sender: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + receiver: Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), + senderUsername: "alice", + receiverUsername: "bob", + gasPrice: 1000000000n, + gasLimit: 80000n, + data: Buffer.from("hello"), + chainID: "localnet", + version: 2, + }); + + const plainObject = transaction.toPlainObject(); + const restoredTransaction = Transaction.newFromPlainObject(plainObject); + + assert.deepEqual(plainObject, transaction.toPlainObject()); + assert.deepEqual(restoredTransaction, Transaction.fromPlainObject(plainObject)); + assert.deepEqual(restoredTransaction, transaction); + assert.deepEqual(plainObject, { + nonce: 90, + value: "123456789000000000000000000000", + sender: "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th", + receiver: "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", + senderUsername: "YWxpY2U=", + receiverUsername: "Ym9i", + gasPrice: 1000000000, + gasLimit: 80000, + data: "aGVsbG8=", + chainID: "localnet", + version: 2, + options: undefined, + guardian: undefined, + signature: undefined, + guardianSignature: undefined, + }); + }); }); diff --git a/src/transaction.ts b/src/transaction.ts index 60ba73e07..0328afea5 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,7 +1,6 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; -import { TransactionsConverter } from "./converters/transactionsConverter"; import { Hash } from "./hash"; import { IGasLimit, IGasPrice, INonce, IPlainTransactionObject, ISignature, ITransactionValue } from "./interface"; import { INetworkConfig } from "./interfaceOfNetwork"; @@ -341,27 +340,66 @@ export class Transaction { } /** - * Legacy method, use "TransactionsConverter.transactionToPlainObject()" instead. - * * Converts the transaction object into a ready-to-serialize, plain JavaScript object. * This function is called internally within the signing procedure. */ toPlainObject(): IPlainTransactionObject { - // Ideally, "converters" package should be outside of "core", and not referenced here. - const converter = new TransactionsConverter(); - return converter.transactionToPlainObject(this); + const plainObject = { + nonce: Number(this.nonce), + value: this.value.toString(), + receiver: this.receiver.toBech32(), + sender: this.sender.toBech32(), + senderUsername: this.toBase64OrUndefined(this.senderUsername), + receiverUsername: this.toBase64OrUndefined(this.receiverUsername), + gasPrice: Number(this.gasPrice), + gasLimit: Number(this.gasLimit), + data: this.toBase64OrUndefined(this.data), + chainID: this.chainID.valueOf(), + version: this.version, + options: this.options == 0 ? undefined : this.options, + guardian: this.guardian.isEmpty() ? undefined : this.guardian.toBech32(), + signature: this.toHexOrUndefined(this.signature), + guardianSignature: this.toHexOrUndefined(this.guardianSignature), + }; + + return plainObject; + } + + /** + * Legacy method, use "Transaction.newFromPlainObject()" instead. + * Converts a plain object transaction into a Transaction Object. + * + * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() + */ + static fromPlainObject(plainObjectTransaction: IPlainTransactionObject): Transaction { + return Transaction.newFromPlainObject(plainObjectTransaction); } /** - * Legacy method, use "TransactionsConverter.plainObjectToTransaction()" instead. * Converts a plain object transaction into a Transaction Object. * * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() */ - static fromPlainObject(plainObjectTransaction: IPlainTransactionObject): Transaction { - // Ideally, "converters" package should be outside of "core", and not referenced here. - const converter = new TransactionsConverter(); - return converter.plainObjectToTransaction(plainObjectTransaction); + static newFromPlainObject(object: IPlainTransactionObject): Transaction { + const transaction = new Transaction({ + nonce: BigInt(object.nonce), + value: BigInt(object.value || ""), + receiver: Address.newFromBech32(object.receiver), + receiverUsername: Buffer.from(object.receiverUsername || "", "base64").toString(), + sender: Address.newFromBech32(object.sender), + senderUsername: Buffer.from(object.senderUsername || "", "base64").toString(), + guardian: object.guardian ? Address.newFromBech32(object.guardian) : Address.empty(), + gasPrice: BigInt(object.gasPrice), + gasLimit: BigInt(object.gasLimit), + data: Buffer.from(object.data || "", "base64"), + chainID: String(object.chainID), + version: Number(object.version), + options: Number(object.options), + signature: Buffer.from(object.signature || "", "hex"), + guardianSignature: Buffer.from(object.guardianSignature || "", "hex"), + }); + + return transaction; } /** @@ -403,6 +441,14 @@ export class Transaction { const fee = computer.computeTransactionFee(this, networkConfig); return new BigNumber(fee.toString()); } + + private toBase64OrUndefined(value?: string | Uint8Array) { + return value && value.length ? Buffer.from(value).toString("base64") : undefined; + } + + private toHexOrUndefined(value?: Uint8Array) { + return value && value.length ? Buffer.from(value).toString("hex") : undefined; + } } /** From 9b42978a0d50f28d745c59cdde964b1e50e12708 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 12 Dec 2024 14:16:01 +0200 Subject: [PATCH 086/214] Remove IAddress Interface and update to use Address --- src/networkProviders/accounts.ts | 7 +++---- src/networkProviders/apiNetworkProvider.ts | 15 ++++++++------- src/networkProviders/interface.ts | 19 ++++++++----------- src/networkProviders/pairs.ts | 3 +-- src/networkProviders/proxyNetworkProvider.ts | 14 +++++++------- src/networkProviders/tokenDefinitions.ts | 5 ++--- src/networkProviders/tokens.ts | 3 +-- src/networkProviders/transactionReceipt.ts | 3 +-- src/testutils/mockNetworkProvider.ts | 10 +++++----- 9 files changed, 36 insertions(+), 43 deletions(-) diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index cee89aea6..673487e07 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -1,12 +1,11 @@ import BigNumber from "bignumber.js"; import { Address } from "../address"; -import { IAddress } from "./interface"; /** * A plain view of an account, as queried from the Network. */ export class AccountOnNetwork { - address: IAddress = Address.empty(); + address: Address = Address.empty(); nonce: number = 0; balance: BigNumber = new BigNumber(0); code: string = ""; @@ -54,7 +53,7 @@ export class GuardianData { return result; } - getCurrentGuardianAddress(): IAddress | undefined { + getCurrentGuardianAddress(): Address | undefined { if (!this.guarded) { return undefined; } @@ -65,7 +64,7 @@ export class GuardianData { class Guardian { activationEpoch: number = 0; - address: IAddress = Address.empty(); + address: Address = Address.empty(); serviceUID: string = ""; static fromHttpResponse(responsePart: any): Guardian { diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 7b2bd6a4d..3d4784769 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,3 +1,4 @@ +import { Address } from "../address"; import { ErrContractQuery, ErrNetworkProvider } from "../errors"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { Transaction } from "../transaction"; @@ -9,7 +10,7 @@ import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig, defaultPagination } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; -import { IAddress, INetworkProvider, IPagination } from "./interface"; +import { INetworkProvider, IPagination } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; @@ -64,18 +65,18 @@ export class ApiNetworkProvider implements INetworkProvider { return stats; } - async getAccount(address: IAddress): Promise { + async getAccount(address: Address): Promise { const response = await this.doGetGeneric(`accounts/${address.bech32()}`); const account = AccountOnNetwork.fromHttpResponse(response); return account; } - async getGuardianData(address: IAddress): Promise { + async getGuardianData(address: Address): Promise { return await this.backingProxyNetworkProvider.getGuardianData(address); } async getFungibleTokensOfAccount( - address: IAddress, + address: Address, pagination?: IPagination, ): Promise { pagination = pagination || defaultPagination; @@ -90,7 +91,7 @@ export class ApiNetworkProvider implements INetworkProvider { } async getNonFungibleTokensOfAccount( - address: IAddress, + address: Address, pagination?: IPagination, ): Promise { pagination = pagination || defaultPagination; @@ -105,7 +106,7 @@ export class ApiNetworkProvider implements INetworkProvider { } async getFungibleTokenOfAccount( - address: IAddress, + address: Address, tokenIdentifier: string, ): Promise { const response = await this.doGetGeneric(`accounts/${address.bech32()}/tokens/${tokenIdentifier}`); @@ -114,7 +115,7 @@ export class ApiNetworkProvider implements INetworkProvider { } async getNonFungibleTokenOfAccount( - address: IAddress, + address: Address, collection: string, nonce: number, ): Promise { diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 2ddd3b5bd..773f26135 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,3 +1,4 @@ +import { Address } from "../address"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { Transaction } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; @@ -37,31 +38,31 @@ export interface INetworkProvider { /** * Fetches the state of an account. */ - getAccount(address: IAddress): Promise; + getAccount(address: Address): Promise; /** * Fetches data about the fungible tokens held by an account. */ - getFungibleTokensOfAccount(address: IAddress, pagination?: IPagination): Promise; + getFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise; /** * Fetches data about the non-fungible tokens held by account. */ getNonFungibleTokensOfAccount( - address: IAddress, + address: Address, pagination?: IPagination, ): Promise; /** * Fetches data about a specific fungible token held by an account. */ - getFungibleTokenOfAccount(address: IAddress, tokenIdentifier: string): Promise; + getFungibleTokenOfAccount(address: Address, tokenIdentifier: string): Promise; /** * Fetches data about a specific non-fungible token (instance) held by an account. */ getNonFungibleTokenOfAccount( - address: IAddress, + address: Address, collection: string, nonce: number, ): Promise; @@ -124,8 +125,8 @@ export interface INetworkProvider { } export interface IContractQuery { - address: IAddress; - caller?: IAddress; + address: Address; + caller?: Address; func: { toString(): string }; value?: { toString(): string }; getEncodedArguments(): string[]; @@ -135,7 +136,3 @@ export interface IPagination { from: number; size: number; } - -export interface IAddress { - bech32(): string; -} diff --git a/src/networkProviders/pairs.ts b/src/networkProviders/pairs.ts index 31a92bf12..b54d10ced 100644 --- a/src/networkProviders/pairs.ts +++ b/src/networkProviders/pairs.ts @@ -1,9 +1,8 @@ import BigNumber from "bignumber.js"; import { Address } from "../address"; -import { IAddress } from "./interface"; export class PairOnNetwork { - address: IAddress = Address.empty(); + address: Address = Address.empty(); id: string = ""; symbol: string = ""; name: string = ""; diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 056f02c8b..f54ea8316 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -10,7 +10,7 @@ import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; -import { IAddress, INetworkProvider, IPagination } from "./interface"; +import { INetworkProvider, IPagination } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; @@ -58,20 +58,20 @@ export class ProxyNetworkProvider implements INetworkProvider { throw new Error("Method not implemented."); } - async getAccount(address: IAddress): Promise { + async getAccount(address: Address): Promise { const response = await this.doGetGeneric(`address/${address.bech32()}`); const account = AccountOnNetwork.fromHttpResponse(response.account); return account; } - async getGuardianData(address: IAddress): Promise { + async getGuardianData(address: Address): Promise { const response = await this.doGetGeneric(`address/${address.bech32()}/guardian-data`); const accountGuardian = GuardianData.fromHttpResponse(response.guardianData); return accountGuardian; } async getFungibleTokensOfAccount( - address: IAddress, + address: Address, _pagination?: IPagination, ): Promise { const url = `address/${address.bech32()}/esdt`; @@ -87,7 +87,7 @@ export class ProxyNetworkProvider implements INetworkProvider { } async getNonFungibleTokensOfAccount( - address: IAddress, + address: Address, _pagination?: IPagination, ): Promise { const url = `address/${address.bech32()}/esdt`; @@ -105,7 +105,7 @@ export class ProxyNetworkProvider implements INetworkProvider { } async getFungibleTokenOfAccount( - address: IAddress, + address: Address, tokenIdentifier: string, ): Promise { const response = await this.doGetGeneric(`address/${address.bech32()}/esdt/${tokenIdentifier}`); @@ -114,7 +114,7 @@ export class ProxyNetworkProvider implements INetworkProvider { } async getNonFungibleTokenOfAccount( - address: IAddress, + address: Address, collection: string, nonce: number, ): Promise { diff --git a/src/networkProviders/tokenDefinitions.ts b/src/networkProviders/tokenDefinitions.ts index fbaccf2ac..31f04ec5e 100644 --- a/src/networkProviders/tokenDefinitions.ts +++ b/src/networkProviders/tokenDefinitions.ts @@ -1,12 +1,11 @@ import BigNumber from "bignumber.js"; import { Address } from "../address"; -import { IAddress } from "./interface"; export class DefinitionOfFungibleTokenOnNetwork { identifier: string = ""; name: string = ""; ticker: string = ""; - owner: IAddress = Address.empty(); + owner: Address = Address.empty(); decimals: number = 0; supply: BigNumber = new BigNumber(0); isPaused: boolean = false; @@ -76,7 +75,7 @@ export class DefinitionOfTokenCollectionOnNetwork { type: string = ""; name: string = ""; ticker: string = ""; - owner: IAddress = Address.empty(); + owner: Address = Address.empty(); decimals: number = 0; canPause: boolean = false; canFreeze: boolean = false; diff --git a/src/networkProviders/tokens.ts b/src/networkProviders/tokens.ts index 1c838f070..04f0d49f9 100644 --- a/src/networkProviders/tokens.ts +++ b/src/networkProviders/tokens.ts @@ -1,7 +1,6 @@ import { BigNumber } from "bignumber.js"; import { Address } from "../address"; import { numberToPaddedHex } from "../utils.codec"; -import { IAddress } from "./interface"; export class FungibleTokenOfAccountOnNetwork { identifier: string = ""; @@ -27,7 +26,7 @@ export class NonFungibleTokenOfAccountOnNetwork { nonce: number = 0; type: string = ""; name: string = ""; - creator: IAddress = Address.empty(); + creator: Address = Address.empty(); supply: BigNumber = new BigNumber(0); decimals: number = 0; royalties: BigNumber = new BigNumber(0); diff --git a/src/networkProviders/transactionReceipt.ts b/src/networkProviders/transactionReceipt.ts index 49d14d62e..10947b2e7 100644 --- a/src/networkProviders/transactionReceipt.ts +++ b/src/networkProviders/transactionReceipt.ts @@ -1,9 +1,8 @@ import { Address } from "../address"; -import { IAddress } from "./interface"; export class TransactionReceipt { value: string = ""; - sender: IAddress = Address.empty(); + sender: Address = Address.empty(); data: string = ""; hash: string = ""; diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 053b7754e..6d61df274 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -14,7 +14,7 @@ import { NetworkStatus, NonFungibleTokenOfAccountOnNetwork, } from "../networkProviders"; -import { IAddress, INetworkProvider, IPagination } from "../networkProviders/interface"; +import { INetworkProvider, IPagination } from "../networkProviders/interface"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { Transaction, TransactionHash } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; @@ -66,22 +66,22 @@ export class MockNetworkProvider implements INetworkProvider { throw new Error("Method not implemented."); } getFungibleTokensOfAccount( - _address: IAddress, + _address: Address, _pagination?: IPagination, ): Promise { throw new Error("Method not implemented."); } getNonFungibleTokensOfAccount( - _address: IAddress, + _address: Address, _pagination?: IPagination, ): Promise { throw new Error("Method not implemented."); } - getFungibleTokenOfAccount(_address: IAddress, _tokenIdentifier: string): Promise { + getFungibleTokenOfAccount(_address: Address, _tokenIdentifier: string): Promise { throw new Error("Method not implemented."); } getNonFungibleTokenOfAccount( - _address: IAddress, + _address: Address, _collection: string, _nonce: number, ): Promise { From 6689b5c90b48c7e61fc93f5a9fdb19b865ff360a Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 12 Dec 2024 14:31:31 +0200 Subject: [PATCH 087/214] Fix compile error --- src/proto/serializer.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/proto/serializer.ts b/src/proto/serializer.ts index 190905487..4988b362a 100644 --- a/src/proto/serializer.ts +++ b/src/proto/serializer.ts @@ -67,7 +67,7 @@ export class ProtoSerializer { return protoTransaction; } - private isRelayedTransaction(transaction: ITransaction) { + private isRelayedTransaction(transaction: Transaction) { return !transaction.relayer.isEmpty(); } From 418d023351750abb70b9c5ed02897e967ace6489 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 12 Dec 2024 16:18:03 +0200 Subject: [PATCH 088/214] Remove unused interfaces (INonce, IGasLimit, IGasPrice, ITransactionOptions, ITransactionVersion, ITransactionValue, ISignature, IAccountBalance --- src/abi/interaction.local.net.spec.ts | 20 +++++----- src/abi/interaction.spec.ts | 52 +++++++++++++------------- src/abi/interaction.ts | 34 ++++++++--------- src/abi/interface.ts | 3 +- src/abi/nativeSerializer.ts | 3 +- src/abi/query.ts | 7 ++-- src/abi/smartContract.spec.ts | 36 +++++++++--------- src/abi/smartContract.ts | 15 ++++---- src/accountManagement/resources.ts | 4 +- src/accounts/account.ts | 9 ++--- src/compatibility.ts | 3 +- src/entrypoints/entrypoints.spec.ts | 6 +-- src/entrypoints/entrypoints.ts | 2 +- src/interface.ts | 40 -------------------- src/interfaceOfNetwork.ts | 13 +++---- src/networkProviders/accounts.ts | 9 ++--- src/proto/serializer.spec.ts | 4 +- src/testutils/mockNetworkProvider.ts | 6 +-- src/testutils/utils.ts | 5 +-- src/testutils/wallets.ts | 3 +- src/transaction.spec.ts | 3 -- src/transaction.ts | 54 +++++++++++++-------------- src/utils.codec.ts | 3 +- 23 files changed, 139 insertions(+), 195 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index f306f2c8d..42b76d821 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -150,10 +150,10 @@ describe("test smart contract interactor", function () { let returnEgldInteraction = ( contract.methods .returns_egld_decimal([]) - .withGasLimit(10000000) + .withGasLimit(10000000n) .withChainID(network.ChainID) .withSender(alice.address) - .withValue(1) + .withValue(1n) ); // returnEgld() @@ -164,10 +164,10 @@ describe("test smart contract interactor", function () { let additionInteraction = contract.methods .managed_decimal_addition([new ManagedDecimalValue("2.5", 2), new ManagedDecimalValue("2.7", 2)]) - .withGasLimit(10000000) + .withGasLimit(10000000n) .withChainID(network.ChainID) .withSender(alice.address) - .withValue(0); + .withValue(0n); // addition() let additionTransaction = additionInteraction @@ -178,10 +178,10 @@ describe("test smart contract interactor", function () { // log let mdLnInteraction = contract.methods .managed_decimal_ln([new ManagedDecimalValue("23", 9)]) - .withGasLimit(10000000) + .withGasLimit(10000000n) .withChainID(network.ChainID) .withSender(alice.address) - .withValue(0); + .withValue(0n); // mdLn() let mdLnTransaction = mdLnInteraction @@ -194,10 +194,10 @@ describe("test smart contract interactor", function () { new ManagedDecimalValue("4", 2, true), new ManagedDecimalValue("5", 2, true), ]) - .withGasLimit(50000000) + .withGasLimit(50000000n) .withChainID(network.ChainID) .withSender(alice.address) - .withValue(0); + .withValue(0n); // addition() let additionVarTransaction = additionVarInteraction @@ -207,10 +207,10 @@ describe("test smart contract interactor", function () { let lnVarInteraction = contract.methods .managed_decimal_ln_var([new ManagedDecimalValue("23", 9, true)]) - .withGasLimit(50000000) + .withGasLimit(50000000n) .withChainID(network.ChainID) .withSender(alice.address) - .withValue(0); + .withValue(0n); // managed_decimal_ln_var() let lnVarTransaction = lnVarInteraction diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index db210faf9..d5edc5038 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -33,15 +33,15 @@ describe("test smart contract interactor", function () { let transaction = interaction .withSender(alice.address) - .withNonce(7) - .withValue(TokenTransfer.egldFromAmount(1)) - .withGasLimit(20000000) + .withNonce(7n) + .withValue(TokenTransfer.egldFromAmount(1).amount) + .withGasLimit(20000000n) .buildTransaction(); assert.deepEqual(transaction.getReceiver(), dummyAddress); assert.equal(transaction.getValue().toString(), "1000000000000000000"); - assert.equal(transaction.getNonce(), 7); - assert.equal(transaction.getGasLimit().valueOf(), 20000000); + assert.equal(transaction.getNonce(), 7n); + assert.equal(transaction.getGasLimit().valueOf(), 20000000n); }); it("should set transfers (payments) on contract calls (transfer and execute)", async function () { @@ -181,9 +181,9 @@ describe("test smart contract interactor", function () { .getUltimateAnswer() .withChainID("T") .withSender(alice) - .withGasLimit(543210) + .withGasLimit(543210n) .withSingleESDTTransfer(new TokenTransfer({ token, amount: 100n })) - .withNonce(42) + .withNonce(42n) .buildTransaction(); assert.deepEqual( @@ -208,12 +208,12 @@ describe("test smart contract interactor", function () { let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry }); - let interaction = contract.methods.getUltimateAnswer().withGasLimit(543210).withChainID("T"); + let interaction = contract.methods.getUltimateAnswer().withGasLimit(543210n).withChainID("T"); assert.equal(contract.getAddress(), dummyAddress); assert.deepEqual(interaction.getFunction(), new ContractFunction("getUltimateAnswer")); assert.lengthOf(interaction.getArguments(), 0); - assert.deepEqual(interaction.getGasLimit(), 543210); + assert.deepEqual(interaction.getGasLimit(), 543210n); provider.mockQueryContractOnFunction( "getUltimateAnswer", @@ -239,29 +239,29 @@ describe("test smart contract interactor", function () { assert.deepEqual(response[0], new BigNumber(42)); // Execute, do not wait for execution - let transaction = interaction.withSender(alice.address).withNonce(0).buildTransaction(); + let transaction = interaction.withSender(alice.address).withNonce(0n).buildTransaction(); transaction.setSender(alice.address); transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); await provider.sendTransaction(transaction); - assert.equal(transaction.getNonce().valueOf(), 0); + assert.equal(transaction.getNonce().valueOf(), 0n); assert.equal(transaction.getData().toString(), "getUltimateAnswer"); assert.equal( transaction.getHash().toString(), "3579ad09099feb9755c860ddd225251170806d833342e912fccdfe2ed5c3a364", ); - transaction = interaction.withNonce(1).buildTransaction(); + transaction = interaction.withNonce(1n).buildTransaction(); transaction.setSender(alice.address); transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); await provider.sendTransaction(transaction); - assert.equal(transaction.getNonce().valueOf(), 1); + assert.equal(transaction.getNonce(), 1n); assert.equal( transaction.getHash().toString(), "ad513ce7c5d371d30e48f073326899766736eac1ac231d847d45bc3facbcb496", ); // Execute, and wait for execution - transaction = interaction.withNonce(2).buildTransaction(); + transaction = interaction.withNonce(2n).buildTransaction(); transaction.setSender(alice.address); transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs", "getUltimateAnswer"); @@ -281,8 +281,8 @@ describe("test smart contract interactor", function () { let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abi }); let getInteraction = contract.methodsExplicit.get(); - let incrementInteraction = (contract.methods.increment()).withGasLimit(543210); - let decrementInteraction = (contract.methods.decrement()).withGasLimit(987654); + let incrementInteraction = (contract.methods.increment()).withGasLimit(543210n); + let decrementInteraction = (contract.methods.decrement()).withGasLimit(987654n); // For "get()", return fake 7 provider.mockQueryContractOnFunction( @@ -308,7 +308,7 @@ describe("test smart contract interactor", function () { let incrementTransaction = incrementInteraction .withSender(alice.address) - .withNonce(14) + .withNonce(14n) .withChainID("mock") .buildTransaction(); @@ -322,19 +322,19 @@ describe("test smart contract interactor", function () { // Decrement #1 let decrementTransaction = decrementInteraction .withSender(alice.address) - .withNonce(15) + .withNonce(15n) .withChainID("mock") .buildTransaction(); decrementTransaction.applySignature(await alice.signer.sign(decrementTransaction.serializeForSigning())); await provider.sendTransaction(decrementTransaction); // Decrement #2 - decrementTransaction = decrementInteraction.withNonce(16).buildTransaction(); + decrementTransaction = decrementInteraction.withNonce(16n).buildTransaction(); decrementTransaction.applySignature(await alice.signer.sign(decrementTransaction.serializeForSigning())); await provider.sendTransaction(decrementTransaction); // Decrement #3 - decrementTransaction = decrementInteraction.withNonce(17).buildTransaction(); + decrementTransaction = decrementInteraction.withNonce(17n).buildTransaction(); decrementTransaction.applySignature(await alice.signer.sign(decrementTransaction.serializeForSigning())); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@05", "decrement"); hash = await provider.sendTransaction(decrementTransaction); @@ -362,17 +362,17 @@ describe("test smart contract interactor", function () { OptionValue.newMissing(), OptionalValue.newMissing(), ]) - .withGasLimit(5000000) + .withGasLimit(5000000n) ); - let statusInteraction = contract.methods.status(["lucky"]).withGasLimit(5000000); + let statusInteraction = contract.methods.status(["lucky"]).withGasLimit(5000000n); - let getLotteryInfoInteraction = contract.methods.getLotteryInfo(["lucky"]).withGasLimit(5000000); + let getLotteryInfoInteraction = contract.methods.getLotteryInfo(["lucky"]).withGasLimit(5000000n); // start() let startTransaction = startInteraction .withSender(alice.address) - .withNonce(14) + .withNonce(14n) .withChainID("mock") .buildTransaction(); @@ -392,7 +392,7 @@ describe("test smart contract interactor", function () { // status() (this is a view function, but for the sake of the test, we'll execute it) let statusTransaction = statusInteraction .withSender(alice.address) - .withNonce(15) + .withNonce(15n) .withChainID("mock") .buildTransaction(); @@ -410,7 +410,7 @@ describe("test smart contract interactor", function () { // lotteryInfo() (this is a view function, but for the sake of the test, we'll execute it) let getLotteryInfoTransaction = getLotteryInfoInteraction .withSender(alice.address) - .withNonce(15) + .withNonce(15n) .withChainID("mock") .buildTransaction(); diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index 2726cb3c1..fa63b2a8f 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -2,7 +2,7 @@ import { Account } from "../accounts"; import { Address } from "../address"; import { Compatibility } from "../compatibility"; import { TRANSACTION_VERSION_DEFAULT } from "../constants"; -import { IAddress, IChainID, IGasLimit, IGasPrice, INonce, ITokenTransfer, ITransactionValue } from "../interface"; +import { ITokenTransfer } from "../interface"; import { SmartContractTransactionsFactory } from "../smartContracts"; import { TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; @@ -34,13 +34,13 @@ export class Interaction { private readonly function: ContractFunction; private readonly args: TypedValue[]; - private nonce: INonce = 0; - private value: ITransactionValue = "0"; - private gasLimit: IGasLimit = 0; - private gasPrice: IGasPrice | undefined = undefined; - private chainID: IChainID = ""; + private nonce: bigint = 0n; + private value: bigint = 0n; + private gasLimit: bigint = 0n; + private gasPrice: bigint | undefined = undefined; + private chainID: string = ""; private querent: Address = Address.empty(); - private explicitReceiver?: IAddress; + private explicitReceiver?: Address; private sender: Address = Address.empty(); private version: number = TRANSACTION_VERSION_DEFAULT; @@ -53,7 +53,7 @@ export class Interaction { this.tokenTransfers = []; } - getContractAddress(): IAddress { + getContractAddress(): Address { return this.contract.getAddress(); } @@ -69,7 +69,7 @@ export class Interaction { return this.args; } - getValue(): ITransactionValue { + getValue(): bigint { return this.value; } @@ -77,11 +77,11 @@ export class Interaction { return this.tokenTransfers; } - getGasLimit(): IGasLimit { + getGasLimit(): bigint { return this.gasLimit; } - getExplicitReceiver(): IAddress | undefined { + getExplicitReceiver(): Address | undefined { return this.explicitReceiver; } @@ -128,7 +128,7 @@ export class Interaction { }); } - withValue(value: ITransactionValue): Interaction { + withValue(value: bigint): Interaction { this.value = value; return this; } @@ -148,17 +148,17 @@ export class Interaction { return this; } - withGasLimit(gasLimit: IGasLimit): Interaction { + withGasLimit(gasLimit: bigint): Interaction { this.gasLimit = gasLimit; return this; } - withGasPrice(gasPrice: IGasPrice): Interaction { + withGasPrice(gasPrice: bigint): Interaction { this.gasPrice = gasPrice; return this; } - withNonce(nonce: INonce): Interaction { + withNonce(nonce: bigint): Interaction { this.nonce = nonce; return this; } @@ -167,7 +167,7 @@ export class Interaction { return this.withNonce(account.getNonceThenIncrement()); } - withChainID(chainID: IChainID): Interaction { + withChainID(chainID: string): Interaction { this.chainID = chainID; return this; } @@ -190,7 +190,7 @@ export class Interaction { return this; } - withExplicitReceiver(receiver: IAddress): Interaction { + withExplicitReceiver(receiver: Address): Interaction { this.explicitReceiver = receiver; return this; } diff --git a/src/abi/interface.ts b/src/abi/interface.ts index 9fc396566..0f2b54e5d 100644 --- a/src/abi/interface.ts +++ b/src/abi/interface.ts @@ -1,5 +1,4 @@ import { Address } from "../address"; -import { ITransactionValue } from "../interface"; import { Transaction } from "../transaction"; import { ReturnCode } from "./returnCode"; import { TypedValue } from "./typesystem"; @@ -65,7 +64,7 @@ export interface CallArguments { export interface QueryArguments { func: IContractFunction; args?: TypedValue[]; - value?: ITransactionValue; + value?: bigint; caller?: Address; } diff --git a/src/abi/nativeSerializer.ts b/src/abi/nativeSerializer.ts index 85ba5b7cb..0632d97a0 100644 --- a/src/abi/nativeSerializer.ts +++ b/src/abi/nativeSerializer.ts @@ -2,7 +2,6 @@ import BigNumber from "bignumber.js"; import { Address } from "../address"; import { ErrInvalidArgument } from "../errors"; -import { IAddress } from "../interface"; import { numberToPaddedHex } from "../utils.codec"; import { ArgumentErrorContext } from "./argumentErrorContext"; import { @@ -67,7 +66,7 @@ import { export namespace NativeTypes { export type NativeBuffer = Buffer | string; export type NativeBytes = Buffer | { valueOf(): Buffer } | string; - export type NativeAddress = string | Buffer | Address | { getAddress(): IAddress }; + export type NativeAddress = string | Buffer | Address | { getAddress(): Address }; export type NativeBigNumber = BigNumber.Value | bigint; } diff --git a/src/abi/query.ts b/src/abi/query.ts index f773f9f21..93e3e6091 100644 --- a/src/abi/query.ts +++ b/src/abi/query.ts @@ -1,5 +1,4 @@ import { Address } from "../address"; -import { ITransactionValue } from "../interface"; import { ArgSerializer } from "./argSerializer"; import { IContractFunction } from "./interface"; import { TypedValue } from "./typesystem"; @@ -9,20 +8,20 @@ export class Query { address: Address; func: IContractFunction; args: TypedValue[]; - value: ITransactionValue; + value: bigint; constructor(obj: { caller?: Address; address: Address; func: IContractFunction; args?: TypedValue[]; - value?: ITransactionValue; + value?: bigint; }) { this.caller = obj.caller || Address.empty(); this.address = obj.address; this.func = obj.func; this.args = obj.args || []; - this.value = obj.value || 0; + this.value = obj.value || 0n; } getEncodedArguments(): string[] { diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index cc4944511..4dc5dd0ec 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -28,10 +28,10 @@ describe("test contract", () => { it("should compute contract address", async () => { let owner = new Address("93ee6143cdc10ce79f15b2a6c2ad38e9b6021c72a1779051f47154fd54cfbd5e"); - let firstContractAddress = SmartContract.computeAddress(owner, 0); + let firstContractAddress = SmartContract.computeAddress(owner, 0n); assert.equal(firstContractAddress.toBech32(), "erd1qqqqqqqqqqqqqpgqhdjjyq8dr7v5yq9tv6v5vt9tfvd00vg7h40q6779zn"); - let secondContractAddress = SmartContract.computeAddress(owner, 1); + let secondContractAddress = SmartContract.computeAddress(owner, 1n); assert.equal( secondContractAddress.toBech32(), "erd1qqqqqqqqqqqqqpgqde8eqjywyu6zlxjxuxqfg5kgtmn3setxh40qen8egy", @@ -51,18 +51,18 @@ describe("test contract", () => { }); provider.mockUpdateAccount(alice.address, (account) => { - account.nonce = 42; + account.nonce = 42n; }); await alice.sync(provider); - deployTransaction.setNonce(alice.account.nonce); + deployTransaction.nonce = alice.account.nonce; assert.equal(deployTransaction.getData().valueOf().toString(), "01020304@0500@0100"); - assert.equal(deployTransaction.getGasLimit().valueOf(), 1000000); - assert.equal(deployTransaction.getNonce().valueOf(), 42); + assert.equal(deployTransaction.gasLimit, 1000000n); + assert.equal(deployTransaction.nonce, 42n); // Compute & set the contract address - contract.setAddress(SmartContract.computeAddress(alice.address, 42)); + contract.setAddress(SmartContract.computeAddress(alice.address, 42n)); assert.equal( contract.getAddress().toBech32(), "erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q", @@ -97,7 +97,7 @@ describe("test contract", () => { }); provider.mockUpdateAccount(alice.address, (account) => { - account.nonce = 42; + account.nonce = 42n; }); let callTransactionOne = contract.call({ @@ -117,16 +117,16 @@ describe("test contract", () => { }); await alice.sync(provider); - callTransactionOne.setNonce(alice.account.nonce); + callTransactionOne.nonce = alice.account.nonce; alice.account.incrementNonce(); - callTransactionTwo.setNonce(alice.account.nonce); + callTransactionTwo.nonce = alice.account.nonce; - assert.equal(callTransactionOne.getNonce().valueOf(), 42); + assert.equal(callTransactionOne.nonce, 42n); assert.equal(callTransactionOne.getData().valueOf().toString(), "helloEarth@05@0123"); - assert.equal(callTransactionOne.getGasLimit().valueOf(), 150000); - assert.equal(callTransactionTwo.getNonce().valueOf(), 43); + assert.equal(callTransactionOne.gasLimit, 150000n); + assert.equal(callTransactionTwo.nonce, 43n); assert.equal(callTransactionTwo.getData().valueOf().toString(), "helloMars@05@0123"); - assert.equal(callTransactionTwo.getGasLimit().valueOf(), 1500000); + assert.equal(callTransactionTwo.gasLimit, 1500000n); // Sign transactions, broadcast them callTransactionOne.applySignature(await alice.signer.sign(callTransactionOne.serializeForSigning())); @@ -173,15 +173,15 @@ describe("test contract", () => { }); provider.mockUpdateAccount(alice.address, (account) => { - account.nonce = 42; + account.nonce = 42n; }); await alice.sync(provider); - deployTransaction.setNonce(alice.account.nonce); + deployTransaction.nonce = alice.account.nonce; assert.equal(deployTransaction.getData().valueOf().toString(), "upgradeContract@01020304@0100"); - assert.equal(deployTransaction.getGasLimit().valueOf(), 1000000); - assert.equal(deployTransaction.getNonce().valueOf(), 42); + assert.equal(deployTransaction.gasLimit, 1000000n); + assert.equal(deployTransaction.nonce, 42n); // Sign the transaction deployTransaction.applySignature(await alice.signer.sign(deployTransaction.serializeForSigning())); diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index b8fb5fe75..2814336cb 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -2,7 +2,6 @@ import { Address, AddressComputer } from "../address"; import { Compatibility } from "../compatibility"; import { TRANSACTION_MIN_GAS_PRICE } from "../constants"; import { ErrContractHasNoAddress } from "../errors"; -import { INonce } from "../interface"; import { Transaction } from "../transaction"; import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { guardValueIsSet } from "../utils"; @@ -151,9 +150,9 @@ export class SmartContract implements ISmartContract { isPayableBySmartContract: metadataAsJson.payableBySc, }); - transaction.setChainID(chainID); - transaction.setValue(value ?? 0); - transaction.setGasPrice(gasPrice ?? TRANSACTION_MIN_GAS_PRICE); + transaction.chainID = chainID; + transaction.value = value ?? 0n; + transaction.gasPrice = gasPrice ?? BigInt(TRANSACTION_MIN_GAS_PRICE); return transaction; } @@ -222,8 +221,8 @@ export class SmartContract implements ISmartContract { }); transaction.setChainID(chainID); - transaction.setValue(value ?? 0); - transaction.setGasPrice(gasPrice ?? TRANSACTION_MIN_GAS_PRICE); + transaction.value = value ?? 0n; + transaction.gasPrice = gasPrice ?? BigInt(TRANSACTION_MIN_GAS_PRICE); return transaction; } @@ -258,7 +257,7 @@ export class SmartContract implements ISmartContract { transaction.setChainID(chainID); transaction.setValue(value); - transaction.setGasPrice(gasPrice ?? TRANSACTION_MIN_GAS_PRICE); + transaction.gasPrice = gasPrice ?? BigInt(TRANSACTION_MIN_GAS_PRICE); return transaction; } @@ -288,7 +287,7 @@ export class SmartContract implements ISmartContract { * @param owner The owner of the Smart Contract * @param nonce The owner nonce used for the deployment transaction */ - static computeAddress(owner: Address, nonce: INonce): Address { + static computeAddress(owner: Address, nonce: bigint): Address { const deployer = Address.fromBech32(owner.toBech32()); const addressComputer = new AddressComputer(); return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); diff --git a/src/accountManagement/resources.ts b/src/accountManagement/resources.ts index aae540e73..26d10786d 100644 --- a/src/accountManagement/resources.ts +++ b/src/accountManagement/resources.ts @@ -1,4 +1,4 @@ -import { IAddress } from "../interface"; +import { Address } from "../address"; -export type SetGuardianInput = { guardianAddress: IAddress; serviceID: string }; +export type SetGuardianInput = { guardianAddress: Address; serviceID: string }; export type SaveKeyValueInput = { keyValuePairs: Map }; diff --git a/src/accounts/account.ts b/src/accounts/account.ts index 4f6060a32..5eea33794 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -1,6 +1,5 @@ import { Address } from "../address"; import { LibraryConfig } from "../config"; -import { INonce } from "../interface"; import { Mnemonic, UserSigner, UserWallet } from "../wallet"; import { IAccount } from "./interfaces"; @@ -16,7 +15,7 @@ export class Account implements IAccount { /** * The nonce of the account (the account sequence number). */ - nonce: INonce = 0; + nonce: bigint = 0n; /** * The signer of the account. @@ -35,15 +34,15 @@ export class Account implements IAccount { * Increments (locally) the nonce (the account sequence number). */ incrementNonce() { - this.nonce = this.nonce.valueOf() + 1; + this.nonce = this.nonce + 1n; } /** * Gets then increments (locally) the nonce (the account sequence number). */ - getNonceThenIncrement(): INonce { + getNonceThenIncrement(): bigint { let nonce = this.nonce; - this.nonce = this.nonce.valueOf() + 1; + this.nonce = this.nonce + 1n; return nonce; } diff --git a/src/compatibility.ts b/src/compatibility.ts index 7fb18b5a8..357b724a8 100644 --- a/src/compatibility.ts +++ b/src/compatibility.ts @@ -1,5 +1,4 @@ import { Address } from "./address"; -import { IAddress } from "./interface"; /** * For internal use only. @@ -8,7 +7,7 @@ export class Compatibility { /** * For internal use only. */ - static guardAddressIsSetAndNonZero(address: IAddress | undefined, context: string, resolution: string) { + static guardAddressIsSetAndNonZero(address: Address | undefined, context: string, resolution: string) { 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.`, diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index e2173e05f..f26e423e3 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -21,7 +21,7 @@ describe("TestEntrypoint", () => { it("native transfer", async () => { const controller = entrypoint.createTransfersController(); const sender = Account.newFromPem(alicePem.pemFileText); - sender.nonce = 77777; + sender.nonce = 77777n; const transaction = await controller.createTransactionForTransfer( sender, @@ -87,10 +87,10 @@ describe("TestEntrypoint", () => { it("create relayed transaction", async function () { const transferController = entrypoint.createTransfersController(); const sender = Account.newFromPem(alicePem.pemFileText); - sender.nonce = 77777; + sender.nonce = 77777n; const relayer = Account.newFromPem(bobPem.pemFileText); - relayer.nonce = 7; + relayer.nonce = 7n; const transaction = await transferController.createTransactionForTransfer( sender, diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 7ee11e047..45b4a2cb2 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -64,7 +64,7 @@ class NetworkEntrypoint { return verifier.verify(messageComputer.computeBytesForVerifying(message), message.signature); } - async recallAccountNonce(address: Address): Promise { + async recallAccountNonce(address: Address): Promise { return (await this.networkProvider.getAccount(address)).nonce; } diff --git a/src/interface.ts b/src/interface.ts index 545160b5c..95252daac 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -28,46 +28,6 @@ export interface IPlainTransactionObject { relayerSignature?: string; } -export interface ISignature { - hex(): string; -} - -export interface IAddress { - bech32(): string; -} - -export interface ITransactionValue { - toString(): string; -} - -export interface IAccountBalance { - toString(): string; -} - -export interface INonce { - valueOf(): number; -} - -export interface IChainID { - valueOf(): string; -} - -export interface IGasLimit { - valueOf(): number; -} - -export interface IGasPrice { - valueOf(): number; -} - -export interface ITransactionVersion { - valueOf(): number; -} - -export interface ITransactionOptions { - valueOf(): number; -} - export interface ITransactionPayload { length(): number; encoded(): string; diff --git a/src/interfaceOfNetwork.ts b/src/interfaceOfNetwork.ts index 8d5303773..e3a4e7e59 100644 --- a/src/interfaceOfNetwork.ts +++ b/src/interfaceOfNetwork.ts @@ -1,9 +1,8 @@ import { Address } from "./address"; -import { IAccountBalance, IAddress } from "./interface"; export interface IAccountOnNetwork { - nonce: number; - balance: IAccountBalance; + nonce: bigint; + balance: bigint; } export interface INetworkConfig { @@ -19,8 +18,8 @@ export interface ITransactionOnNetwork { hash: string; type: string; value: string; - receiver: IAddress; - sender: IAddress; + receiver: Address; + sender: Address; function?: string; data: Buffer; status: ITransactionStatus; @@ -49,8 +48,8 @@ export interface IContractResults { export interface IContractResultItem { hash: string; nonce: number; - receiver: IAddress; - sender: IAddress; + receiver: Address; + sender: Address; data: string; returnMessage: string; logs: ITransactionLogs; diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index 673487e07..086885d89 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -1,4 +1,3 @@ -import BigNumber from "bignumber.js"; import { Address } from "../address"; /** @@ -6,8 +5,8 @@ import { Address } from "../address"; */ export class AccountOnNetwork { address: Address = Address.empty(); - nonce: number = 0; - balance: BigNumber = new BigNumber(0); + nonce: bigint = 0n; + balance: bigint = 0n; code: string = ""; userName: string = ""; @@ -19,8 +18,8 @@ export class AccountOnNetwork { let result = new AccountOnNetwork(); result.address = new Address(payload["address"] || ""); - result.nonce = Number(payload["nonce"] || 0); - result.balance = new BigNumber(payload["balance"] || 0); + result.nonce = BigInt(payload["nonce"] || 0); + result.balance = BigInt(payload["balance"] || 0); result.code = payload["code"] || ""; result.userName = payload["username"] || ""; diff --git a/src/proto/serializer.spec.ts b/src/proto/serializer.spec.ts index 9a6b693e6..dd7e70687 100644 --- a/src/proto/serializer.spec.ts +++ b/src/proto/serializer.spec.ts @@ -1,6 +1,5 @@ import { assert } from "chai"; import { Address } from "../address"; -import { Signature } from "../signature"; import { loadTestWallets, TestWallet } from "../testutils"; import { TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; @@ -110,8 +109,9 @@ describe("serialize transactions", () => { }); transaction.applySignature( - new Signature( + Buffer.from( "dfa3e9f2fdec60dcb353bac3b3435b4a2ff251e7e98eaf8620f46c731fc70c8ba5615fd4e208b05e75fe0f7dc44b7a99567e29f94fcd91efac7e67b182cd2a04", + "hex", ), ); diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 6d61df274..ea560da96 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -40,18 +40,18 @@ export class MockNetworkProvider implements INetworkProvider { this.accounts.set( MockNetworkProvider.AddressOfAlice.toBech32(), new AccountOnNetwork({ - nonce: 0, + nonce: 0n, balance: createAccountBalance(1000), }), ); this.accounts.set( MockNetworkProvider.AddressOfBob.toBech32(), - new AccountOnNetwork({ nonce: 5, balance: createAccountBalance(500) }), + new AccountOnNetwork({ nonce: 5n, balance: createAccountBalance(500) }), ); this.accounts.set( MockNetworkProvider.AddressOfCarol.toBech32(), new AccountOnNetwork({ - nonce: 42, + nonce: 42n, balance: createAccountBalance(300), }), ); diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index 636c107ad..1ba118c9b 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -1,4 +1,3 @@ -import BigNumber from "bignumber.js"; import * as fs from "fs"; import { PathLike } from "fs"; import { AbiRegistry, Code, SmartContract, TypedValue } from "../abi"; @@ -86,8 +85,8 @@ export function setupUnitTestWatcherTimeouts() { TransactionWatcher.DefaultTimeout = 42 * 42; } -export function createAccountBalance(egld: number): BigNumber { - return new BigNumber(egld.toString() + "0".repeat(18)); +export function createAccountBalance(egld: number): bigint { + return BigInt(egld.toString() + "0".repeat(18)); } export function b64TopicsToBytes(topics: string[]): Uint8Array[] { diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index b66314447..628e53d1e 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -2,7 +2,6 @@ import * as fs from "fs"; import * as path from "path"; import { Account } from "../accounts"; import { Address } from "../address"; -import { IAddress } from "../interface"; import { IAccountOnNetwork } from "../interfaceOfNetwork"; import { getAxios } from "../utils"; import { UserSecretKey, UserSigner } from "./../wallet"; @@ -12,7 +11,7 @@ import { isOnBrowserTests } from "./utils"; export const DummyMnemonicOf12Words = "matter trumpet twenty parade fame north lift sail valve salon foster cinnamon"; interface IAccountFetcher { - getAccount(address: IAddress): Promise; + getAccount(address: Address): Promise; } export async function loadAndSyncTestWallets(provider: IAccountFetcher): Promise> { diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index f128b4b15..745ed11ac 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -503,9 +503,6 @@ describe("test transaction", async () => { assert.equal(tx2.getValue().toString(), "123456789000000000000000000000"); const tx3 = new Transaction({ - // Passing a BigNumber is not recommended. - // However, ITransactionValue interface is permissive, and developers may mistakenly pass such objects as values. - // TokenTransfer objects or simple strings (see above) are preferred, instead. value: BigInt("123456789000000000000000000000"), sender: wallets.alice.address, receiver: wallets.bob.address, diff --git a/src/transaction.ts b/src/transaction.ts index 3f61a40ed..53ca342fe 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -2,7 +2,7 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; import { Hash } from "./hash"; -import { IGasLimit, IGasPrice, INonce, IPlainTransactionObject, ISignature, ITransactionValue } from "./interface"; +import { IPlainTransactionObject } from "./interface"; import { INetworkConfig } from "./interfaceOfNetwork"; import { interpretSignatureAsBuffer } from "./signature"; import { TransactionComputer } from "./transactionComputer"; @@ -119,20 +119,18 @@ export class Transaction { guardianSignature?: Uint8Array; relayerSignature?: Uint8Array; }) { - this.nonce = BigInt(options.nonce?.valueOf() || 0n); - // We still rely on "bigNumber" for value, because client code might be passing a BigNumber object as a legacy "ITransactionValue", - // and we want to keep compatibility. - this.value = options.value ? BigInt(new BigNumber(options.value.toString()).toFixed(0)) : 0n; + this.nonce = options.nonce ?? 0n; + this.value = options.value ?? 0n; this.sender = options.sender; this.receiver = options.receiver; this.senderUsername = options.senderUsername || ""; this.receiverUsername = options.receiverUsername || ""; - this.gasPrice = BigInt(options.gasPrice?.valueOf() || TRANSACTION_MIN_GAS_PRICE); - this.gasLimit = BigInt(options.gasLimit.valueOf()); - this.data = options.data?.valueOf() || new Uint8Array(); + this.gasPrice = options.gasPrice ?? BigInt(TRANSACTION_MIN_GAS_PRICE); + this.gasLimit = options.gasLimit; + this.data = options.data ?? new Uint8Array(); this.chainID = options.chainID.valueOf(); - this.version = Number(options.version?.valueOf() || TRANSACTION_VERSION_DEFAULT); - this.options = Number(options.options?.valueOf() || TRANSACTION_OPTIONS_DEFAULT); + this.version = options.version ?? TRANSACTION_VERSION_DEFAULT; + this.options = options.options ?? TRANSACTION_OPTIONS_DEFAULT; this.guardian = options.guardian ?? Address.empty(); this.relayer = options.relayer ? options.relayer : Address.empty(); @@ -144,30 +142,30 @@ export class Transaction { /** * Legacy method, use the "nonce" property instead. */ - getNonce(): INonce { - return Number(this.nonce); + getNonce(): bigint { + return this.nonce; } /** * Legacy method, use the "nonce" property instead. * Sets the account sequence number of the sender. Must be done prior signing. */ - setNonce(nonce: INonce | bigint) { - this.nonce = BigInt(nonce.valueOf()); + setNonce(nonce: bigint) { + this.nonce = nonce; } /** * Legacy method, use the "value" property instead. */ - getValue(): ITransactionValue { + getValue(): bigint { return this.value; } /** * Legacy method, use the "value" property instead. */ - setValue(value: ITransactionValue | bigint) { - this.value = BigInt(value.toString()); + setValue(value: bigint) { + this.value = value; } /** @@ -229,29 +227,29 @@ export class Transaction { /** * Legacy method, use the "gasPrice" property instead. */ - getGasPrice(): IGasPrice { - return Number(this.gasPrice); + getGasPrice(): bigint { + return this.gasPrice; } /** * Legacy method, use the "gasPrice" property instead. */ - setGasPrice(gasPrice: IGasPrice | bigint) { - this.gasPrice = BigInt(gasPrice.valueOf()); + setGasPrice(gasPrice: bigint) { + this.gasPrice = gasPrice; } /** * Legacy method, use the "gasLimit" property instead. */ - getGasLimit(): IGasLimit { - return Number(this.gasLimit); + getGasLimit(): bigint { + return this.gasLimit; } /** * Legacy method, use the "gasLimit" property instead. */ - setGasLimit(gasLimit: IGasLimit | bigint) { - this.gasLimit = BigInt(gasLimit.valueOf()); + setGasLimit(gasLimit: bigint) { + this.gasLimit = gasLimit; } /** @@ -412,7 +410,7 @@ export class Transaction { data: Buffer.from(object.data || "", "base64"), chainID: String(object.chainID), version: Number(object.version), - options: Number(object.options), + options: object.options ? Number(object.options) : undefined, signature: Buffer.from(object.signature || "", "hex"), guardianSignature: Buffer.from(object.guardianSignature || "", "hex"), relayerSignature: Buffer.from(object.relayerSignature || "", "hex"), @@ -427,7 +425,7 @@ export class Transaction { * * @param signature The signature, as computed by a signer. */ - applySignature(signature: ISignature | Uint8Array) { + applySignature(signature: Uint8Array) { this.signature = interpretSignatureAsBuffer(signature); } @@ -437,7 +435,7 @@ export class Transaction { * * @param guardianSignature The signature, as computed by a signer. */ - applyGuardianSignature(guardianSignature: ISignature | Uint8Array) { + applyGuardianSignature(guardianSignature: Uint8Array) { this.guardianSignature = interpretSignatureAsBuffer(guardianSignature); } diff --git a/src/utils.codec.ts b/src/utils.codec.ts index 4f70e93c8..ab64eed86 100644 --- a/src/utils.codec.ts +++ b/src/utils.codec.ts @@ -1,7 +1,6 @@ import BigNumber from "bignumber.js"; import * as contractsCodecUtils from "./abi/codec/utils"; import { Address } from "./address"; -import { IAddress } from "./interface"; export function numberToPaddedHex(value: bigint | number | BigNumber.Value) { let hexableNumber: { toString(radix?: number): string }; @@ -54,7 +53,7 @@ export function bigIntToHex(value: BigNumber.Value): string { return contractsCodecUtils.getHexMagnitudeOfBigInt(value); } -export function addressToHex(address: IAddress): string { +export function addressToHex(address: Address): string { const buffer = Address.fromBech32(address.toString()).pubkey(); return buffer.toString("hex"); } From 2ce19d5e26ac1ba8de1c63d3494e4e7400f4a146 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 16 Dec 2024 16:04:30 +0200 Subject: [PATCH 089/214] Remove ITokenTransfer and ITransactionPayload --- src/abi/interaction.ts | 9 ++++----- src/address.ts | 9 ++------- src/interface.ts | 18 ------------------ src/testutils/dummyQuery.ts | 5 ++--- src/transactionBuilder.ts | 10 ++++------ src/transfers/transferTransactionsFactory.ts | 7 +++---- 6 files changed, 15 insertions(+), 43 deletions(-) diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index fa63b2a8f..4f33f3632 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -2,7 +2,6 @@ import { Account } from "../accounts"; import { Address } from "../address"; import { Compatibility } from "../compatibility"; import { TRANSACTION_VERSION_DEFAULT } from "../constants"; -import { ITokenTransfer } from "../interface"; import { SmartContractTransactionsFactory } from "../smartContracts"; import { TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; @@ -73,7 +72,7 @@ export class Interaction { return this.value; } - getTokenTransfers(): ITokenTransfer[] { + getTokenTransfers(): TokenTransfer[] { return this.tokenTransfers; } @@ -133,17 +132,17 @@ export class Interaction { return this; } - withSingleESDTTransfer(transfer: ITokenTransfer): Interaction { + withSingleESDTTransfer(transfer: TokenTransfer): Interaction { this.tokenTransfers = [transfer].map((transfer) => new TokenTransfer(transfer)); return this; } - withSingleESDTNFTTransfer(transfer: ITokenTransfer): Interaction { + withSingleESDTNFTTransfer(transfer: TokenTransfer): Interaction { this.tokenTransfers = [transfer].map((transfer) => new TokenTransfer(transfer)); return this; } - withMultiESDTNFTTransfer(transfers: ITokenTransfer[]): Interaction { + withMultiESDTNFTTransfer(transfers: TokenTransfer[]): Interaction { this.tokenTransfers = transfers.map((transfer) => new TokenTransfer(transfer)); return this; } diff --git a/src/address.ts b/src/address.ts index ec5fae2f7..04686e774 100644 --- a/src/address.ts +++ b/src/address.ts @@ -13,11 +13,6 @@ const PUBKEY_LENGTH = 32; const SMART_CONTRACT_HEX_PUBKEY_PREFIX = "0".repeat(16); -interface IAddress { - getPublicKey(): Buffer; - getHrp(): string; -} - /** * An Address, as an immutable object. */ @@ -275,7 +270,7 @@ export class AddressComputer { this.numberOfShardsWithoutMeta = numberOfShardsWithoutMeta || CURRENT_NUMBER_OF_SHARDS_WITHOUT_META; } - computeContractAddress(deployer: IAddress, deploymentNonce: bigint): Address { + computeContractAddress(deployer: Address, deploymentNonce: bigint): Address { const initialPadding = Buffer.alloc(8, 0); const ownerPubkey = deployer.getPublicKey(); const shardSelector = ownerPubkey.slice(30); @@ -293,7 +288,7 @@ export class AddressComputer { return new Address(addressBytes); } - getShardOfAddress(address: IAddress): number { + getShardOfAddress(address: Address): number { return this.getShardOfPubkey(address.getPublicKey(), this.numberOfShardsWithoutMeta); } diff --git a/src/interface.ts b/src/interface.ts index 95252daac..d867b4629 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -1,4 +1,3 @@ -import BigNumber from "bignumber.js"; import { TransactionOnNetwork } from "./transactionOnNetwork"; export interface ITransactionFetcher { @@ -27,20 +26,3 @@ export interface IPlainTransactionObject { guardianSignature?: string; relayerSignature?: string; } - -export interface ITransactionPayload { - length(): number; - encoded(): string; - toString(): string; - valueOf(): Buffer; -} - -/** - * Legacy interface. The class `TokenTransfer` can be used instead, where necessary. - */ -export interface ITokenTransfer { - readonly tokenIdentifier: string; - readonly nonce: number; - readonly amountAsBigInteger: BigNumber.Value; - valueOf(): BigNumber.Value; -} diff --git a/src/testutils/dummyQuery.ts b/src/testutils/dummyQuery.ts index 076369df3..5be41fe69 100644 --- a/src/testutils/dummyQuery.ts +++ b/src/testutils/dummyQuery.ts @@ -1,10 +1,9 @@ import { Address } from "../address"; -import { IAddress } from "../interface"; import { IContractQuery } from "../networkProviders/interface"; export class MockQuery implements IContractQuery { - caller: IAddress = Address.empty(); - address: IAddress = Address.empty(); + caller = Address.empty(); + address = Address.empty(); func: string = ""; args: string[] = []; value: string = ""; diff --git a/src/transactionBuilder.ts b/src/transactionBuilder.ts index 2ef3b64b5..d7e46d4bc 100644 --- a/src/transactionBuilder.ts +++ b/src/transactionBuilder.ts @@ -1,8 +1,6 @@ import { Address } from "./address"; import { ARGUMENTS_SEPARATOR } from "./constants"; -import { ITransactionPayload } from "./interface"; import { Transaction } from "./transaction"; -import { TransactionPayload } from "./transactionPayload"; interface Config { chainID: string; @@ -40,19 +38,19 @@ export class TransactionBuilder { this.amount = options.amount; } - private computeGasLimit(payload: ITransactionPayload): bigint { + private computeGasLimit(payload: Uint8Array): bigint { if (!this.addDataMovementGas) { return this.providedGasLimit; } - const dataMovementGas = this.config.minGasLimit + this.config.gasLimitPerByte * BigInt(payload.length()); + const dataMovementGas = this.config.minGasLimit + this.config.gasLimitPerByte * BigInt(payload.length); const gasLimit = dataMovementGas + this.providedGasLimit; return gasLimit; } - private buildTransactionPayload(): TransactionPayload { + private buildTransactionPayload(): Uint8Array { const data = this.dataParts.join(ARGUMENTS_SEPARATOR); - return new TransactionPayload(data); + return Buffer.from(data); } build(): Transaction { diff --git a/src/transfers/transferTransactionsFactory.ts b/src/transfers/transferTransactionsFactory.ts index b2b69fd52..45b4fc739 100644 --- a/src/transfers/transferTransactionsFactory.ts +++ b/src/transfers/transferTransactionsFactory.ts @@ -2,7 +2,6 @@ import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, TypedValue, U16V import { Address } from "../address"; import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../constants"; import { Err, ErrBadUsage } from "../errors"; -import { ITokenTransfer } from "../interface"; import { TokenComputer, TokenTransfer } from "../tokens"; import { TokenTransfersDataBuilder } from "../tokenTransfersDataBuilder"; import { Transaction } from "../transaction"; @@ -184,7 +183,7 @@ export class TransferTransactionsFactory { * Use {@link createTransactionForESDTTokenTransfer} instead. */ createESDTTransfer(args: { - tokenTransfer: ITokenTransfer; + tokenTransfer: TokenTransfer; nonce?: bigint; receiver: Address; sender: Address; @@ -226,7 +225,7 @@ export class TransferTransactionsFactory { * Use {@link createTransactionForESDTTokenTransfer} instead. */ createESDTNFTTransfer(args: { - tokenTransfer: ITokenTransfer; + tokenTransfer: TokenTransfer; nonce?: bigint; destination: Address; sender: Address; @@ -272,7 +271,7 @@ export class TransferTransactionsFactory { * Use {@link createTransactionForESDTTokenTransfer} instead. */ createMultiESDTNFTTransfer(args: { - tokenTransfers: ITokenTransfer[]; + tokenTransfers: TokenTransfer[]; nonce?: bigint; destination: Address; sender: Address; From eaab21aca03a4ebacb2736535e1a005cc1228eca Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 17 Dec 2024 14:58:29 +0200 Subject: [PATCH 090/214] Update token transfer to follow specs --- src/abi/interaction.spec.ts | 24 ++++--- src/proto/serializer.spec.ts | 2 +- .../smartContractTransactionsFactory.ts | 2 +- src/tokens.spec.ts | 67 ++++--------------- src/tokens.ts | 26 +++---- src/transaction.local.net.spec.ts | 25 ++++--- src/transfers/transferTransactionsFactory.ts | 18 ++--- 7 files changed, 70 insertions(+), 94 deletions(-) diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index d5edc5038..61b643255 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -34,7 +34,7 @@ describe("test smart contract interactor", function () { let transaction = interaction .withSender(alice.address) .withNonce(7n) - .withValue(TokenTransfer.egldFromAmount(1).amount) + .withValue(TokenTransfer.newFromNativeAmount(1000000000000000000n).amount) .withGasLimit(20000000n) .buildTransaction(); @@ -49,11 +49,17 @@ describe("test smart contract interactor", function () { let dummyFunction = new ContractFunction("dummy"); let alice = new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const TokenFoo = (amount: BigNumber.Value) => TokenTransfer.fungibleFromAmount("FOO-6ce17b", amount, 0); - const TokenBar = (amount: BigNumber.Value) => TokenTransfer.fungibleFromAmount("BAR-5bc08f", amount, 3); + const TokenFoo = (amount: BigNumber.Value) => + new TokenTransfer({ token: new Token({ identifier: "FOO-6ce17b" }), amount: BigInt(amount.toString()) }); + const TokenBar = (amount: BigNumber.Value) => + new TokenTransfer({ token: new Token({ identifier: "BAR-5bc08f" }), amount: BigInt(amount.toString()) }); const LKMEX = (nonce: number, amount: BigNumber.Value) => - TokenTransfer.metaEsdtFromAmount("LKMEX-aab910", nonce, amount, 18); - const nonFungibleToken = (nonce: number) => TokenTransfer.nonFungible("MOS-b9b4b2", nonce); + new TokenTransfer({ + token: new Token({ identifier: "LKMEX-aab910", nonce: BigInt(nonce) }), + amount: BigInt(amount.toString()), + }); + const nonFungibleToken = (nonce: number) => + new TokenTransfer({ token: new Token({ identifier: "MOS-b9b4b2", nonce: BigInt(nonce) }), amount: 1n }); const hexFoo = "464f4f2d366365313762"; const hexBar = "4241522d356263303866"; @@ -73,7 +79,7 @@ describe("test smart contract interactor", function () { // Meta ESDT (special SFT), single transaction = new Interaction(contract, dummyFunction, []) .withSender(alice) - .withSingleESDTNFTTransfer(LKMEX(123456, 123.456)) + .withSingleESDTNFTTransfer(LKMEX(123456, "123456000000000000000")) .buildTransaction(); assert.equal(transaction.getSender().toBech32(), alice.toBech32()); @@ -85,7 +91,7 @@ describe("test smart contract interactor", function () { // Meta ESDT (special SFT), single, but using "withSender()" (recommended) transaction = new Interaction(contract, dummyFunction, []) - .withSingleESDTNFTTransfer(LKMEX(123456, 123.456)) + .withSingleESDTNFTTransfer(LKMEX(123456, 123456000000000000000)) .withSender(alice) .buildTransaction(); @@ -125,7 +131,7 @@ describe("test smart contract interactor", function () { // ESDT, multiple transaction = new Interaction(contract, dummyFunction, []) .withSender(alice) - .withMultiESDTNFTTransfer([TokenFoo(3), TokenBar(3.14)]) + .withMultiESDTNFTTransfer([TokenFoo(3), TokenBar(3140)]) .buildTransaction(); assert.equal(transaction.getSender().toBech32(), alice.toBech32()); @@ -137,7 +143,7 @@ describe("test smart contract interactor", function () { // ESDT, multiple, but using "withSender()" (recommended) transaction = new Interaction(contract, dummyFunction, []) - .withMultiESDTNFTTransfer([TokenFoo(3), TokenBar(3.14)]) + .withMultiESDTNFTTransfer([TokenFoo(3), TokenBar(3140)]) .withSender(alice) .buildTransaction(); diff --git a/src/proto/serializer.spec.ts b/src/proto/serializer.spec.ts index dd7e70687..142a6570f 100644 --- a/src/proto/serializer.spec.ts +++ b/src/proto/serializer.spec.ts @@ -57,7 +57,7 @@ describe("serialize transactions", () => { it("with data, with value", async () => { let transaction = new Transaction({ nonce: 91n, - value: TokenTransfer.egldFromAmount(10).amount, + value: TokenTransfer.newFromNativeAmount(10000000000000000000n).amount, sender: wallets.alice.address, receiver: wallets.bob.address, gasLimit: 100000n, diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index dd0cb2617..e77ba6e9c 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -78,7 +78,7 @@ export class SmartContractTransactionsFactory { let numberOfTokens = tokenTransfers.length; if (nativeTransferAmount && numberOfTokens) { - tokenTransfers.push(TokenTransfer.newFromEgldAmount(nativeTransferAmount)); + tokenTransfers.push(TokenTransfer.newFromNativeAmount(nativeTransferAmount)); nativeTransferAmount = 0n; numberOfTokens++; } diff --git a/src/tokens.spec.ts b/src/tokens.spec.ts index e9a29ef54..88d8f65dd 100644 --- a/src/tokens.spec.ts +++ b/src/tokens.spec.ts @@ -58,70 +58,31 @@ describe("test tokens and token computer", async () => { }); describe("test token transfer (legacy)", () => { - it("should work with EGLD", () => { - assert.equal(TokenTransfer.egldFromAmount("1").toString(), "1000000000000000000"); - assert.equal(TokenTransfer.egldFromAmount("10").toString(), "10000000000000000000"); - assert.equal(TokenTransfer.egldFromAmount("100").toString(), "100000000000000000000"); - assert.equal(TokenTransfer.egldFromAmount("1000").toString(), "1000000000000000000000"); - assert.equal(TokenTransfer.egldFromAmount("0.1").toString(), "100000000000000000"); - assert.equal(TokenTransfer.egldFromAmount("0.123456789").toString(), "123456789000000000"); - assert.equal(TokenTransfer.egldFromAmount("0.123456789123456789").toString(), "123456789123456789"); - assert.equal(TokenTransfer.egldFromAmount("0.123456789123456789777").toString(), "123456789123456789"); - assert.equal(TokenTransfer.egldFromAmount("0.123456789123456789777777888888").toString(), "123456789123456789"); - - assert.equal(TokenTransfer.egldFromAmount(0.1).toPrettyString(), "0.100000000000000000 EGLD"); - assert.equal(TokenTransfer.egldFromAmount(1).toPrettyString(), "1.000000000000000000 EGLD"); - assert.equal(TokenTransfer.egldFromAmount(10).toPrettyString(), "10.000000000000000000 EGLD"); - 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.egldFromBigInteger("1").toString(), "1"); - assert.equal(TokenTransfer.egldFromBigInteger("1").toPrettyString(), "0.000000000000000001 EGLD"); - assert.isTrue(TokenTransfer.egldFromAmount("1").isEgld()); - }); - - it("should work with USDC (legacy)", () => { - const identifier = "USDC-c76f1f"; - const numDecimals = 6; - - assert.equal(TokenTransfer.fungibleFromAmount(identifier, "1", numDecimals).toString(), "1000000"); - 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", - ); - }); - - it("should work with MetaESDT (legacy)", () => { + it("should work with custom token type", () => { const identifier = "MEXFARML-28d646"; - const numDecimals = 18; - const nonce = 12345678; - const transfer = TokenTransfer.metaEsdtFromAmount(identifier, nonce, "0.1", numDecimals); - - assert.equal(transfer.tokenIdentifier, identifier); - assert.equal(transfer.nonce, nonce); + const nonce = 12345678n; + const transfer = new TokenTransfer({ + token: new Token({ identifier, nonce }), + amount: BigInt(100000000000000000), + }); + + assert.equal(transfer.token.identifier, identifier); + assert.equal(transfer.token.nonce, nonce); assert.equal(transfer.toString(), "100000000000000000"); }); it("should work with NFTs (legacy)", () => { const identifier = "TEST-38f249"; - const nonce = 1; - const transfer = TokenTransfer.nonFungible(identifier, nonce); + const nonce = 1n; + const transfer = new TokenTransfer({ token: new Token({ identifier, nonce }), amount: 1n }); assert.equal(transfer.tokenIdentifier, identifier); - assert.equal(transfer.nonce, nonce); - assert.equal(transfer.toPrettyString(), "1 TEST-38f249"); + assert.equal(transfer.token.nonce, nonce); + assert.equal(transfer.amount, 1n); }); it("should create TokenTransfer from native token amount", () => { - const transfer = TokenTransfer.newFromEgldAmount(1000000000000000000n); + const transfer = TokenTransfer.newFromNativeAmount(1000000000000000000n); assert.equal(transfer.token.identifier, "EGLD-000000"); assert.equal(transfer.token.nonce, 0n); diff --git a/src/tokens.ts b/src/tokens.ts index f8c4a364f..8e9d66a35 100644 --- a/src/tokens.ts +++ b/src/tokens.ts @@ -85,7 +85,7 @@ export class TokenTransfer { } } - static newFromEgldAmount(amount: bigint): TokenTransfer { + static newFromNativeAmount(amount: bigint): TokenTransfer { const token = new Token({ identifier: EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER }); return new TokenTransfer({ token, amount }); } @@ -95,7 +95,7 @@ export class TokenTransfer { } /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); */ static egldFromAmount(amount: BigNumber.Value) { const amountAsBigInteger = new BigNumber(amount).shiftedBy(EGLDNumDecimals).decimalPlaces(0); @@ -103,7 +103,7 @@ export class TokenTransfer { } /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); */ static egldFromBigInteger(amountAsBigInteger: BigNumber.Value) { return new TokenTransfer({ @@ -115,7 +115,7 @@ export class TokenTransfer { } /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); */ static fungibleFromAmount(tokenIdentifier: string, amount: BigNumber.Value, numDecimals: number) { const amountAsBigInteger = new BigNumber(amount).shiftedBy(numDecimals).decimalPlaces(0); @@ -123,7 +123,7 @@ export class TokenTransfer { } /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); */ static fungibleFromBigInteger( tokenIdentifier: string, @@ -139,7 +139,7 @@ export class TokenTransfer { } /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); */ static nonFungible(tokenIdentifier: string, nonce: number) { return new TokenTransfer({ @@ -151,7 +151,7 @@ export class TokenTransfer { } /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); */ static semiFungible(tokenIdentifier: string, nonce: number, quantity: number) { return new TokenTransfer({ @@ -163,7 +163,7 @@ export class TokenTransfer { } /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); */ static metaEsdtFromAmount(tokenIdentifier: string, nonce: number, amount: BigNumber.Value, numDecimals: number) { const amountAsBigInteger = new BigNumber(amount).shiftedBy(numDecimals).decimalPlaces(0); @@ -171,7 +171,7 @@ export class TokenTransfer { } /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); */ static metaEsdtFromBigInteger( tokenIdentifier: string, @@ -192,14 +192,14 @@ export class TokenTransfer { } /** - * Legacy function. Use the "amount" field instead. + * @deprecated Use the "amount" field instead. */ valueOf(): BigNumber { return new BigNumber(this.amount.toString()); } /** - * Legacy function. For formatting and parsing amounts, use "sdk-dapp" or "bignumber.js" directly. + * @deprecated For formatting and parsing amounts, use "sdk-dapp" or "bignumber.js" directly. */ toPrettyString(): string { return `${this.toAmount()} ${this.tokenIdentifier}`; @@ -210,7 +210,7 @@ export class TokenTransfer { } /** - * Legacy function. Within your code, don't mix native values (EGLD) and custom (ESDT) tokens. + * @deprecated Within your code, don't mix native values (EGLD) and custom (ESDT) tokens. * See "TransferTransactionsFactory.createTransactionForNativeTokenTransfer()" vs. "TransferTransactionsFactory.createTransactionForESDTTokenTransfer()". */ isEgld(): boolean { @@ -218,7 +218,7 @@ export class TokenTransfer { } /** - * Legacy function. Use "TokenComputer.isFungible(token)" instead. + * @deprecated Use "TokenComputer.isFungible(token)" instead. */ isFungible(): boolean { return this.token.nonce == 0n; diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index b21667def..9e95780be 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -39,7 +39,7 @@ describe("test transaction", function () { let transactionOne = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.egldFromAmount(42).amount, + value: TokenTransfer.newFromNativeAmount(42n).amount, gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -47,7 +47,7 @@ describe("test transaction", function () { let transactionTwo = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.egldFromAmount(43).amount, + value: TokenTransfer.newFromNativeAmount(43n).amount, gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -72,7 +72,10 @@ describe("test transaction", function () { await bob.sync(provider); let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); - assert.deepEqual(TokenTransfer.egldFromAmount(85).valueOf(), newBalanceOfBob.minus(initialBalanceOfBob)); + assert.deepEqual( + TokenTransfer.newFromNativeAmount(85n).amount, + BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()), + ); }); it("should send transaction and wait for completion using the new proxy provider", async function () { @@ -86,7 +89,7 @@ describe("test transaction", function () { let transactionOne = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.egldFromAmount(42).amount, + value: TokenTransfer.newFromNativeAmount(42n).amount, gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -103,7 +106,10 @@ describe("test transaction", function () { await bob.sync(provider); let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); - assert.deepEqual(TokenTransfer.egldFromAmount(42).valueOf(), newBalanceOfBob.minus(initialBalanceOfBob)); + assert.deepEqual( + TokenTransfer.newFromNativeAmount(42n).amount, + BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()), + ); }); it("should simulate transactions", async function () { @@ -118,7 +124,7 @@ describe("test transaction", function () { data: Buffer.from("helloWorld"), gasLimit: 70000n, receiver: alice.address, - value: TokenTransfer.egldFromAmount(1000).amount, + value: TokenTransfer.newFromNativeAmount(1000n).amount, chainID: network.ChainID, }); @@ -127,7 +133,7 @@ describe("test transaction", function () { data: Buffer.from("helloWorld"), gasLimit: 70000n, receiver: alice.address, - value: TokenTransfer.egldFromAmount(1000000).amount, + value: TokenTransfer.newFromNativeAmount(1000000n).amount, chainID: network.ChainID, }); @@ -171,7 +177,10 @@ describe("test transaction", function () { await bob.sync(provider); const newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); - assert.deepEqual(TokenTransfer.egldFromAmount(42).valueOf(), newBalanceOfBob.minus(initialBalanceOfBob)); + assert.deepEqual( + TokenTransfer.newFromNativeAmount(42n).amount, + BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()), + ); }); async function signTransaction(options: { transaction: Transaction; wallet: TestWallet }) { diff --git a/src/transfers/transferTransactionsFactory.ts b/src/transfers/transferTransactionsFactory.ts index 45b4fc739..b523d24fe 100644 --- a/src/transfers/transferTransactionsFactory.ts +++ b/src/transfers/transferTransactionsFactory.ts @@ -132,7 +132,7 @@ export class TransferTransactionsFactory { }); } - const nativeTransfer = nativeAmount ? TokenTransfer.newFromEgldAmount(nativeAmount) : undefined; + const nativeTransfer = nativeAmount ? TokenTransfer.newFromNativeAmount(nativeAmount) : undefined; if (nativeTransfer) { tokenTransfers.push(nativeTransfer); } @@ -199,9 +199,9 @@ export class TransferTransactionsFactory { const { argumentsString } = new ArgSerializer().valuesToString([ // The token identifier - BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), + BytesValue.fromUTF8(args.tokenTransfer.token.identifier), // The transfered amount - new BigUIntValue(args.tokenTransfer.valueOf()), + new BigUIntValue(args.tokenTransfer.amount), ]); const data = `ESDTTransfer@${argumentsString}`; @@ -241,11 +241,11 @@ export class TransferTransactionsFactory { const { argumentsString } = new ArgSerializer().valuesToString([ // The token identifier - BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), + BytesValue.fromUTF8(args.tokenTransfer.token.identifier), // The nonce of the token - new U64Value(args.tokenTransfer.nonce), + new U64Value(args.tokenTransfer.token.nonce), // The transferred quantity - new BigUIntValue(args.tokenTransfer.valueOf()), + new BigUIntValue(args.tokenTransfer.amount), // The destination address new AddressValue(args.destination), ]); @@ -296,11 +296,11 @@ export class TransferTransactionsFactory { parts.push( ...[ // The token identifier - BytesValue.fromUTF8(payment.tokenIdentifier), + BytesValue.fromUTF8(payment.token.identifier), // The nonce of the token - new U64Value(payment.nonce), + new U64Value(payment.token.nonce), // The transfered quantity - new BigUIntValue(payment.valueOf()), + new BigUIntValue(payment.amount), ], ); } From 6a28a88808ec98822f4e9eff3a4947f5c0a1200f Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 17 Dec 2024 15:23:02 +0200 Subject: [PATCH 091/214] Update Address to follow specs --- src/abi/codec/address.ts | 4 ++-- src/abi/interaction.spec.ts | 2 +- src/abi/query.spec.ts | 2 +- src/abi/smartContract.ts | 2 +- .../accountTransactionsFactory.ts | 2 +- src/address.spec.ts | 6 +++--- src/address.ts | 14 +++++++------- src/compatibility.ts | 4 ++-- .../delegationTransactionsFactory.spec.ts | 5 ++++- src/delegation/delegationTransactionsFactory.ts | 2 +- src/message.ts | 2 +- src/networkProviders/apiNetworkProvider.ts | 10 +++++----- src/networkProviders/proxyNetworkProvider.ts | 14 +++++++------- src/proto/serializer.spec.ts | 4 ++-- .../smartContractTransactionsFactory.ts | 4 ++-- .../tokenManagementTransactionsFactory.ts | 2 +- src/utils.codec.ts | 2 +- 17 files changed, 42 insertions(+), 39 deletions(-) diff --git a/src/abi/codec/address.ts b/src/abi/codec/address.ts index 8e640d540..befe22ff4 100644 --- a/src/abi/codec/address.ts +++ b/src/abi/codec/address.ts @@ -29,13 +29,13 @@ export class AddressBinaryCodec { * Encodes an AddressValue to a buffer. */ encodeNested(primitive: AddressValue): Buffer { - return primitive.valueOf().pubkey(); + return primitive.valueOf().getPublicKey(); } /** * Encodes an AddressValue to a buffer. */ encodeTopLevel(primitive: AddressValue): Buffer { - return primitive.valueOf().pubkey(); + return primitive.valueOf().getPublicKey(); } } diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 61b643255..515c4f0cc 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -65,7 +65,7 @@ describe("test smart contract interactor", function () { const hexBar = "4241522d356263303866"; const hexLKMEX = "4c4b4d45582d616162393130"; const hexNFT = "4d4f532d623962346232"; - const hexContractAddress = new Address(contract.getAddress().toBech32()).hex(); + const hexContractAddress = new Address(contract.getAddress().toBech32()).toHex(); const hexDummyFunction = "64756d6d79"; // ESDT, single diff --git a/src/abi/query.spec.ts b/src/abi/query.spec.ts index 090166b1a..b9e198cbc 100644 --- a/src/abi/query.spec.ts +++ b/src/abi/query.spec.ts @@ -1,9 +1,9 @@ +import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Address } from "../address"; import { ContractFunction } from "./function"; import { Query } from "./query"; import { BigUIntValue, U32Value } from "./typesystem"; -import BigNumber from "bignumber.js"; import { BytesValue } from "./typesystem/bytes"; describe("test smart contract queries", () => { diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 2814336cb..78440f7ff 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -288,7 +288,7 @@ export class SmartContract implements ISmartContract { * @param nonce The owner nonce used for the deployment transaction */ static computeAddress(owner: Address, nonce: bigint): Address { - const deployer = Address.fromBech32(owner.toBech32()); + const deployer = Address.newFromBech32(owner.toBech32()); const addressComputer = new AddressComputer(); return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); } diff --git a/src/accountManagement/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts index 37b17662f..646edb0a5 100644 --- a/src/accountManagement/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -63,7 +63,7 @@ export class AccountTransactionsFactory { createTransactionForSettingGuardian(sender: Address, options: SetGuardianInput): Transaction { const dataParts = [ "SetGuardian", - Address.fromBech32(options.guardianAddress.bech32()).toHex(), + Address.newFromBech32(options.guardianAddress.toBech32()).toHex(), Buffer.from(options.serviceID).toString("hex"), ]; diff --git a/src/address.spec.ts b/src/address.spec.ts index ee7546755..bfb2dccf1 100644 --- a/src/address.spec.ts +++ b/src/address.spec.ts @@ -20,12 +20,12 @@ describe("test address", () => { }); it("should create address (custom hrp)", async () => { - let address = Address.fromHex(aliceHex, "test"); + let address = Address.newFromHex(aliceHex, "test"); assert.deepEqual(address.getPublicKey(), Buffer.from(aliceHex, "hex")); assert.equal(address.getHrp(), "test"); assert.equal(address.toBech32(), "test1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ss5hqhtr"); - address = Address.fromHex(bobHex, "xerd"); + address = Address.newFromHex(bobHex, "xerd"); assert.deepEqual(address.getPublicKey(), Buffer.from(bobHex, "hex")); assert.equal(address.getHrp(), "xerd"); assert.equal(address.toBech32(), "xerd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruq9thc9j"); @@ -34,7 +34,7 @@ describe("test address", () => { it("should create empty address", async () => { const nobody = Address.empty(); - assert.isEmpty(nobody.hex()); + assert.isEmpty(nobody.toHex()); assert.isEmpty(nobody.toBech32()); assert.deepEqual(nobody.toJSON(), { bech32: "", pubkey: "" }); }); diff --git a/src/address.ts b/src/address.ts index 04686e774..4b1327b4d 100644 --- a/src/address.ts +++ b/src/address.ts @@ -93,7 +93,7 @@ export class Address { } /** - * Use {@link newFromBech32} instead. + * @deprecated Use {@link newFromBech32} instead. */ static fromBech32(value: string): Address { // On this legacy flow, we do not accept addresses with custom hrp (in order to avoid behavioral breaking changes). @@ -113,7 +113,7 @@ export class Address { } /** - * Use {@link newFromHex} instead. + * @deprecated Use {@link newFromHex} instead. */ static fromHex(value: string, hrp?: string): Address { return Address.newFromHex(value, hrp); @@ -147,7 +147,7 @@ export class Address { } /** - * Use {@link toHex} instead. + * @deprecated Use {@link toHex} instead. */ hex(): string { return this.toHex(); @@ -165,7 +165,7 @@ export class Address { } /** - * Use {@link toBech32} instead. + * @deprecated Use {@link toBech32} instead. */ bech32(): string { return this.toBech32(); @@ -179,13 +179,13 @@ export class Address { return ""; } - let words = bech32.toWords(this.pubkey()); + let words = bech32.toWords(this.getPublicKey()); let address = bech32.encode(this.hrp, words); return address; } /** - * Use {@link getPublicKey} instead. + * @deprecated Use {@link getPublicKey} instead. */ pubkey(): Buffer { return this.getPublicKey(); @@ -249,7 +249,7 @@ export class Address { } /** - * Use {@link isSmartContract} instead. + * @deprecated Use {@link isSmartContract} instead. */ isContractAddress(): boolean { return this.isSmartContract(); diff --git a/src/compatibility.ts b/src/compatibility.ts index 357b724a8..25d584aa2 100644 --- a/src/compatibility.ts +++ b/src/compatibility.ts @@ -8,11 +8,11 @@ export class Compatibility { * For internal use only. */ static guardAddressIsSetAndNonZero(address: Address | undefined, context: string, resolution: string) { - if (!address || address.bech32() == "") { + if (!address || address.toBech32() == "") { 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().toBech32()) { + } else if (address.toBech32() == Address.Zero().toBech32()) { 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/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index 65a11930d..a99916bb0 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -25,7 +25,10 @@ describe("test delegation transactions factory", function () { transaction.sender, Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), ); - assert.deepEqual(transaction.receiver, Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, config.addressHrp)); + assert.deepEqual( + transaction.receiver, + Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, config.addressHrp), + ); assert.isDefined(transaction.data); assert.deepEqual(transaction.data, Buffer.from("createNewDelegationContract@010f0cf064dd59200000@0a")); assert.equal(transaction.gasLimit, 60126500n); diff --git a/src/delegation/delegationTransactionsFactory.ts b/src/delegation/delegationTransactionsFactory.ts index bd71fcd3b..94c688e96 100644 --- a/src/delegation/delegationTransactionsFactory.ts +++ b/src/delegation/delegationTransactionsFactory.ts @@ -31,7 +31,7 @@ export class DelegationTransactionsFactory { constructor(options: { config: IConfig }) { this.config = options.config; this.argSerializer = new ArgSerializer(); - this.delegationManagerAddress = Address.fromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, this.config.addressHrp); + this.delegationManagerAddress = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX, this.config.addressHrp); } createTransactionForNewDelegationContract( diff --git a/src/message.ts b/src/message.ts index 4d10df6cd..03bbde1a6 100644 --- a/src/message.ts +++ b/src/message.ts @@ -86,7 +86,7 @@ export class MessageComputer { let address: Address | undefined = undefined; if (packedMessage.address) { - address = Address.fromBech32(packedMessage.address); + address = Address.newFromBech32(packedMessage.address); } const version = packedMessage.version || DEFAULT_MESSAGE_VERSION; diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 3d4784769..5f16345ea 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -66,7 +66,7 @@ export class ApiNetworkProvider implements INetworkProvider { } async getAccount(address: Address): Promise { - const response = await this.doGetGeneric(`accounts/${address.bech32()}`); + const response = await this.doGetGeneric(`accounts/${address.toBech32()}`); const account = AccountOnNetwork.fromHttpResponse(response); return account; } @@ -81,7 +81,7 @@ export class ApiNetworkProvider implements INetworkProvider { ): Promise { pagination = pagination || defaultPagination; - const url = `accounts/${address.bech32()}/tokens?${this.buildPaginationParams(pagination)}`; + const url = `accounts/${address.toBech32()}/tokens?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); const tokens = response.map((item) => FungibleTokenOfAccountOnNetwork.fromHttpResponse(item)); @@ -96,7 +96,7 @@ export class ApiNetworkProvider implements INetworkProvider { ): Promise { pagination = pagination || defaultPagination; - const url = `accounts/${address.bech32()}/nfts?${this.buildPaginationParams(pagination)}`; + const url = `accounts/${address.toBech32()}/nfts?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); const tokens = response.map((item) => NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(item)); @@ -109,7 +109,7 @@ export class ApiNetworkProvider implements INetworkProvider { address: Address, tokenIdentifier: string, ): Promise { - const response = await this.doGetGeneric(`accounts/${address.bech32()}/tokens/${tokenIdentifier}`); + const response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${tokenIdentifier}`); const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response); return tokenData; } @@ -120,7 +120,7 @@ export class ApiNetworkProvider implements INetworkProvider { nonce: number, ): Promise { const nonceAsHex = numberToPaddedHex(nonce); - const response = await this.doGetGeneric(`accounts/${address.bech32()}/nfts/${collection}-${nonceAsHex}`); + const response = await this.doGetGeneric(`accounts/${address.toBech32()}/nfts/${collection}-${nonceAsHex}`); const tokenData = NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(response); return tokenData; } diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index f54ea8316..631947053 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -59,13 +59,13 @@ export class ProxyNetworkProvider implements INetworkProvider { } async getAccount(address: Address): Promise { - const response = await this.doGetGeneric(`address/${address.bech32()}`); + const response = await this.doGetGeneric(`address/${address.toBech32()}`); const account = AccountOnNetwork.fromHttpResponse(response.account); return account; } async getGuardianData(address: Address): Promise { - const response = await this.doGetGeneric(`address/${address.bech32()}/guardian-data`); + const response = await this.doGetGeneric(`address/${address.toBech32()}/guardian-data`); const accountGuardian = GuardianData.fromHttpResponse(response.guardianData); return accountGuardian; } @@ -74,7 +74,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: Address, _pagination?: IPagination, ): Promise { - const url = `address/${address.bech32()}/esdt`; + const url = `address/${address.toBech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); // Skip NFTs / SFTs. @@ -90,7 +90,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: Address, _pagination?: IPagination, ): Promise { - const url = `address/${address.bech32()}/esdt`; + const url = `address/${address.toBech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); // Skip fungible tokens. @@ -108,7 +108,7 @@ export class ProxyNetworkProvider implements INetworkProvider { address: Address, tokenIdentifier: string, ): Promise { - const response = await this.doGetGeneric(`address/${address.bech32()}/esdt/${tokenIdentifier}`); + const response = await this.doGetGeneric(`address/${address.toBech32()}/esdt/${tokenIdentifier}`); const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response.tokenData); return tokenData; } @@ -119,7 +119,7 @@ export class ProxyNetworkProvider implements INetworkProvider { nonce: number, ): Promise { const response = await this.doGetGeneric( - `address/${address.bech32()}/nft/${collection}/nonce/${nonce.valueOf()}`, + `address/${address.toBech32()}/nft/${collection}/nonce/${nonce.valueOf()}`, ); const tokenData = NonFungibleTokenOfAccountOnNetwork.fromProxyHttpResponseByNonce(response.tokenData); return tokenData; @@ -185,7 +185,7 @@ export class ProxyNetworkProvider implements INetworkProvider { const encodedIdentifier = Buffer.from(identifier); const queryResponse = await this.queryContract({ - contract: Address.fromHex(ESDT_CONTRACT_ADDRESS_HEX), + contract: Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX), function: "getTokenProperties", arguments: [new Uint8Array(encodedIdentifier)], }); diff --git a/src/proto/serializer.spec.ts b/src/proto/serializer.spec.ts index 142a6570f..226eb101c 100644 --- a/src/proto/serializer.spec.ts +++ b/src/proto/serializer.spec.ts @@ -126,8 +126,8 @@ describe("serialize transactions", () => { const transaction = new Transaction({ nonce: 204n, value: 1000000000000000000n, - sender: Address.fromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"), - receiver: Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + sender: Address.newFromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"), + receiver: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), senderUsername: "carol", receiverUsername: "alice", gasLimit: 50000n, diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index e77ba6e9c..7fd885f2c 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -43,7 +43,7 @@ export class SmartContractTransactionsFactory { this.abi = options.abi; this.tokenComputer = new TokenComputer(); this.dataArgsBuilder = new TokenTransfersDataBuilder(); - this.contractDeployAddress = Address.fromHex(CONTRACT_DEPLOY_ADDRESS_HEX, this.config.addressHrp); + this.contractDeployAddress = Address.newFromHex(CONTRACT_DEPLOY_ADDRESS_HEX, this.config.addressHrp); } createTransactionForDeploy(sender: Address, options: resources.ContractDeployInput): Transaction { @@ -185,7 +185,7 @@ export class SmartContractTransactionsFactory { contract: Address; newOwner: Address; }): Transaction { - const dataParts = ["ChangeOwnerAddress", Address.fromBech32(options.newOwner.toBech32()).toHex()]; + const dataParts = ["ChangeOwnerAddress", Address.newFromBech32(options.newOwner.toBech32()).toHex()]; return new TransactionBuilder({ config: this.config, diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index b87ab9fb1..bf902580e 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -51,7 +51,7 @@ export class TokenManagementTransactionsFactory { this.argSerializer = new ArgSerializer(); this.trueAsString = "true"; this.falseAsString = "false"; - this.esdtContractAddress = Address.fromHex(ESDT_CONTRACT_ADDRESS_HEX, this.config.addressHrp); + this.esdtContractAddress = Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, this.config.addressHrp); } createTransactionForIssuingFungible(sender: Address, options: resources.IssueFungibleInput): Transaction { diff --git a/src/utils.codec.ts b/src/utils.codec.ts index ab64eed86..b1fc6a8f0 100644 --- a/src/utils.codec.ts +++ b/src/utils.codec.ts @@ -54,6 +54,6 @@ export function bigIntToHex(value: BigNumber.Value): string { } export function addressToHex(address: Address): string { - const buffer = Address.fromBech32(address.toString()).pubkey(); + const buffer = Address.newFromBech32(address.toString()).getPublicKey(); return buffer.toString("hex"); } From f20e9d4ed51f5e95cc785be994a51f72b4bcc424 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 17 Dec 2024 15:36:52 +0200 Subject: [PATCH 092/214] Fix integration tests --- src/transaction.local.net.spec.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 9e95780be..4e8c72596 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -39,7 +39,7 @@ describe("test transaction", function () { let transactionOne = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.newFromNativeAmount(42n).amount, + value: TokenTransfer.newFromNativeAmount(42000000000000000000n).amount, gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -47,7 +47,7 @@ describe("test transaction", function () { let transactionTwo = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.newFromNativeAmount(43n).amount, + value: TokenTransfer.newFromNativeAmount(43000000000000000000n).amount, gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -73,7 +73,7 @@ describe("test transaction", function () { let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); assert.deepEqual( - TokenTransfer.newFromNativeAmount(85n).amount, + TokenTransfer.newFromNativeAmount(85000000000000000000n).amount, BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()), ); }); @@ -178,7 +178,7 @@ describe("test transaction", function () { const newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); assert.deepEqual( - TokenTransfer.newFromNativeAmount(42n).amount, + TokenTransfer.newFromNativeAmount(42000000000000000000n).amount, BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()), ); }); From bacfc5634f3b1da5d0f3951925f262e9610eaf1d Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 17 Dec 2024 15:37:41 +0200 Subject: [PATCH 093/214] Update Integration tests --- src/transaction.local.net.spec.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 9e95780be..4e8c72596 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -39,7 +39,7 @@ describe("test transaction", function () { let transactionOne = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.newFromNativeAmount(42n).amount, + value: TokenTransfer.newFromNativeAmount(42000000000000000000n).amount, gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -47,7 +47,7 @@ describe("test transaction", function () { let transactionTwo = new Transaction({ sender: alice.address, receiver: bob.address, - value: TokenTransfer.newFromNativeAmount(43n).amount, + value: TokenTransfer.newFromNativeAmount(43000000000000000000n).amount, gasLimit: BigInt(network.MinGasLimit), chainID: network.ChainID, }); @@ -73,7 +73,7 @@ describe("test transaction", function () { let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); assert.deepEqual( - TokenTransfer.newFromNativeAmount(85n).amount, + TokenTransfer.newFromNativeAmount(85000000000000000000n).amount, BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()), ); }); @@ -178,7 +178,7 @@ describe("test transaction", function () { const newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); assert.deepEqual( - TokenTransfer.newFromNativeAmount(42n).amount, + TokenTransfer.newFromNativeAmount(42000000000000000000n).amount, BigInt(newBalanceOfBob.minus(initialBalanceOfBob).toString()), ); }); From 0f0102c239c3e4532c5e8b5f6d6e5d377f8fe105 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 17 Dec 2024 15:38:56 +0200 Subject: [PATCH 094/214] Drop legacy comment --- src/tokens.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tokens.spec.ts b/src/tokens.spec.ts index 88d8f65dd..28118e261 100644 --- a/src/tokens.spec.ts +++ b/src/tokens.spec.ts @@ -57,7 +57,7 @@ describe("test tokens and token computer", async () => { }); }); -describe("test token transfer (legacy)", () => { +describe("test token transfer", () => { it("should work with custom token type", () => { const identifier = "MEXFARML-28d646"; const nonce = 12345678n; @@ -71,7 +71,7 @@ describe("test token transfer (legacy)", () => { assert.equal(transfer.toString(), "100000000000000000"); }); - it("should work with NFTs (legacy)", () => { + it("should work with NFTs", () => { const identifier = "TEST-38f249"; const nonce = 1n; const transfer = new TokenTransfer({ token: new Token({ identifier, nonce }), amount: 1n }); From f297d2347f58aef68872ed9d25ff877695bd007e Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 17 Dec 2024 15:55:08 +0200 Subject: [PATCH 095/214] Remove gas estimator related code --- src/transfers/transferTransactionsFactory.ts | 220 +------------------ 1 file changed, 4 insertions(+), 216 deletions(-) diff --git a/src/transfers/transferTransactionsFactory.ts b/src/transfers/transferTransactionsFactory.ts index b523d24fe..0ed1e1bab 100644 --- a/src/transfers/transferTransactionsFactory.ts +++ b/src/transfers/transferTransactionsFactory.ts @@ -1,4 +1,3 @@ -import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, TypedValue, U16Value, U64Value } from "../abi"; import { Address } from "../address"; import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../constants"; import { Err, ErrBadUsage } from "../errors"; @@ -20,13 +19,6 @@ interface IConfig { gasLimitMultiESDTNFTTransfer: bigint; } -interface IGasEstimator { - forEGLDTransfer(dataLength: number): number; - forESDTTransfer(dataLength: number): number; - forESDTNFTTransfer(dataLength: number): number; - forMultiESDTNFTTransfer(dataLength: number, numTransfers: number): number; -} - /** * Use this class to create transactions for native token transfers (EGLD) or custom tokens transfers (ESDT/NTF/MetaESDT). */ @@ -34,36 +26,11 @@ export class TransferTransactionsFactory { private readonly config?: IConfig; private readonly tokenTransfersDataBuilder?: TokenTransfersDataBuilder; private readonly tokenComputer?: TokenComputer; - private readonly gasEstimator?: IGasEstimator; - /** - * Should be instantiated using `Config`. - * Instantiating this class using GasEstimator represents the legacy version of this class. - * The legacy version contains methods like `createEGLDTransfer`, `createESDTTransfer`, `createESDTNFTTransfer` and `createMultiESDTNFTTransfer`. - * This was done in order to minimize breaking changes in client code. - */ - constructor(options: IGasEstimator | { config: IConfig }) { - if (this.isGasEstimator(options)) { - this.gasEstimator = options; - } else { - this.config = options.config; - this.tokenComputer = new TokenComputer(); - this.tokenTransfersDataBuilder = new TokenTransfersDataBuilder(); - } - } - - private isGasEstimator(options: any): options is IGasEstimator { - return ( - typeof options === "object" && - typeof options.forEGLDTransfer === "function" && - typeof options.forESDTTransfer === "function" && - typeof options.forESDTNFTTransfer === "function" && - typeof options.forMultiESDTNFTTransfer === "function" - ); - } - - private isGasEstimatorDefined(): boolean { - return this.gasEstimator !== undefined; + constructor(options: { config: IConfig }) { + this.config = options.config; + this.tokenComputer = new TokenComputer(); + this.tokenTransfersDataBuilder = new TokenTransfersDataBuilder(); } private ensureConfigIsDefined() { @@ -143,185 +110,6 @@ export class TransferTransactionsFactory { }); } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForNativeTokenTransfer} instead. - */ - createEGLDTransfer(args: { - nonce?: bigint; - value: bigint; - receiver: Address; - sender: Address; - gasPrice?: bigint; - gasLimit?: bigint; - data?: Uint8Array; - chainID: string; - }) { - if (!this.isGasEstimatorDefined()) { - throw new Err( - "You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method.", - ); - } - - const dataLength = args.data?.length || 0; - const estimatedGasLimit = this.gasEstimator!.forEGLDTransfer(dataLength); - - return new Transaction({ - nonce: args.nonce, - value: args.value, - receiver: args.receiver, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || BigInt(estimatedGasLimit), - data: args.data, - chainID: args.chainID, - }); - } - - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createESDTTransfer(args: { - tokenTransfer: TokenTransfer; - nonce?: bigint; - receiver: Address; - sender: Address; - gasPrice?: bigint; - gasLimit?: bigint; - chainID: string; - }) { - if (!this.isGasEstimatorDefined()) { - throw new Err( - "You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.", - ); - } - - const { argumentsString } = new ArgSerializer().valuesToString([ - // The token identifier - BytesValue.fromUTF8(args.tokenTransfer.token.identifier), - // The transfered amount - new BigUIntValue(args.tokenTransfer.amount), - ]); - - const data = `ESDTTransfer@${argumentsString}`; - const transactionPayload = Buffer.from(data); - const dataLength = transactionPayload.length || 0; - const estimatedGasLimit = this.gasEstimator!.forESDTTransfer(dataLength); - - return new Transaction({ - nonce: args.nonce, - receiver: args.receiver, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || BigInt(estimatedGasLimit), - data: transactionPayload, - chainID: args.chainID, - }); - } - - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createESDTNFTTransfer(args: { - tokenTransfer: TokenTransfer; - nonce?: bigint; - destination: Address; - sender: Address; - gasPrice?: bigint; - gasLimit?: bigint; - chainID: string; - }) { - if (!this.isGasEstimatorDefined()) { - throw new Err( - "You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.", - ); - } - - const { argumentsString } = new ArgSerializer().valuesToString([ - // The token identifier - BytesValue.fromUTF8(args.tokenTransfer.token.identifier), - // The nonce of the token - new U64Value(args.tokenTransfer.token.nonce), - // The transferred quantity - new BigUIntValue(args.tokenTransfer.amount), - // The destination address - new AddressValue(args.destination), - ]); - - const data = `ESDTNFTTransfer@${argumentsString}`; - const transactionPayload = Buffer.from(data); - const dataLength = transactionPayload.length || 0; - const estimatedGasLimit = this.gasEstimator!.forESDTNFTTransfer(dataLength); - - return new Transaction({ - nonce: args.nonce, - receiver: args.sender, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || BigInt(estimatedGasLimit), - data: transactionPayload, - chainID: args.chainID, - }); - } - - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createMultiESDTNFTTransfer(args: { - tokenTransfers: TokenTransfer[]; - nonce?: bigint; - destination: Address; - sender: Address; - gasPrice?: bigint; - gasLimit?: bigint; - chainID: string; - }) { - if (!this.isGasEstimatorDefined()) { - throw new Err( - "You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.", - ); - } - - const parts: TypedValue[] = [ - // The destination address - new AddressValue(args.destination), - // Number of tokens - new U16Value(args.tokenTransfers.length), - ]; - - for (const payment of args.tokenTransfers) { - parts.push( - ...[ - // The token identifier - BytesValue.fromUTF8(payment.token.identifier), - // The nonce of the token - new U64Value(payment.token.nonce), - // The transfered quantity - new BigUIntValue(payment.amount), - ], - ); - } - - const { argumentsString } = new ArgSerializer().valuesToString(parts); - const data = `MultiESDTNFTTransfer@${argumentsString}`; - const transactionPayload = Buffer.from(data); - const dataLength = transactionPayload.length || 0; - const estimatedGasLimit = this.gasEstimator!.forMultiESDTNFTTransfer(dataLength, args.tokenTransfers.length); - - return new Transaction({ - nonce: args.nonce, - receiver: args.sender, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || BigInt(estimatedGasLimit), - data: transactionPayload, - chainID: args.chainID, - }); - } - private createSingleESDTTransferTransaction( sender: Address, options: { From ede0df6481288e93b259aa636e4fb1fbd3008839 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 18 Dec 2024 11:07:06 +0200 Subject: [PATCH 096/214] Code review follow up --- src/abi/interaction.spec.ts | 2 +- src/abi/smartContract.ts | 3 +-- src/accountManagement/accountTransactionsFactory.ts | 2 +- src/entrypoints/entrypoints.spec.ts | 5 ++--- src/smartContracts/smartContractTransactionsFactory.ts | 2 +- src/utils.codec.ts | 6 ------ 6 files changed, 6 insertions(+), 14 deletions(-) diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 515c4f0cc..c24450dc0 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -65,7 +65,7 @@ describe("test smart contract interactor", function () { const hexBar = "4241522d356263303866"; const hexLKMEX = "4c4b4d45582d616162393130"; const hexNFT = "4d4f532d623962346232"; - const hexContractAddress = new Address(contract.getAddress().toBech32()).toHex(); + const hexContractAddress = contract.getAddress().toHex(); const hexDummyFunction = "64756d6d79"; // ESDT, single diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 78440f7ff..2a48e597d 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -288,8 +288,7 @@ export class SmartContract implements ISmartContract { * @param nonce The owner nonce used for the deployment transaction */ static computeAddress(owner: Address, nonce: bigint): Address { - const deployer = Address.newFromBech32(owner.toBech32()); const addressComputer = new AddressComputer(); - return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); + return addressComputer.computeContractAddress(owner, BigInt(nonce.valueOf())); } } diff --git a/src/accountManagement/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts index 646edb0a5..2cdac3c70 100644 --- a/src/accountManagement/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -63,7 +63,7 @@ export class AccountTransactionsFactory { createTransactionForSettingGuardian(sender: Address, options: SetGuardianInput): Transaction { const dataParts = [ "SetGuardian", - Address.newFromBech32(options.guardianAddress.toBech32()).toHex(), + options.guardianAddress.toHex(), Buffer.from(options.serviceID).toString("hex"), ]; diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index f26e423e3..782437606 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -42,8 +42,7 @@ describe("TestEntrypoint", () => { this.timeout(30000); const abi = await loadAbiRegistry("src/testdata/adder.abi.json"); const sender = Account.newFromPem(alicePem.pemFileText); - const accountAddress = new Address(sender.address); - sender.nonce = await entrypoint.recallAccountNonce(accountAddress); + sender.nonce = await entrypoint.recallAccountNonce(sender.address); const controller = entrypoint.createSmartContractController(abi); const bytecode = readFileSync("src/testdata/adder.wasm"); @@ -63,7 +62,7 @@ describe("TestEntrypoint", () => { assert.equal(outcome.contracts.length, 1); - const contractAddress = Address.fromBech32(outcome.contracts[0].address); + const contractAddress = Address.newFromBech32(outcome.contracts[0].address); const executeTransaction = await controller.createTransactionForExecute( sender, diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index 7fd885f2c..42113e174 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -185,7 +185,7 @@ export class SmartContractTransactionsFactory { contract: Address; newOwner: Address; }): Transaction { - const dataParts = ["ChangeOwnerAddress", Address.newFromBech32(options.newOwner.toBech32()).toHex()]; + const dataParts = ["ChangeOwnerAddress", options.newOwner.toHex()]; return new TransactionBuilder({ config: this.config, diff --git a/src/utils.codec.ts b/src/utils.codec.ts index b1fc6a8f0..467f6d31c 100644 --- a/src/utils.codec.ts +++ b/src/utils.codec.ts @@ -1,6 +1,5 @@ import BigNumber from "bignumber.js"; import * as contractsCodecUtils from "./abi/codec/utils"; -import { Address } from "./address"; export function numberToPaddedHex(value: bigint | number | BigNumber.Value) { let hexableNumber: { toString(radix?: number): string }; @@ -52,8 +51,3 @@ export function bigIntToHex(value: BigNumber.Value): string { return contractsCodecUtils.getHexMagnitudeOfBigInt(value); } - -export function addressToHex(address: Address): string { - const buffer = Address.newFromBech32(address.toString()).getPublicKey(); - return buffer.toString("hex"); -} From 23fd5cf623fd950a12ee184dc246481a00f903d2 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 18 Dec 2024 11:13:47 +0200 Subject: [PATCH 097/214] Fix compiling --- src/tokenOperations/codec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tokenOperations/codec.ts b/src/tokenOperations/codec.ts index 3fc5cad65..5dcd62c13 100644 --- a/src/tokenOperations/codec.ts +++ b/src/tokenOperations/codec.ts @@ -22,7 +22,7 @@ export function bigIntToBuffer(value: BigNumber.Value): Buffer { return contractsCodecUtils.bigIntToBuffer(value); } -export { addressToHex, bigIntToHex, utf8ToHex } from "../utils.codec"; +export { bigIntToHex, utf8ToHex } from "../utils.codec"; export function bufferToHex(value: Buffer) { const hex = value.toString("hex"); From 7fa413a47edcb32ac0097b1559de0cae52d8e3c9 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 18 Dec 2024 11:24:06 +0200 Subject: [PATCH 098/214] Remove unneeded check --- src/transfers/transferTransactionsFactory.ts | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/transfers/transferTransactionsFactory.ts b/src/transfers/transferTransactionsFactory.ts index 0ed1e1bab..3423142fd 100644 --- a/src/transfers/transferTransactionsFactory.ts +++ b/src/transfers/transferTransactionsFactory.ts @@ -1,6 +1,6 @@ import { Address } from "../address"; import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../constants"; -import { Err, ErrBadUsage } from "../errors"; +import { ErrBadUsage } from "../errors"; import { TokenComputer, TokenTransfer } from "../tokens"; import { TokenTransfersDataBuilder } from "../tokenTransfersDataBuilder"; import { Transaction } from "../transaction"; @@ -33,15 +33,7 @@ export class TransferTransactionsFactory { this.tokenTransfersDataBuilder = new TokenTransfersDataBuilder(); } - private ensureConfigIsDefined() { - if (this.config === undefined) { - throw new Err("'config' is not defined"); - } - } - createTransactionForNativeTokenTransfer(sender: Address, options: resources.NativeTokenTransferInput): Transaction { - this.ensureConfigIsDefined(); - const data = options.data || new Uint8Array(); return new Transaction({ @@ -55,8 +47,6 @@ export class TransferTransactionsFactory { } createTransactionForESDTTokenTransfer(sender: Address, options: resources.CustomTokenTransferInput): Transaction { - this.ensureConfigIsDefined(); - const numberOfTransfers = options.tokenTransfers.length; if (numberOfTransfers === 0) { @@ -117,8 +107,6 @@ export class TransferTransactionsFactory { tokenTransfers: TokenTransfer[]; }, ): Transaction { - this.ensureConfigIsDefined(); - const transfer = options.tokenTransfers[0]; const { dataParts, extraGasForTransfer, receiver } = this.buildTransferData(transfer, { sender, From be16a79bd0ea086b4991a5ebcf7e90d1a00916d2 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 18 Dec 2024 11:43:05 +0200 Subject: [PATCH 099/214] Update code metadata to follow specs --- src/abi/codeMetadata.spec.ts | 8 ++++---- src/abi/codeMetadata.ts | 6 +++--- src/abi/codec/codemetadata.ts | 4 ++-- src/abi/smartContract.ts | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/abi/codeMetadata.spec.ts b/src/abi/codeMetadata.spec.ts index 7d184c4eb..2322a6417 100644 --- a/src/abi/codeMetadata.spec.ts +++ b/src/abi/codeMetadata.spec.ts @@ -37,7 +37,7 @@ describe("CodeMetadata Class Tests", function () { CodeMetadata.ByteZero.Upgradeable | CodeMetadata.ByteZero.Readable, CodeMetadata.ByteOne.Payable | CodeMetadata.ByteOne.PayableBySc, ]); - const metadata = CodeMetadata.fromBuffer(buffer); + const metadata = CodeMetadata.newFromBuffer(buffer); assert.isTrue(metadata.upgradeable); assert.isTrue(metadata.readable); @@ -47,7 +47,7 @@ describe("CodeMetadata Class Tests", function () { it("should create from buffer correctly when some flags are set", function () { const buffer = Buffer.from([CodeMetadata.ByteZero.Upgradeable, CodeMetadata.ByteOne.PayableBySc]); - const metadata = CodeMetadata.fromBuffer(buffer); + const metadata = CodeMetadata.newFromBuffer(buffer); assert.isTrue(metadata.upgradeable); assert.isFalse(metadata.readable); @@ -60,7 +60,7 @@ describe("CodeMetadata Class Tests", function () { assert.throws( () => { - CodeMetadata.fromBuffer(buffer); + CodeMetadata.newFromBuffer(buffer); }, Error, "code metadata buffer has length 1, expected 2", @@ -69,7 +69,7 @@ describe("CodeMetadata Class Tests", function () { it("should test code metadata from bytes", () => { const bytes = new Uint8Array([1, 0]); - const codeMetadata = CodeMetadata.fromBytes(bytes); + const codeMetadata = CodeMetadata.newFromBytes(bytes); assert.equal(codeMetadata.toString(), "0100"); assert.deepEqual(codeMetadata.toJSON(), { diff --git a/src/abi/codeMetadata.ts b/src/abi/codeMetadata.ts index 7efff036a..34160f5ce 100644 --- a/src/abi/codeMetadata.ts +++ b/src/abi/codeMetadata.ts @@ -41,14 +41,14 @@ export class CodeMetadata { this.payableBySc = payableBySc; } - static fromBytes(bytes: Uint8Array): CodeMetadata { - return CodeMetadata.fromBuffer(Buffer.from(bytes)); + static newFromBytes(bytes: Uint8Array): CodeMetadata { + return CodeMetadata.newFromBuffer(Buffer.from(bytes)); } /** * Creates a metadata object from a buffer. */ - static fromBuffer(buffer: Buffer): CodeMetadata { + static newFromBuffer(buffer: Buffer): CodeMetadata { if (buffer.length != CodeMetadataLength) { throw new Error(`code metadata buffer has length ${buffer.length}, expected ${CodeMetadataLength}`); } diff --git a/src/abi/codec/codemetadata.ts b/src/abi/codec/codemetadata.ts index e5502ad8e..09682de28 100644 --- a/src/abi/codec/codemetadata.ts +++ b/src/abi/codec/codemetadata.ts @@ -3,12 +3,12 @@ import { CodeMetadataValue } from "../typesystem/codeMetadata"; export class CodeMetadataCodec { decodeNested(buffer: Buffer): [CodeMetadataValue, number] { - const codeMetadata = CodeMetadata.fromBuffer(buffer.slice(0, CodeMetadataLength)); + const codeMetadata = CodeMetadata.newFromBuffer(buffer.slice(0, CodeMetadataLength)); return [new CodeMetadataValue(codeMetadata), CodeMetadataLength]; } decodeTopLevel(buffer: Buffer): CodeMetadataValue { - const codeMetadata = CodeMetadata.fromBuffer(buffer); + const codeMetadata = CodeMetadata.newFromBuffer(buffer); return new CodeMetadataValue(codeMetadata); } diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 2a48e597d..624ada69e 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -165,7 +165,7 @@ export class SmartContract implements ISmartContract { } { let metadata: CodeMetadata; if (codeMetadata) { - metadata = CodeMetadata.fromBytes(Buffer.from(codeMetadata.toString(), "hex")); + metadata = CodeMetadata.newFromBytes(Buffer.from(codeMetadata.toString(), "hex")); } else { metadata = new CodeMetadata(); } From 3645a29b7c1fa36364baa743d0ad5cd0221efda8 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 19 Dec 2024 15:32:08 +0200 Subject: [PATCH 100/214] Update TransactionOnNetwork to follow specs --- .../providers.dev.net.spec.ts | 14 +++++-- ...tContractTransactionsOutcomeParser.spec.ts | 10 ++--- src/transactionEvents.ts | 3 +- src/transactionOnNetwork.ts | 41 +++++++++++-------- .../transactionEventsParser.spec.ts | 4 +- 5 files changed, 42 insertions(+), 30 deletions(-) diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 3c5a09e7e..4a7760d14 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -274,12 +274,18 @@ describe("test network providers on devnet: Proxy and API", function () { ) { // Proxy and API exhibit differences in the "function" field, in case of move-balance transactions. apiResponse.function = proxyResponse.function; - + apiResponse.raw = {}; + apiResponse.smartContractResults.map((x) => (x.raw = {})); + apiResponse.smartContractResults.map((x) => x.logs.events.map((e) => (e.raw = {}))); + apiResponse.logs.events.map((e) => (e.raw = {})); // Ignore fields which are not present on API response: proxyResponse.epoch = 0; - proxyResponse.blockNonce = 0; - proxyResponse.hyperblockNonce = 0; - proxyResponse.hyperblockHash = ""; + proxyResponse.blockHash = ""; + proxyResponse.miniblockHash = ""; + proxyResponse.raw = {}; + proxyResponse.smartContractResults.map((x) => (x.raw = {})); + proxyResponse.smartContractResults.map((x) => x.logs.events.map((e) => (e.raw = {}))); + proxyResponse.logs.events.map((e) => (e.raw = {})); } it("should have the same response for transactions with events", async function () { diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index 1f1b151dd..b835dbf6d 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -17,7 +17,7 @@ describe("test smart contract transactions outcome parser", () => { const parser = new SmartContractTransactionsOutcomeParser(); const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 7, + nonce: 7n, logs: new TransactionLogs({ events: [ new TransactionEvent({ @@ -52,7 +52,7 @@ describe("test smart contract transactions outcome parser", () => { const parser = new SmartContractTransactionsOutcomeParser(); const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 7, + nonce: 7n, logs: new TransactionLogs({ events: [ new TransactionEvent({ @@ -77,7 +77,7 @@ describe("test smart contract transactions outcome parser", () => { it("parses execute outcome, without ABI", function () { const parser = new SmartContractTransactionsOutcomeParser(); const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 7, + nonce: 7n, smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b@2a") })], }); @@ -94,7 +94,7 @@ describe("test smart contract transactions outcome parser", () => { }); const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 7, + nonce: 7n, function: "getUltimateAnswer", smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b@2a") })], }); @@ -113,7 +113,7 @@ describe("test smart contract transactions outcome parser", () => { }); const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 7, + nonce: 7n, smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b@2a") })], }); diff --git a/src/transactionEvents.ts b/src/transactionEvents.ts index 5aadce52c..48df23ccb 100644 --- a/src/transactionEvents.ts +++ b/src/transactionEvents.ts @@ -1,6 +1,7 @@ import { Address } from "./address"; export class TransactionEvent { + raw: Record = {}; address: Address = Address.empty(); identifier: string = ""; topics: Uint8Array[] = []; @@ -25,8 +26,8 @@ export class TransactionEvent { result.topics = (responsePart.topics || []).map((topic) => Buffer.from(topic, "base64")); result.data = Buffer.from(responsePart.data ?? "", "base64"); - result.additionalData = (responsePart.additionalData || []).map((data) => Buffer.from(data, "base64")); + result.raw = responsePart; return result; } diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 0e7b4f496..ebb81f2c1 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -32,26 +32,29 @@ export function prepareTransactionForBroadcasting(transaction: Transaction): any } export class TransactionOnNetwork { + raw: Record = {}; isCompleted?: boolean; hash: string = ""; type: string = ""; - nonce: number = 0; - round: number = 0; + nonce: bigint = 0n; + round: bigint = 0n; epoch: number = 0; - value: string = ""; + value: bigint = 0n; receiver: Address = Address.empty(); sender: Address = Address.empty(); - gasLimit: number = 0; - gasPrice: number = 0; + senderShard: number = 0; + receiverShard: number = 0; + gasLimit: bigint = 0n; + gasPrice: bigint = 0n; function: string = ""; data: Buffer = Buffer.from([]); + version: number = 0; + options: number = 0; signature: string = ""; status: TransactionStatus = TransactionStatus.createUnknown(); timestamp: number = 0; - - blockNonce: number = 0; - hyperblockNonce: number = 0; - hyperblockHash: string = ""; + miniblockHash: string = ""; + blockHash: string = ""; smartContractResults: SmartContractResult[] = []; logs: TransactionLogs = new TransactionLogs(); @@ -105,23 +108,25 @@ export class TransactionOnNetwork { let result = new TransactionOnNetwork(); result.hash = txHash; result.type = response.type || ""; - result.nonce = response.nonce || 0; - result.round = response.round; + result.nonce = BigInt(response.nonce || 0); + result.round = BigInt(response.round || 0); result.epoch = response.epoch || 0; - result.value = (response.value || 0).toString(); + result.value = BigInt((response.value || 0).toString()); result.sender = new Address(response.sender); result.receiver = new Address(response.receiver); - result.gasPrice = response.gasPrice || 0; - result.gasLimit = response.gasLimit || 0; + result.gasPrice = BigInt(response.gasPrice) || 0n; + result.gasLimit = BigInt(response.gasLimit) || 0n; result.function = response.function || ""; result.data = Buffer.from(response.data || "", "base64"); + result.version = response.version || 1; + result.options = response.options || 0; + result.data = Buffer.from(response.data || "", "base64"); result.status = new TransactionStatus(response.status); result.timestamp = response.timestamp || 0; - - result.blockNonce = response.blockNonce || 0; - result.hyperblockNonce = response.hyperblockNonce || 0; - result.hyperblockHash = response.hyperblockHash || ""; + result.miniblockHash = response.miniblockHash || ""; + result.blockHash = response.blockHash || ""; result.logs = TransactionLogs.fromHttpResponse(response.logs || {}); + // result.raw = response; return result; } diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts index d5fb21d24..5770853a0 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts @@ -42,7 +42,7 @@ describe("test transaction events parser", () => { }); const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 7, + nonce: 7n, smartContractResults: [ new SmartContractResult({ data: Buffer.from("@6f6b"), @@ -92,7 +92,7 @@ describe("test transaction events parser", () => { }); const transactionOnNetwork = new TransactionOnNetwork({ - nonce: 7, + nonce: 7n, smartContractResults: [new SmartContractResult({ data: Buffer.from("@6f6b") })], logs: new TransactionLogs({ events: [ From cd90c4e6b00fd23207fcd781d1919f53a40ba282 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 14 Jan 2025 11:11:35 +0200 Subject: [PATCH 101/214] Update isCompleted --- src/testutils/mockNetworkProvider.ts | 5 ++--- src/transactionOnNetwork.ts | 2 +- src/transactionWatcher.ts | 5 +---- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index ea560da96..6083900e8 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -121,7 +121,7 @@ export class MockNetworkProvider implements INetworkProvider { } mockPutTransaction(hash: TransactionHash, item: TransactionOnNetwork) { - item.isCompleted = false; + item.status = TransactionStatus.createUnknown(); this.transactions.set(hash.toString(), item); } @@ -137,7 +137,6 @@ export class MockNetworkProvider implements INetworkProvider { let response = new TransactionOnNetwork({ status: new TransactionStatus("executed"), smartContractResults: [contractResult], - isCompleted: true, function: functionName, }); @@ -164,7 +163,7 @@ export class MockNetworkProvider implements INetworkProvider { }); } else if (point instanceof MarkCompleted) { this.mockUpdateTransaction(hash, (transaction) => { - transaction.isCompleted = true; + transaction.status = new TransactionStatus("success"); }); } else if (point instanceof Wait) { await timeline.start(point.milliseconds); diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index ebb81f2c1..36fb4f07f 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -82,7 +82,7 @@ export class TransactionOnNetwork { if (processStatus) { result.status = processStatus; - result.isCompleted = result.status.isSuccessful() || result.status.isFailed(); + result.isCompleted = result.status.isExecuted(); } return result; diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index d0483105f..4b2179a2c 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -81,10 +81,7 @@ export class TransactionWatcher { */ public async awaitCompleted(transactionOrTxHash: ITransaction | string): Promise { const isCompleted = (transactionOnNetwork: TransactionOnNetwork) => { - if (transactionOnNetwork.isCompleted === undefined) { - throw new ErrIsCompletedFieldIsMissingOnTransaction(); - } - return transactionOnNetwork.isCompleted; + return transactionOnNetwork.status.isExecuted(); }; const doFetch = async () => { From 8501e03bb4bed5b49632bbba9f0748987eefdf0c Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 14 Jan 2025 11:13:24 +0200 Subject: [PATCH 102/214] remove comment --- src/transactionOnNetwork.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 36fb4f07f..f7a692f0b 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -126,7 +126,7 @@ export class TransactionOnNetwork { result.miniblockHash = response.miniblockHash || ""; result.blockHash = response.blockHash || ""; result.logs = TransactionLogs.fromHttpResponse(response.logs || {}); - // result.raw = response; + result.raw = response; return result; } From 7df8980bff7f1e178deb16d2abbf8dd49a43743a Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 14 Jan 2025 12:19:16 +0200 Subject: [PATCH 103/214] Add isCompleted on TranactionStatus and mark as deprecated isExecuted --- src/transactionOnNetwork.ts | 2 +- src/transactionStatus.ts | 26 +++++++++++--------------- src/transactionWatcher.ts | 2 +- 3 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index f7a692f0b..c884a6895 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -82,7 +82,7 @@ export class TransactionOnNetwork { if (processStatus) { result.status = processStatus; - result.isCompleted = result.status.isExecuted(); + result.isCompleted = result.status.isCompleted(); } return result; diff --git a/src/transactionStatus.ts b/src/transactionStatus.ts index bb509cbcf..e13ee7b84 100644 --- a/src/transactionStatus.ts +++ b/src/transactionStatus.ts @@ -25,40 +25,36 @@ export class TransactionStatus { * Returns whether the transaction is pending (e.g. in mempool). */ isPending(): boolean { - return ( - this.status == "received" || - this.status == "pending" - ); + return this.status == "received" || this.status == "pending"; } /** * Returns whether the transaction has been executed (not necessarily with success). + * @deprecated This will be remove next version, please use {@link isCompleted} instead. */ isExecuted(): boolean { return this.isSuccessful() || this.isFailed() || this.isInvalid(); } + /** + * Returns whether the transaction has been conpleted (not necessarily with success). + */ + isCompleted(): boolean { + return this.isSuccessful() || this.isFailed() || this.isInvalid(); + } + /** * Returns whether the transaction has been executed successfully. */ isSuccessful(): boolean { - return ( - this.status == "executed" || - this.status == "success" || - this.status == "successful" - ); + return this.status == "executed" || this.status == "success" || this.status == "successful"; } /** * Returns whether the transaction has been executed, but with a failure. */ isFailed(): boolean { - return ( - this.status == "fail" || - this.status == "failed" || - this.status == "unsuccessful" || - this.isInvalid() - ); + return this.status == "fail" || this.status == "failed" || this.status == "unsuccessful" || this.isInvalid(); } /** diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index 4b2179a2c..98bf20739 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -81,7 +81,7 @@ export class TransactionWatcher { */ public async awaitCompleted(transactionOrTxHash: ITransaction | string): Promise { const isCompleted = (transactionOnNetwork: TransactionOnNetwork) => { - return transactionOnNetwork.status.isExecuted(); + return transactionOnNetwork.status.isCompleted(); }; const doFetch = async () => { From 00144afd91a3b6f87e3ae63e6ceb75dd81f3bfa0 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 14 Jan 2025 14:24:00 +0200 Subject: [PATCH 104/214] Add isCompleted and IsSuccessfull falg on transaction status --- src/transactionOnNetwork.ts | 4 ++-- src/transactionStatus.ts | 16 +++++++++++----- src/transactionWatcher.ts | 2 +- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index c884a6895..42bfa624e 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -50,7 +50,7 @@ export class TransactionOnNetwork { data: Buffer = Buffer.from([]); version: number = 0; options: number = 0; - signature: string = ""; + signature?: Uint8Array; status: TransactionStatus = TransactionStatus.createUnknown(); timestamp: number = 0; miniblockHash: string = ""; @@ -82,7 +82,7 @@ export class TransactionOnNetwork { if (processStatus) { result.status = processStatus; - result.isCompleted = result.status.isCompleted(); + result.isCompleted = result.status.isStatusCompleted(); } return result; diff --git a/src/transactionStatus.ts b/src/transactionStatus.ts index e13ee7b84..e58486817 100644 --- a/src/transactionStatus.ts +++ b/src/transactionStatus.ts @@ -7,11 +7,17 @@ export class TransactionStatus { */ readonly status: string; + readonly isCompleted: boolean; + + readonly isSuccessfull: boolean; + /** * Creates a new TransactionStatus object. */ constructor(status: string) { this.status = (status || "").toLowerCase(); + this.isCompleted = this.isStatusCompleted(); + this.isSuccessfull = this.isStatusSuccessful(); } /** @@ -30,23 +36,23 @@ export class TransactionStatus { /** * Returns whether the transaction has been executed (not necessarily with success). - * @deprecated This will be remove next version, please use {@link isCompleted} instead. + * @deprecated This will be remove next version, please use {@link isStatusCompleted} instead. */ isExecuted(): boolean { - return this.isSuccessful() || this.isFailed() || this.isInvalid(); + return this.isStatusSuccessful() || this.isFailed() || this.isInvalid(); } /** * Returns whether the transaction has been conpleted (not necessarily with success). */ - isCompleted(): boolean { - return this.isSuccessful() || this.isFailed() || this.isInvalid(); + isStatusCompleted(): boolean { + return this.isStatusSuccessful() || this.isFailed() || this.isInvalid(); } /** * Returns whether the transaction has been executed successfully. */ - isSuccessful(): boolean { + isStatusSuccessful(): boolean { return this.status == "executed" || this.status == "success" || this.status == "successful"; } diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index 98bf20739..d3e4fa4c8 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -81,7 +81,7 @@ export class TransactionWatcher { */ public async awaitCompleted(transactionOrTxHash: ITransaction | string): Promise { const isCompleted = (transactionOnNetwork: TransactionOnNetwork) => { - return transactionOnNetwork.status.isCompleted(); + return transactionOnNetwork.status.isStatusCompleted(); }; const doFetch = async () => { From a3ba1c8aca7752b99bec9a3236b112de63437540 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 14 Jan 2025 14:41:36 +0200 Subject: [PATCH 105/214] Revert IsCompleted and IsSuccessfull methods --- src/transactionOnNetwork.ts | 6 +++--- src/transactionStatus.ts | 16 +++++----------- src/transactionWatcher.ts | 2 +- 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 42bfa624e..a5db991e0 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -50,7 +50,7 @@ export class TransactionOnNetwork { data: Buffer = Buffer.from([]); version: number = 0; options: number = 0; - signature?: Uint8Array; + signature: Uint8Array = new Uint8Array(); status: TransactionStatus = TransactionStatus.createUnknown(); timestamp: number = 0; miniblockHash: string = ""; @@ -82,7 +82,7 @@ export class TransactionOnNetwork { if (processStatus) { result.status = processStatus; - result.isCompleted = result.status.isStatusCompleted(); + result.isCompleted = result.status.isSuccessful() || result.status.isFailed(); } return result; @@ -126,7 +126,7 @@ export class TransactionOnNetwork { result.miniblockHash = response.miniblockHash || ""; result.blockHash = response.blockHash || ""; result.logs = TransactionLogs.fromHttpResponse(response.logs || {}); - result.raw = response; + // result.raw = response; return result; } diff --git a/src/transactionStatus.ts b/src/transactionStatus.ts index e58486817..e13ee7b84 100644 --- a/src/transactionStatus.ts +++ b/src/transactionStatus.ts @@ -7,17 +7,11 @@ export class TransactionStatus { */ readonly status: string; - readonly isCompleted: boolean; - - readonly isSuccessfull: boolean; - /** * Creates a new TransactionStatus object. */ constructor(status: string) { this.status = (status || "").toLowerCase(); - this.isCompleted = this.isStatusCompleted(); - this.isSuccessfull = this.isStatusSuccessful(); } /** @@ -36,23 +30,23 @@ export class TransactionStatus { /** * Returns whether the transaction has been executed (not necessarily with success). - * @deprecated This will be remove next version, please use {@link isStatusCompleted} instead. + * @deprecated This will be remove next version, please use {@link isCompleted} instead. */ isExecuted(): boolean { - return this.isStatusSuccessful() || this.isFailed() || this.isInvalid(); + return this.isSuccessful() || this.isFailed() || this.isInvalid(); } /** * Returns whether the transaction has been conpleted (not necessarily with success). */ - isStatusCompleted(): boolean { - return this.isStatusSuccessful() || this.isFailed() || this.isInvalid(); + isCompleted(): boolean { + return this.isSuccessful() || this.isFailed() || this.isInvalid(); } /** * Returns whether the transaction has been executed successfully. */ - isStatusSuccessful(): boolean { + isSuccessful(): boolean { return this.status == "executed" || this.status == "success" || this.status == "successful"; } diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index d3e4fa4c8..98bf20739 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -81,7 +81,7 @@ export class TransactionWatcher { */ public async awaitCompleted(transactionOrTxHash: ITransaction | string): Promise { const isCompleted = (transactionOnNetwork: TransactionOnNetwork) => { - return transactionOnNetwork.status.isStatusCompleted(); + return transactionOnNetwork.status.isCompleted(); }; const doFetch = async () => { From 279eb8d87b0c366f46d56d3bbf03ebdcb0c30301 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 14 Jan 2025 14:44:14 +0200 Subject: [PATCH 106/214] Remove commented code --- src/transactionOnNetwork.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index a5db991e0..2b4746a42 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -126,7 +126,7 @@ export class TransactionOnNetwork { result.miniblockHash = response.miniblockHash || ""; result.blockHash = response.blockHash || ""; result.logs = TransactionLogs.fromHttpResponse(response.logs || {}); - // result.raw = response; + result.raw = response; return result; } From b319e26260d2b256c7745af907e48c30a723c3e6 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 15 Jan 2025 13:21:50 +0200 Subject: [PATCH 107/214] update network providers to follow specs --- src/networkProviders/apiNetworkProvider.ts | 194 +++++++++++++------ src/networkProviders/blockOnNetwork.ts | 62 ++++++ src/networkProviders/constants.ts | 5 + src/networkProviders/interface.ts | 135 +++++++++---- src/networkProviders/proxyNetworkProvider.ts | 182 +++++++++++++---- src/networkProviders/resources.ts | 116 +++++++++++ src/testutils/mockNetworkProvider.ts | 43 ++++ 7 files changed, 604 insertions(+), 133 deletions(-) create mode 100644 src/networkProviders/blockOnNetwork.ts create mode 100644 src/networkProviders/resources.ts diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 5f16345ea..3b374a82b 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,12 +1,16 @@ import { Address } from "../address"; +import { METACHAIN_ID } from "../constants"; import { ErrContractQuery, ErrNetworkProvider } from "../errors"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; +import { Token } from "../tokens"; import { Transaction } from "../transaction"; -import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; +import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; +import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; import { numberToPaddedHex } from "../utils.codec"; import { AccountOnNetwork, GuardianData } from "./accounts"; +import { BlockOnNetwork } from "./blockOnNetwork"; import { defaultAxiosConfig, defaultPagination } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; @@ -18,6 +22,13 @@ import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; import { PairOnNetwork } from "./pairs"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; +import { + AccountStorage, + AccountStorageEntry, + AwaitingOptions, + GetBlockArguments, + TransactionCostEstimationResponse, +} from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; import { extendUserAgentIfBackend } from "./userAgent"; @@ -49,8 +60,8 @@ export class ApiNetworkProvider implements INetworkProvider { return await this.backingProxyNetworkProvider.getNetworkConfig(); } - async getNetworkStatus(): Promise { - return await this.backingProxyNetworkProvider.getNetworkStatus(); + async getNetworkStatus(shard: number = METACHAIN_ID): Promise { + return await this.backingProxyNetworkProvider.getNetworkStatus(shard); } async getNetworkStakeStatistics(): Promise { @@ -65,12 +76,119 @@ export class ApiNetworkProvider implements INetworkProvider { return stats; } + async getBlock(blockArgs: GetBlockArguments): Promise { + const response = await this.doGetGeneric(`blocks/${blockArgs.blockHash}`); + return BlockOnNetwork.fromHttpResponse(response); + } + + async getLatestBlock(_shard: number): Promise { + const response = await this.doGetGeneric("block/latest"); + return BlockOnNetwork.fromHttpResponse(response); + } + async getAccount(address: Address): Promise { const response = await this.doGetGeneric(`accounts/${address.toBech32()}`); const account = AccountOnNetwork.fromHttpResponse(response); return account; } + async getAccountStorage(address: Address): Promise { + const response = await this.doGetGeneric(`address/${address.toBech32()}/keys`); + const account = AccountStorage.fromHttpResponse(response.data); + return account; + } + + async getAccountStorageEntry(address: Address, entryKey: string): Promise { + const keyAsHex = Buffer.from(entryKey).toString("hex"); + const response = await this.doGetGeneric(`address/${address.toBech32()}/key/${keyAsHex}`); + const account = AccountStorageEntry.fromHttpResponse(response.data, entryKey); + return account; + } + + awaitAccountOnCondition( + _address: Address, + _condition: (account: AccountOnNetwork) => boolean, + options?: AwaitingOptions, + ): AccountOnNetwork { + if (!options) { + options = new AwaitingOptions(); + } + throw new Error("Method not implemented."); + } + + async sendTransaction(tx: Transaction): Promise { + const transaction = prepareTransactionForBroadcasting(tx); + const response = await this.doPostGeneric("transactions", transaction); + return response.txHash; + } + + async simulateTransaction(tx: Transaction): Promise { + return await this.backingProxyNetworkProvider.simulateTransaction(tx); + } + async estimateTransactionCost(tx: Transaction): Promise { + const transaction = prepareTransactionForBroadcasting(tx); + const response = await this.doPostGeneric("transaction/cost", transaction); + return TransactionCostEstimationResponse.fromHttpResponse(response); + } + + async sendTransactions(txs: Transaction[]): Promise { + return await this.backingProxyNetworkProvider.sendTransactions(txs); + } + + async getTransaction(txHash: string): Promise { + const response = await this.doGetGeneric(`transactions/${txHash}`); + const transaction = TransactionOnNetwork.fromApiHttpResponse(txHash, response); + return transaction; + } + + async getTransactionStatus(txHash: string): Promise { + const response = await this.doGetGeneric(`transactions/${txHash}?fields=status`); + const status = new TransactionStatus(response.status); + return status; + } + + async awaitTransactionOnCondition( + transactionHash: string, + condition: (account: TransactionOnNetwork) => boolean, + options?: AwaitingOptions, + ): Promise { + if (!options) { + options = new AwaitingOptions(); + } + + const awaiter = new TransactionWatcher(this, { + patienceMilliseconds: options.patienceInMilliseconds, + pollingIntervalMilliseconds: options.pollingIntervalInMilliseconds, + timeoutMilliseconds: options.timeoutInMilliseconds, + }); + return await awaiter.awaitOnCondition(transactionHash, condition); + } + async awaitTransactionCompleted(transactionHash: string, options?: AwaitingOptions): Promise { + if (!options) { + options = new AwaitingOptions(); + } + + const awaiter = new TransactionWatcher(this, { + patienceMilliseconds: options.patienceInMilliseconds, + pollingIntervalMilliseconds: options.pollingIntervalInMilliseconds, + timeoutMilliseconds: options.timeoutInMilliseconds, + }); + return await awaiter.awaitCompleted(transactionHash); + } + + //TODO check this + async getTokenOfAccount(address: Address, token: Token): Promise { + let response; + if (token.nonce === 0n) { + response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${token.identifier}`); + } else { + response = await this.doGetGeneric( + `accounts/${address.toBech32()}/nfts/${token.identifier}/nonce/${token.nonce}`, + ); + } + return FungibleTokenOfAccountOnNetwork.fromHttpResponse(response); + } + async getGuardianData(address: Address): Promise { return await this.backingProxyNetworkProvider.getGuardianData(address); } @@ -84,9 +202,6 @@ export class ApiNetworkProvider implements INetworkProvider { const url = `accounts/${address.toBech32()}/tokens?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); const tokens = response.map((item) => FungibleTokenOfAccountOnNetwork.fromHttpResponse(item)); - - // TODO: Fix sorting - tokens.sort((a, b) => a.identifier.localeCompare(b.identifier)); return tokens; } @@ -99,9 +214,6 @@ export class ApiNetworkProvider implements INetworkProvider { const url = `accounts/${address.toBech32()}/nfts?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); const tokens = response.map((item) => NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(item)); - - // TODO: Fix sorting - tokens.sort((a, b) => a.identifier.localeCompare(b.identifier)); return tokens; } @@ -125,6 +237,25 @@ export class ApiNetworkProvider implements INetworkProvider { return tokenData; } + async getDefinitionOfFungibleToken(tokenIdentifier: string): Promise { + const response = await this.doGetGeneric(`tokens/${tokenIdentifier}`); + const definition = DefinitionOfFungibleTokenOnNetwork.fromApiHttpResponse(response); + return definition; + } + + async getDefinitionOfTokenCollection(collection: string): Promise { + const response = await this.doGetGeneric(`collections/${collection}`); + const definition = DefinitionOfTokenCollectionOnNetwork.fromApiHttpResponse(response); + return definition; + } + + async getNonFungibleToken(collection: string, nonce: number): Promise { + const nonceAsHex = numberToPaddedHex(nonce); + const response = await this.doGetGeneric(`nfts/${collection}-${nonceAsHex}`); + const token = NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(response); + return token; + } + async getMexPairs(pagination?: IPagination): Promise { let url = `mex/pairs`; if (pagination) { @@ -136,32 +267,6 @@ export class ApiNetworkProvider implements INetworkProvider { return response.map((item) => PairOnNetwork.fromApiHttpResponse(item)); } - async getTransaction(txHash: string): Promise { - const response = await this.doGetGeneric(`transactions/${txHash}`); - const transaction = TransactionOnNetwork.fromApiHttpResponse(txHash, response); - return transaction; - } - - async getTransactionStatus(txHash: string): Promise { - const response = await this.doGetGeneric(`transactions/${txHash}?fields=status`); - const status = new TransactionStatus(response.status); - return status; - } - - async sendTransaction(tx: Transaction): Promise { - const transaction = prepareTransactionForBroadcasting(tx); - const response = await this.doPostGeneric("transactions", transaction); - return response.txHash; - } - - async sendTransactions(txs: Transaction[]): Promise { - return await this.backingProxyNetworkProvider.sendTransactions(txs); - } - - async simulateTransaction(tx: Transaction): Promise { - return await this.backingProxyNetworkProvider.simulateTransaction(tx); - } - async queryContract(query: SmartContractQuery): Promise { try { const request = new ContractQueryRequest(query).toHttpRequest(); @@ -172,25 +277,6 @@ export class ApiNetworkProvider implements INetworkProvider { } } - async getDefinitionOfFungibleToken(tokenIdentifier: string): Promise { - const response = await this.doGetGeneric(`tokens/${tokenIdentifier}`); - const definition = DefinitionOfFungibleTokenOnNetwork.fromApiHttpResponse(response); - return definition; - } - - async getDefinitionOfTokenCollection(collection: string): Promise { - const response = await this.doGetGeneric(`collections/${collection}`); - const definition = DefinitionOfTokenCollectionOnNetwork.fromApiHttpResponse(response); - return definition; - } - - async getNonFungibleToken(collection: string, nonce: number): Promise { - const nonceAsHex = numberToPaddedHex(nonce); - const response = await this.doGetGeneric(`nfts/${collection}-${nonceAsHex}`); - const token = NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(response); - return token; - } - async doGetGeneric(resourceUrl: string): Promise { const response = await this.doGet(resourceUrl); return response; diff --git a/src/networkProviders/blockOnNetwork.ts b/src/networkProviders/blockOnNetwork.ts new file mode 100644 index 000000000..bba2409e5 --- /dev/null +++ b/src/networkProviders/blockOnNetwork.ts @@ -0,0 +1,62 @@ +/** + * An object holding network status configuration parameters. + */ +export class BlockOnNetwork { + /** + * The raw data return by provider. + */ + public raw: Record = {}; + + /** + * The shard number. + */ + public shard: number = 0; + + /** + * The shard nonce. + */ + public nonce: bigint = 0n; + + /** + * The block hash. + */ + public hash: string = ""; + + /** + * The block previous hash. + */ + public previousHash: string = ""; + + /** + * The block timestamp. + */ + public timestamp: number = 0; + + /** + * The block timestamp. + */ + public round: number = 0; + + /** + * The block timestamp. + */ + public epoch: number = 0; + + /** + * Constructs a configuration object from a HTTP response (as returned by the provider). + */ + static fromHttpResponse(payload: any): BlockOnNetwork { + let blockOnNetwork = new BlockOnNetwork(); + + blockOnNetwork.raw = payload; + blockOnNetwork.shard = Number(payload["shard"]) ?? 0; + blockOnNetwork.nonce = BigInt(payload["nonce"] ?? 0); + blockOnNetwork.hash = payload["hash"]; + blockOnNetwork.previousHash = payload["prevBlockHash"] ?? payload["prevHash"] ?? ""; + blockOnNetwork.timestamp = Number(payload["timestamp"] ?? 0); + blockOnNetwork.round = Number(payload["round"] ?? 0); + blockOnNetwork.epoch = Number(payload["epoch"] ?? 0); + + return blockOnNetwork; + } +} diff --git a/src/networkProviders/constants.ts b/src/networkProviders/constants.ts index d85d175b4..06d93c10a 100644 --- a/src/networkProviders/constants.ts +++ b/src/networkProviders/constants.ts @@ -5,3 +5,8 @@ export const MaxUint64AsBigNumber = new BigNumber("18446744073709551615"); export const EsdtContractAddress = new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); export const BaseUserAgent = "multiversx-sdk"; export const UnknownClientName = "unknown"; + +export const DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS = 6000; +export const DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS = + 15 * DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS; +export const DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS = 0; diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 773f26135..4b8c3734a 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,13 +1,22 @@ import { Address } from "../address"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; +import { Token } from "../tokens"; import { Transaction } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { AccountOnNetwork } from "./accounts"; +import { BlockOnNetwork } from "./blockOnNetwork"; import { NetworkConfig } from "./networkConfig"; import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; +import { + AccountStorage, + AccountStorageEntry, + AwaitingOptions, + GetBlockArguments, + TransactionCostEstimationResponse, +} from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; @@ -26,14 +35,14 @@ export interface INetworkProvider { getNetworkStatus(): Promise; /** - * Fetches stake statistics. + * Fetches a block by nonce or by hash. */ - getNetworkStakeStatistics(): Promise; + getBlock(blockArgs: GetBlockArguments): Promise; /** - * Fetches general statistics. + * Fetches the latest block of a shard. */ - getNetworkGeneralStatistics(): Promise; + getLatestBlock(shard: number): Promise; /** * Fetches the state of an account. @@ -41,31 +50,47 @@ export interface INetworkProvider { getAccount(address: Address): Promise; /** - * Fetches data about the fungible tokens held by an account. + * Fetches the storage (key-value pairs) of an account. */ - getFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise; + getAccountStorage(address: Address): Promise; /** - * Fetches data about the non-fungible tokens held by account. + * Fetches a specific storage entry of an account. */ - getNonFungibleTokensOfAccount( + getAccountStorageEntry(address: Address, entryKey: string): Promise; + + /** + * Waits until an account satisfies a given condition. + * Can throw: + * - ErrAwaitConditionNotReached + */ + awaitAccountOnCondition( address: Address, - pagination?: IPagination, - ): Promise; + condition: (account: AccountOnNetwork) => boolean, + options?: AwaitingOptions, + ): AccountOnNetwork; /** - * Fetches data about a specific fungible token held by an account. + * Broadcasts an already-signed transaction. */ - getFungibleTokenOfAccount(address: Address, tokenIdentifier: string): Promise; + sendTransaction(tx: Transaction): Promise; /** - * Fetches data about a specific non-fungible token (instance) held by an account. + * Simulates the processing of an already-signed transaction. + * */ - getNonFungibleTokenOfAccount( - address: Address, - collection: string, - nonce: number, - ): Promise; + simulateTransaction(tx: Transaction): Promise; + + /** + * Estimates the cost of a transaction. + * + */ + estimateTransactionCost(tx: Transaction): Promise; + + /** + * Broadcasts a list of already-signed transactions. + */ + sendTransactions(txs: Transaction[]): Promise; /** * Fetches the state of a transaction. @@ -73,30 +98,54 @@ export interface INetworkProvider { getTransaction(txHash: string, withProcessStatus?: boolean): Promise; /** - * Queries the status of a transaction. + * Waits until the transaction satisfies a given condition. + * Can throw: + * - ErrAwaitConditionNotReached */ - getTransactionStatus(txHash: string): Promise; + awaitTransactionOnCondition( + transactionHash: string, + condition: (account: TransactionOnNetwork) => boolean, + options?: AwaitingOptions, + ): Promise; /** - * Broadcasts an already-signed transaction. + * Waits until the transaction is completely processed. + * Can throw: + * - ErrAwaitConditionNotReached */ - sendTransaction(tx: Transaction): Promise; + awaitTransactionCompleted(transactionHash: string, options?: AwaitingOptions): Promise; /** - * Broadcasts a list of already-signed transactions. + * Fetches the balance of an account, for a given token. */ - sendTransactions(txs: Transaction[]): Promise; + getTokenOfAccount(address: Address, token: Token): Promise; /** - * Simulates the processing of an already-signed transaction. - * + * Fetches data about the fungible tokens held by an account. */ - simulateTransaction(tx: Transaction): Promise; + getFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise; /** - * Queries a Smart Contract - runs a pure function defined by the contract and returns its results. + * Fetches data about the non-fungible tokens held by account. */ - queryContract(query: SmartContractQuery): Promise; + getNonFungibleTokensOfAccount( + address: Address, + pagination?: IPagination, + ): Promise; + + /** + * Fetches data about a specific fungible token held by an account. + */ + getFungibleTokenOfAccount(address: Address, tokenIdentifier: string): Promise; + + /** + * Fetches data about a specific non-fungible token (instance) held by an account. + */ + getNonFungibleTokenOfAccount( + address: Address, + collection: string, + nonce: number, + ): Promise; /** * Fetches the definition of a fungible token. @@ -108,11 +157,31 @@ export interface INetworkProvider { */ getDefinitionOfTokenCollection(collection: string): Promise; + /** + * Queries a Smart Contract - runs a pure function defined by the contract and returns its results. + */ + queryContract(query: SmartContractQuery): Promise; + /** * Fetches data about a specific non-fungible token (instance). */ getNonFungibleToken(collection: string, nonce: number): Promise; + /** + * Fetches stake statistics. + */ + getNetworkStakeStatistics(): Promise; + + /** + * Fetches general statistics. + */ + getNetworkGeneralStatistics(): Promise; + + /** + * Queries the status of a transaction. + */ + getTransactionStatus(txHash: string): Promise; + /** * Performs a generic GET action against the provider (useful for new HTTP endpoints). */ @@ -124,14 +193,6 @@ export interface INetworkProvider { doPostGeneric(resourceUrl: string, payload: any): Promise; } -export interface IContractQuery { - address: Address; - caller?: Address; - func: { toString(): string }; - value?: { toString(): string }; - getEncodedArguments(): string[]; -} - export interface IPagination { from: number; size: number; diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 631947053..c00650f6f 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,12 +1,15 @@ import { Address } from "../address"; -import { ESDT_CONTRACT_ADDRESS_HEX } from "../constants"; +import { ESDT_CONTRACT_ADDRESS_HEX, METACHAIN_ID } from "../constants"; import { ErrContractQuery, ErrNetworkProvider } from "../errors"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; +import { Token } from "../tokens"; import { Transaction } from "../transaction"; -import { TransactionOnNetwork, prepareTransactionForBroadcasting } from "../transactionOnNetwork"; +import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; +import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; import { AccountOnNetwork, GuardianData } from "./accounts"; +import { BlockOnNetwork } from "./blockOnNetwork"; import { defaultAxiosConfig } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; @@ -16,6 +19,13 @@ import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; +import { + AccountStorage, + AccountStorageEntry, + AwaitingOptions, + GetBlockArguments, + TransactionCostEstimationResponse, +} from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; import { extendUserAgentIfBackend } from "./userAgent"; @@ -40,8 +50,8 @@ export class ProxyNetworkProvider implements INetworkProvider { return networkConfig; } - async getNetworkStatus(): Promise { - const response = await this.doGetGeneric("network/status/4294967295"); + async getNetworkStatus(shard: number = METACHAIN_ID): Promise { + const response = await this.doGetGeneric(`network/status/${shard}`); const networkStatus = NetworkStatus.fromHttpResponse(response.status); return networkStatus; } @@ -58,6 +68,22 @@ export class ProxyNetworkProvider implements INetworkProvider { throw new Error("Method not implemented."); } + async getBlock(blockArgs: GetBlockArguments): Promise { + let response = {}; + if (blockArgs.blockHash) { + response = await this.doGetGeneric(`block/${blockArgs.shard}/by-hash/${blockArgs.blockHash}`); + } else if (blockArgs.blockNonce) { + response = await this.doGetGeneric(`block/${blockArgs.shard}/by-nonce/${blockArgs.blockNonce}`); + } else throw new Error("Block hash or block nonce not provided."); + return BlockOnNetwork.fromHttpResponse(response); + } + + async getLatestBlock(shard: number): Promise { + const blockNonce = (await this.getNetworkStatus(shard)).Nonce; + const response = await this.doGetGeneric(`block/${shard}/by-nonce/${blockNonce}`); + return BlockOnNetwork.fromHttpResponse(response); + } + async getAccount(address: Address): Promise { const response = await this.doGetGeneric(`address/${address.toBech32()}`); const account = AccountOnNetwork.fromHttpResponse(response.account); @@ -70,6 +96,109 @@ export class ProxyNetworkProvider implements INetworkProvider { return accountGuardian; } + async getAccountStorage(address: Address): Promise { + const response = await this.doGetGeneric(`address/${address.toBech32()}/keys`); + const account = AccountStorage.fromHttpResponse(response); + return account; + } + + async getAccountStorageEntry(address: Address, entryKey: string): Promise { + const keyAsHex = Buffer.from(entryKey).toString("hex"); + const response = await this.doGetGeneric(`address/${address.toBech32()}/keys/${keyAsHex}`); + const account = AccountStorageEntry.fromHttpResponse(response, entryKey); + return account; + } + + awaitAccountOnCondition( + _address: Address, + _condition: (account: AccountOnNetwork) => boolean, + options?: AwaitingOptions, + ): AccountOnNetwork { + if (!options) { + options = new AwaitingOptions(); + } + throw new Error("Method not implemented."); + } + + async sendTransaction(tx: Transaction): Promise { + const transaction = prepareTransactionForBroadcasting(tx); + const response = await this.doPostGeneric("transaction/send", transaction); + return response.txHash; + } + + async simulateTransaction(tx: Transaction): Promise { + const transaction = prepareTransactionForBroadcasting(tx); + const response = await this.doPostGeneric("transaction/simulate", transaction); + return response; + } + + async estimateTransactionCost(tx: Transaction): Promise { + const transaction = prepareTransactionForBroadcasting(tx); + const response = await this.doPostGeneric("transaction/cost", transaction); + return TransactionCostEstimationResponse.fromHttpResponse(response); + } + + async sendTransactions(txs: Transaction[]): Promise { + const data = txs.map((tx) => prepareTransactionForBroadcasting(tx)); + + const response = await this.doPostGeneric("transaction/send-multiple", data); + const hashes = Array(txs.length).fill(null); + + for (let i = 0; i < txs.length; i++) { + hashes[i] = response.txsHashes[i.toString()] || null; + } + + return hashes; + } + + async getTransaction(txHash: string, _?: boolean): Promise { + const url = this.buildUrlWithQueryParameters(`transaction/${txHash}`, { withResults: "true" }); + const [data, status] = await Promise.all([this.doGetGeneric(url), this.getTransactionStatus(txHash)]); + return TransactionOnNetwork.fromProxyHttpResponse(txHash, data.transaction, status); + } + + async awaitTransactionOnCondition( + transactionHash: string, + condition: (account: TransactionOnNetwork) => boolean, + options?: AwaitingOptions, + ): Promise { + if (!options) { + options = new AwaitingOptions(); + } + + const awaiter = new TransactionWatcher(this, { + patienceMilliseconds: options.patienceInMilliseconds, + pollingIntervalMilliseconds: options.pollingIntervalInMilliseconds, + timeoutMilliseconds: options.timeoutInMilliseconds, + }); + return await awaiter.awaitOnCondition(transactionHash, condition); + } + + async awaitTransactionCompleted(transactionHash: string, options?: AwaitingOptions): Promise { + if (!options) { + options = new AwaitingOptions(); + } + + const awaiter = new TransactionWatcher(this, { + patienceMilliseconds: options.patienceInMilliseconds, + pollingIntervalMilliseconds: options.pollingIntervalInMilliseconds, + timeoutMilliseconds: options.timeoutInMilliseconds, + }); + return await awaiter.awaitCompleted(transactionHash); + } + + async getTokenOfAccount(address: Address, token: Token): Promise { + let response; + if (token.nonce === 0n) { + response = await this.doGetGeneric(`address/${address.toBech32()}/esdt/${token.identifier}`); + } else { + response = await this.doGetGeneric( + `address/${address.toBech32()}/nft/${token.identifier}/nonce/${token.nonce}`, + ); + } + return FungibleTokenOfAccountOnNetwork.fromHttpResponse(response); + } + async getFungibleTokensOfAccount( address: Address, _pagination?: IPagination, @@ -125,41 +254,19 @@ export class ProxyNetworkProvider implements INetworkProvider { return tokenData; } - async getTransaction(txHash: string, _?: boolean): Promise { - const url = this.buildUrlWithQueryParameters(`transaction/${txHash}`, { withResults: "true" }); - const [data, status] = await Promise.all([this.doGetGeneric(url), this.getTransactionStatus(txHash)]); - return TransactionOnNetwork.fromProxyHttpResponse(txHash, data.transaction, status); - } - async getTransactionStatus(txHash: string): Promise { const response = await this.doGetGeneric(`transaction/${txHash}/process-status`); const status = new TransactionStatus(response.status); return status; } - async sendTransaction(tx: Transaction): Promise { - const transaction = prepareTransactionForBroadcasting(tx); - const response = await this.doPostGeneric("transaction/send", transaction); - return response.txHash; - } - - async sendTransactions(txs: Transaction[]): Promise { - const data = txs.map((tx) => prepareTransactionForBroadcasting(tx)); - - const response = await this.doPostGeneric("transaction/send-multiple", data); - const hashes = Array(txs.length).fill(null); - - for (let i = 0; i < txs.length; i++) { - hashes[i] = response.txsHashes[i.toString()] || null; - } - - return hashes; - } - - async simulateTransaction(tx: Transaction): Promise { - const transaction = prepareTransactionForBroadcasting(tx); - const response = await this.doPostGeneric("transaction/simulate", transaction); - return response; + async getDefinitionOfFungibleToken(tokenIdentifier: string): Promise { + const properties = await this.getTokenProperties(tokenIdentifier); + const definition = DefinitionOfFungibleTokenOnNetwork.fromResponseOfGetTokenProperties( + tokenIdentifier, + properties, + ); + return definition; } async queryContract(query: SmartContractQuery): Promise { @@ -172,15 +279,6 @@ export class ProxyNetworkProvider implements INetworkProvider { } } - async getDefinitionOfFungibleToken(tokenIdentifier: string): Promise { - const properties = await this.getTokenProperties(tokenIdentifier); - const definition = DefinitionOfFungibleTokenOnNetwork.fromResponseOfGetTokenProperties( - tokenIdentifier, - properties, - ); - return definition; - } - private async getTokenProperties(identifier: string): Promise { const encodedIdentifier = Buffer.from(identifier); diff --git a/src/networkProviders/resources.ts b/src/networkProviders/resources.ts new file mode 100644 index 000000000..e4ba375ec --- /dev/null +++ b/src/networkProviders/resources.ts @@ -0,0 +1,116 @@ +import { BytesValue } from "../abi"; +import { Address } from "../address"; +import { TransactionStatus } from "../transactionStatus"; +import { + DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS, + DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS, + DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS, +} from "./constants"; + +/** + * A plain view of an account storage. + */ +export class AccountStorage { + raw: Record = {}; + blockCoordinates!: BlockCoordinates; + entries: AccountStorageEntry[] = []; + constructor(init?: Partial) { + Object.assign(this, init); + } + + static fromHttpResponse(payload: any): AccountStorage { + let result = new AccountStorage(); + + const pairs = payload["pairs"] || {}; + const entries: AccountStorageEntry[] = []; + + for (const element of pairs.items) { + const decodedKey = BytesValue.fromHex(element.key).toString(); + const decodedValue = BytesValue.fromHex(element.value); + entries.push( + new AccountStorageEntry({ + raw: { key: element.value }, + key: decodedKey, + value: decodedValue.toString(), + }), + ); + } + + result.raw = payload; + result.entries = entries; + result.blockCoordinates = BlockCoordinates.fromHttpResponse(payload); + + return result; + } +} + +export class BlockCoordinates { + nonce: bigint = 0n; + hash: string = ""; + rootHash?: string; + constructor(init?: Partial) { + Object.assign(this, init); + } + static fromHttpResponse(payload: any): BlockCoordinates { + const result = new BlockCoordinates(); + const value = payload["blockInfo"] || {}; + + result.nonce = value["nonce"] || 0n; + result.hash = value["hash"] || ""; + result.rootHash = value["rootHash"] || ""; + + return result; + } +} + +export class AccountStorageEntry { + raw: Record = {}; + address: Address = Address.empty(); + key: string = ""; + value: string = ""; + constructor(init?: Partial) { + Object.assign(this, init); + } + + static fromHttpResponse(payload: any, key: string): AccountStorageEntry { + const result = new AccountStorageEntry(); + const value = payload["value"] || ""; + + result.raw = payload; + result.key = key; + result.value = BytesValue.fromHex(value).toString(); + + return result; + } +} + +export class AwaitingOptions { + pollingIntervalInMilliseconds: number = DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS; + timeoutInMilliseconds: number = DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS; + patienceInMilliseconds: number = DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS; +} + +export class TransactionCostEstimationResponse { + raw: Record = {}; + gasLimit: number = 0; + status: TransactionStatus = TransactionStatus.createUnknown(); + + static fromHttpResponse(payload: any): TransactionCostEstimationResponse { + const result = new TransactionCostEstimationResponse(); + + result.raw = payload; + result.gasLimit = payload["txGasUnits"] ?? 0; + result.status = new TransactionStatus(""); + + return result; + } +} + +export class GetBlockArguments { + shard?: number; + blockNonce?: bigint; + blockHash?: string; + constructor(init?: Partial) { + Object.assign(this, init); + } +} diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 6083900e8..079ae4af9 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -14,8 +14,16 @@ import { NetworkStatus, NonFungibleTokenOfAccountOnNetwork, } from "../networkProviders"; +import { BlockOnNetwork } from "../networkProviders/blockOnNetwork"; import { INetworkProvider, IPagination } from "../networkProviders/interface"; +import { + AccountStorage, + AccountStorageEntry, + AwaitingOptions, + TransactionCostEstimationResponse, +} from "../networkProviders/resources"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; +import { Token } from "../tokens"; import { Transaction, TransactionHash } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; @@ -56,6 +64,41 @@ export class MockNetworkProvider implements INetworkProvider { }), ); } + getBlock(): Promise { + throw new Error("Method not implemented."); + } + getLatestBlock(_shard: number): Promise { + throw new Error("Method not implemented."); + } + getAccountStorage(_address: Address): Promise { + throw new Error("Method not implemented."); + } + getAccountStorageEntry(_address: Address, _entryKey: string): Promise { + throw new Error("Method not implemented."); + } + awaitAccountOnCondition( + _address: Address, + _condition: (account: AccountOnNetwork) => boolean, + _options?: AwaitingOptions, + ): AccountOnNetwork { + throw new Error("Method not implemented."); + } + estimateTransactionCost(_tx: Transaction): Promise { + throw new Error("Method not implemented."); + } + awaitTransactionOnCondition( + _transactionHash: string, + _condition: (account: TransactionOnNetwork) => boolean, + _options?: AwaitingOptions, + ): Promise { + throw new Error("Method not implemented."); + } + awaitTransactionCompleted(_transactionHash: string, _options?: AwaitingOptions): Promise { + throw new Error("Method not implemented."); + } + getTokenOfAccount(_address: Address, _token: Token): Promise { + throw new Error("Method not implemented."); + } getNetworkStatus(): Promise { throw new Error("Method not implemented."); } From 93db14981d33a13ab5afbe5cd9494a48e6d1d80c Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 15 Jan 2025 13:38:45 +0200 Subject: [PATCH 108/214] Remove unused methods --- src/abi/smartContract.spec.ts | 8 +- src/networkProviders/apiNetworkProvider.ts | 21 ------ src/networkProviders/index.ts | 2 - src/networkProviders/interface.ts | 18 ----- .../networkGeneralStatistics.ts | 73 ------------------- src/networkProviders/networkStake.ts | 47 ------------ .../providers.dev.net.spec.ts | 32 -------- src/networkProviders/proxyNetworkProvider.ts | 15 ---- src/testutils/mockNetworkProvider.ts | 14 +--- src/transactionWatcher.spec.ts | 4 +- 10 files changed, 7 insertions(+), 227 deletions(-) delete mode 100644 src/networkProviders/networkGeneralStatistics.ts delete mode 100644 src/networkProviders/networkStake.ts diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index 4dc5dd0ec..7658b7c50 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -85,7 +85,7 @@ describe("test contract", () => { watcher.awaitCompleted(deployTransaction.getHash().hex()), ]); - assert.isTrue((await provider.getTransactionStatus(hash)).isExecuted()); + assert.isTrue((await provider.getTransaction(hash)).status.isCompleted()); }); it("should call", async () => { @@ -154,8 +154,8 @@ describe("test contract", () => { watcher.awaitCompleted(callTransactionTwo.getHash().hex()), ]); - assert.isTrue((await provider.getTransactionStatus(hashOne)).isExecuted()); - assert.isTrue((await provider.getTransactionStatus(hashTwo)).isExecuted()); + assert.isTrue((await provider.getTransaction(hashOne)).status.isCompleted()); + assert.isTrue((await provider.getTransaction(hashTwo)).status.isCompleted()); }); it("should upgrade", async () => { @@ -200,7 +200,7 @@ describe("test contract", () => { watcher.awaitCompleted(deployTransaction.getHash().hex()), ]); - assert.isTrue((await provider.getTransactionStatus(hash)).isExecuted()); + assert.isTrue((await provider.getTransaction(hash)).status.isCompleted()); }); it("v13 should be stricter than v12 on optional> (exotic) parameters (since NativeSerializer is used under the hood)", async () => { diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 3b374a82b..f7345f560 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -5,7 +5,6 @@ import { SmartContractQuery, SmartContractQueryResponse } from "../smartContract import { Token } from "../tokens"; import { Transaction } from "../transaction"; import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionStatus } from "../transactionStatus"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; import { numberToPaddedHex } from "../utils.codec"; @@ -16,9 +15,7 @@ import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; import { INetworkProvider, IPagination } from "./interface"; import { NetworkConfig } from "./networkConfig"; -import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; -import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; import { PairOnNetwork } from "./pairs"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; @@ -64,18 +61,6 @@ export class ApiNetworkProvider implements INetworkProvider { return await this.backingProxyNetworkProvider.getNetworkStatus(shard); } - async getNetworkStakeStatistics(): Promise { - const response = await this.doGetGeneric("stake"); - const networkStake = NetworkStake.fromHttpResponse(response); - return networkStake; - } - - async getNetworkGeneralStatistics(): Promise { - const response = await this.doGetGeneric("stats"); - const stats = NetworkGeneralStatistics.fromHttpResponse(response); - return stats; - } - async getBlock(blockArgs: GetBlockArguments): Promise { const response = await this.doGetGeneric(`blocks/${blockArgs.blockHash}`); return BlockOnNetwork.fromHttpResponse(response); @@ -141,12 +126,6 @@ export class ApiNetworkProvider implements INetworkProvider { return transaction; } - async getTransactionStatus(txHash: string): Promise { - const response = await this.doGetGeneric(`transactions/${txHash}?fields=status`); - const status = new TransactionStatus(response.status); - return status; - } - async awaitTransactionOnCondition( transactionHash: string, condition: (account: TransactionOnNetwork) => boolean, diff --git a/src/networkProviders/index.ts b/src/networkProviders/index.ts index c39640f9e..4a9558add 100644 --- a/src/networkProviders/index.ts +++ b/src/networkProviders/index.ts @@ -10,6 +10,4 @@ export { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwor export { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; export { NetworkConfig } from "./networkConfig"; -export { NetworkGeneralStatistics } from "./networkGeneralStatistics"; -export { NetworkStake } from "./networkStake"; export { NetworkStatus } from "./networkStatus"; diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 4b8c3734a..35a68e33a 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -3,12 +3,9 @@ import { SmartContractQuery, SmartContractQueryResponse } from "../smartContract import { Token } from "../tokens"; import { Transaction } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionStatus } from "../transactionStatus"; import { AccountOnNetwork } from "./accounts"; import { BlockOnNetwork } from "./blockOnNetwork"; import { NetworkConfig } from "./networkConfig"; -import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; -import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; import { AccountStorage, @@ -167,21 +164,6 @@ export interface INetworkProvider { */ getNonFungibleToken(collection: string, nonce: number): Promise; - /** - * Fetches stake statistics. - */ - getNetworkStakeStatistics(): Promise; - - /** - * Fetches general statistics. - */ - getNetworkGeneralStatistics(): Promise; - - /** - * Queries the status of a transaction. - */ - getTransactionStatus(txHash: string): Promise; - /** * Performs a generic GET action against the provider (useful for new HTTP endpoints). */ diff --git a/src/networkProviders/networkGeneralStatistics.ts b/src/networkProviders/networkGeneralStatistics.ts deleted file mode 100644 index 2935b1cbc..000000000 --- a/src/networkProviders/networkGeneralStatistics.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * An object holding general Network statistics and parameters. - */ -export class NetworkGeneralStatistics { - /** - * The number of Shards. - */ - public Shards: number; - - /** - * The Number of Blocks. - */ - public Blocks: number; - - /** - * The Number of Accounts. - */ - public Accounts: number; - - /** - * The Number of transactions. - */ - public Transactions: number; - - /** - * The Refresh rate. - */ - public RefreshRate: number; - - /** - * The Number of the current Epoch. - */ - public Epoch: number; - - /** - * The Number of rounds passed. - */ - public RoundsPassed: number; - - /** - * The Number of Rounds per epoch. - */ - public RoundsPerEpoch: number; - - constructor() { - this.Shards = 0; - this.Blocks = 0; - this.Accounts = 0; - this.Transactions = 0; - this.RefreshRate = 0; - this.Epoch = 0; - this.RoundsPassed = 0; - this.RoundsPerEpoch = 0; - } - - /** - * Constructs a stats object from a HTTP response (as returned by the provider). - */ - static fromHttpResponse(payload: any): NetworkGeneralStatistics { - let stats = new NetworkGeneralStatistics(); - - stats.Shards = Number(payload["shards"]); - stats.Blocks = Number(payload["blocks"]); - stats.Accounts = Number(payload["accounts"]); - stats.Transactions = Number(payload["transactions"]); - stats.RefreshRate = Number(payload["refreshRate"]); - stats.Epoch = Number(payload["epoch"]); - stats.RoundsPassed = Number(payload["roundsPassed"]); - stats.RoundsPerEpoch = Number(payload["roundsPerEpoch"]); - - return stats; - } -} diff --git a/src/networkProviders/networkStake.ts b/src/networkProviders/networkStake.ts deleted file mode 100644 index 5806f9eb2..000000000 --- a/src/networkProviders/networkStake.ts +++ /dev/null @@ -1,47 +0,0 @@ -import BigNumber from "bignumber.js"; - -/** - * An object holding Network stake parameters. - */ -export class NetworkStake { - private static default: NetworkStake; - - /** - * The Total Validators Number. - */ - public TotalValidators: number; - - /** - * The Active Validators Number. - */ - public ActiveValidators: number; - /** - * The Queue Size. - */ - public QueueSize: number; - /** - * The Total Validators Number. - */ - public TotalStaked: BigNumber; - - constructor() { - this.TotalValidators = 0; - this.ActiveValidators = 0; - this.QueueSize = 0; - this.TotalStaked = new BigNumber(0); - } - - /** - * Constructs a configuration object from a HTTP response (as returned by the provider). - */ - static fromHttpResponse(payload: any): NetworkStake { - let networkStake = new NetworkStake(); - - networkStake.TotalValidators = Number(payload["totalValidators"]); - networkStake.ActiveValidators = Number(payload["activeValidators"]); - networkStake.QueueSize = Number(payload["queueSize"]); - networkStake.TotalStaked = new BigNumber(payload["totalStaked"]); - - return networkStake; - } -} diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 4a7760d14..ba06ad84f 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -106,22 +106,6 @@ describe("test network providers on devnet: Proxy and API", function () { assert.approximately(apiResponse.NoncesPassedInCurrentEpoch, proxyResponse.NoncesPassedInCurrentEpoch, 1); }); - // TODO: Enable test after implementing ProxyNetworkProvider.getNetworkStakeStatistics(). - it.skip("should have same response for getNetworkStakeStatistics()", async function () { - let apiResponse = await apiProvider.getNetworkStakeStatistics(); - let proxyResponse = await proxyProvider.getNetworkStakeStatistics(); - - assert.deepEqual(apiResponse, proxyResponse); - }); - - // TODO: Enable test after implementing ProxyNetworkProvider.getNetworkGeneralStatistics(). - it.skip("should have same response for getNetworkGeneralStatistics()", async function () { - let apiResponse = await apiProvider.getNetworkGeneralStatistics(); - let proxyResponse = await proxyProvider.getNetworkGeneralStatistics(); - - assert.deepEqual(apiResponse, proxyResponse); - }); - it("should have same response for getAccount()", async function () { let apiResponse = await apiProvider.getAccount(alice); let proxyResponse = await proxyProvider.getAccount(alice); @@ -317,22 +301,6 @@ describe("test network providers on devnet: Proxy and API", function () { ); }); - it("should have same response for getTransactionStatus()", async function () { - this.timeout(20000); - - let hashes = [ - "08acf8cbd71306a56eb58f9593cb2e23f109c94e27acdd906c82a5c3a5f84d9d", - "410efb1db2ab86678b8dbc503beb695b5b7d52754fb0de86c09cbb433de5f6a8", - ]; - - for (const hash of hashes) { - let apiResponse = await apiProvider.getTransactionStatus(hash); - let proxyResponse = await proxyProvider.getTransactionStatus(hash); - - assert.deepEqual(apiResponse, proxyResponse, `transaction: ${hash}`); - } - }); - it("should have same response for getDefinitionOfFungibleToken()", async function () { this.timeout(10000); diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index c00650f6f..c06f5708c 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -15,9 +15,7 @@ import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; import { INetworkProvider, IPagination } from "./interface"; import { NetworkConfig } from "./networkConfig"; -import { NetworkGeneralStatistics } from "./networkGeneralStatistics"; import { NetworkProviderConfig } from "./networkProviderConfig"; -import { NetworkStake } from "./networkStake"; import { NetworkStatus } from "./networkStatus"; import { AccountStorage, @@ -55,19 +53,6 @@ export class ProxyNetworkProvider implements INetworkProvider { const networkStatus = NetworkStatus.fromHttpResponse(response.status); return networkStatus; } - - async getNetworkStakeStatistics(): Promise { - // TODO: Implement wrt.: - // https://github.com/multiversx/mx-api-service/blob/main/src/endpoints/stake/stake.service.ts - throw new Error("Method not implemented."); - } - - async getNetworkGeneralStatistics(): Promise { - // TODO: Implement wrt. (full implementation may not be possible): - // https://github.com/multiversx/mx-api-service/blob/main/src/endpoints/network/network.service.ts - throw new Error("Method not implemented."); - } - async getBlock(blockArgs: GetBlockArguments): Promise { let response = {}; if (blockArgs.blockHash) { diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 079ae4af9..18af52ab7 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -9,8 +9,6 @@ import { DefinitionOfTokenCollectionOnNetwork, FungibleTokenOfAccountOnNetwork, NetworkConfig, - NetworkGeneralStatistics, - NetworkStake, NetworkStatus, NonFungibleTokenOfAccountOnNetwork, } from "../networkProviders"; @@ -102,12 +100,7 @@ export class MockNetworkProvider implements INetworkProvider { getNetworkStatus(): Promise { throw new Error("Method not implemented."); } - getNetworkStakeStatistics(): Promise { - throw new Error("Method not implemented."); - } - getNetworkGeneralStatistics(): Promise { - throw new Error("Method not implemented."); - } + getFungibleTokensOfAccount( _address: Address, _pagination?: IPagination, @@ -259,11 +252,6 @@ export class MockNetworkProvider implements INetworkProvider { throw new ErrMock("Transaction not found"); } - async getTransactionStatus(txHash: string): Promise { - let transaction = await this.getTransaction(txHash); - return transaction.status; - } - async getNetworkConfig(): Promise { throw new errors.ErrNotImplemented(); } diff --git a/src/transactionWatcher.spec.ts b/src/transactionWatcher.spec.ts index f5161f4a8..aeda03a5b 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/transactionWatcher.spec.ts @@ -35,7 +35,7 @@ describe("test transactionWatcher", () => { watcher.awaitCompleted(dummyTransaction.getHash().hex()), ]); - assert.isTrue((await provider.getTransactionStatus(hash.hex())).isExecuted()); + assert.isTrue((await provider.getTransaction(hash.hex())).status.isCompleted()); }); it("should await status == executed using transaction", async () => { @@ -67,6 +67,6 @@ describe("test transactionWatcher", () => { watcher.awaitCompleted(dummyTransaction), ]); - assert.isTrue((await provider.getTransactionStatus(hash.hex())).isExecuted()); + assert.isTrue((await provider.getTransaction(hash.hex())).status.isCompleted()); }); }); From 339e723453b07febf65d0df9704112da271c9b16 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 15 Jan 2025 13:50:33 +0200 Subject: [PATCH 109/214] Remove methods that are not in specs --- src/networkProviders/apiNetworkProvider.ts | 30 +------ src/networkProviders/blockOnNetwork.ts | 62 -------------- src/networkProviders/interface.ts | 35 ++------ .../providers.dev.net.spec.ts | 83 ------------------- src/networkProviders/proxyNetworkProvider.ts | 27 +----- src/networkProviders/resources.ts | 63 ++++++++++++++ src/testutils/mockNetworkProvider.ts | 15 +--- 7 files changed, 74 insertions(+), 241 deletions(-) delete mode 100644 src/networkProviders/blockOnNetwork.ts diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index f7345f560..b5587e493 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -7,9 +7,7 @@ import { Transaction } from "../transaction"; import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; -import { numberToPaddedHex } from "../utils.codec"; import { AccountOnNetwork, GuardianData } from "./accounts"; -import { BlockOnNetwork } from "./blockOnNetwork"; import { defaultAxiosConfig, defaultPagination } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; @@ -23,6 +21,7 @@ import { AccountStorage, AccountStorageEntry, AwaitingOptions, + BlockOnNetwork, GetBlockArguments, TransactionCostEstimationResponse, } from "./resources"; @@ -196,26 +195,6 @@ export class ApiNetworkProvider implements INetworkProvider { return tokens; } - async getFungibleTokenOfAccount( - address: Address, - tokenIdentifier: string, - ): Promise { - const response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${tokenIdentifier}`); - const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response); - return tokenData; - } - - async getNonFungibleTokenOfAccount( - address: Address, - collection: string, - nonce: number, - ): Promise { - const nonceAsHex = numberToPaddedHex(nonce); - const response = await this.doGetGeneric(`accounts/${address.toBech32()}/nfts/${collection}-${nonceAsHex}`); - const tokenData = NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(response); - return tokenData; - } - async getDefinitionOfFungibleToken(tokenIdentifier: string): Promise { const response = await this.doGetGeneric(`tokens/${tokenIdentifier}`); const definition = DefinitionOfFungibleTokenOnNetwork.fromApiHttpResponse(response); @@ -228,13 +207,6 @@ export class ApiNetworkProvider implements INetworkProvider { return definition; } - async getNonFungibleToken(collection: string, nonce: number): Promise { - const nonceAsHex = numberToPaddedHex(nonce); - const response = await this.doGetGeneric(`nfts/${collection}-${nonceAsHex}`); - const token = NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(response); - return token; - } - async getMexPairs(pagination?: IPagination): Promise { let url = `mex/pairs`; if (pagination) { diff --git a/src/networkProviders/blockOnNetwork.ts b/src/networkProviders/blockOnNetwork.ts deleted file mode 100644 index bba2409e5..000000000 --- a/src/networkProviders/blockOnNetwork.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * An object holding network status configuration parameters. - */ -export class BlockOnNetwork { - /** - * The raw data return by provider. - */ - public raw: Record = {}; - - /** - * The shard number. - */ - public shard: number = 0; - - /** - * The shard nonce. - */ - public nonce: bigint = 0n; - - /** - * The block hash. - */ - public hash: string = ""; - - /** - * The block previous hash. - */ - public previousHash: string = ""; - - /** - * The block timestamp. - */ - public timestamp: number = 0; - - /** - * The block timestamp. - */ - public round: number = 0; - - /** - * The block timestamp. - */ - public epoch: number = 0; - - /** - * Constructs a configuration object from a HTTP response (as returned by the provider). - */ - static fromHttpResponse(payload: any): BlockOnNetwork { - let blockOnNetwork = new BlockOnNetwork(); - - blockOnNetwork.raw = payload; - blockOnNetwork.shard = Number(payload["shard"]) ?? 0; - blockOnNetwork.nonce = BigInt(payload["nonce"] ?? 0); - blockOnNetwork.hash = payload["hash"]; - blockOnNetwork.previousHash = payload["prevBlockHash"] ?? payload["prevHash"] ?? ""; - blockOnNetwork.timestamp = Number(payload["timestamp"] ?? 0); - blockOnNetwork.round = Number(payload["round"] ?? 0); - blockOnNetwork.epoch = Number(payload["epoch"] ?? 0); - - return blockOnNetwork; - } -} diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 35a68e33a..a4bbb96bc 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -4,13 +4,13 @@ import { Token } from "../tokens"; import { Transaction } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { AccountOnNetwork } from "./accounts"; -import { BlockOnNetwork } from "./blockOnNetwork"; import { NetworkConfig } from "./networkConfig"; import { NetworkStatus } from "./networkStatus"; import { AccountStorage, AccountStorageEntry, AwaitingOptions, + BlockOnNetwork, GetBlockArguments, TransactionCostEstimationResponse, } from "./resources"; @@ -94,6 +94,13 @@ export interface INetworkProvider { */ getTransaction(txHash: string, withProcessStatus?: boolean): Promise; + /** + * Waits until the transaction is completely processed. + * Can throw: + * - ErrAwaitConditionNotReached + */ + awaitTransactionCompleted(transactionHash: string, options?: AwaitingOptions): Promise; + /** * Waits until the transaction satisfies a given condition. * Can throw: @@ -105,13 +112,6 @@ export interface INetworkProvider { options?: AwaitingOptions, ): Promise; - /** - * Waits until the transaction is completely processed. - * Can throw: - * - ErrAwaitConditionNotReached - */ - awaitTransactionCompleted(transactionHash: string, options?: AwaitingOptions): Promise; - /** * Fetches the balance of an account, for a given token. */ @@ -130,20 +130,6 @@ export interface INetworkProvider { pagination?: IPagination, ): Promise; - /** - * Fetches data about a specific fungible token held by an account. - */ - getFungibleTokenOfAccount(address: Address, tokenIdentifier: string): Promise; - - /** - * Fetches data about a specific non-fungible token (instance) held by an account. - */ - getNonFungibleTokenOfAccount( - address: Address, - collection: string, - nonce: number, - ): Promise; - /** * Fetches the definition of a fungible token. */ @@ -159,11 +145,6 @@ export interface INetworkProvider { */ queryContract(query: SmartContractQuery): Promise; - /** - * Fetches data about a specific non-fungible token (instance). - */ - getNonFungibleToken(collection: string, nonce: number): Promise; - /** * Performs a generic GET action against the provider (useful for new HTTP endpoints). */ diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index ba06ad84f..b512e6a46 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -7,13 +7,9 @@ import { TransactionOnNetwork } from "../transactionOnNetwork"; import { ApiNetworkProvider } from "./apiNetworkProvider"; import { INetworkProvider } from "./interface"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; -import { NonFungibleTokenOfAccountOnNetwork } from "./tokens"; describe("test network providers on devnet: Proxy and API", function () { let alice = new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - let carol = new Address("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"); - let dan = new Address("erd1kyaqzaprcdnv4luvanah0gfxzzsnpaygsy6pytrexll2urtd05ts9vegu7"); - const MAX_NUMBER_OF_ITEMS_BY_DEFAULT = 20; let apiProvider: INetworkProvider = new ApiNetworkProvider("https://devnet-api.multiversx.com", { timeout: 10000, @@ -113,69 +109,6 @@ describe("test network providers on devnet: Proxy and API", function () { assert.deepEqual(apiResponse, proxyResponse); }); - it("should have same response for getFungibleTokensOfAccount(), getFungibleTokenOfAccount()", async function () { - this.timeout(30000); - - for (const user of [carol, dan]) { - let apiResponse = (await apiProvider.getFungibleTokensOfAccount(user)).slice( - 0, - MAX_NUMBER_OF_ITEMS_BY_DEFAULT, - ); - let proxyResponse = (await proxyProvider.getFungibleTokensOfAccount(user)).slice( - 0, - MAX_NUMBER_OF_ITEMS_BY_DEFAULT, - ); - - for (let i = 0; i < apiResponse.length; i++) { - assert.equal(apiResponse[i].identifier, proxyResponse[i].identifier); - assert.equal(apiResponse[i].balance.valueOf, proxyResponse[i].balance.valueOf); - } - } - }); - - it("should have same response for getNonFungibleTokensOfAccount(), getNonFungibleTokenOfAccount", async function () { - this.timeout(30000); - - let apiResponse = (await apiProvider.getNonFungibleTokensOfAccount(dan)).slice( - 0, - MAX_NUMBER_OF_ITEMS_BY_DEFAULT, - ); - let proxyResponse = (await proxyProvider.getNonFungibleTokensOfAccount(dan)).slice( - 0, - MAX_NUMBER_OF_ITEMS_BY_DEFAULT, - ); - - assert.isTrue(apiResponse.length > 0, "For the sake of the test, there should be at least one item."); - assert.equal(apiResponse.length, proxyResponse.length); - - for (let i = 0; i < apiResponse.length; i++) { - removeInconsistencyForNonFungibleTokenOfAccount(apiResponse[i], proxyResponse[i]); - } - - assert.deepEqual(apiResponse, proxyResponse); - - const item = apiResponse[0]; - let apiItemResponse = await apiProvider.getNonFungibleTokenOfAccount(dan, item.collection, item.nonce); - let proxyItemResponse = await proxyProvider.getNonFungibleTokenOfAccount(dan, item.collection, item.nonce); - - removeInconsistencyForNonFungibleTokenOfAccount(apiItemResponse, proxyItemResponse); - assert.deepEqual(apiResponse, proxyResponse, `user: ${dan.toBech32()}, token: ${item.identifier}`); - }); - - // TODO: Strive to have as little differences as possible between Proxy and API. - function removeInconsistencyForNonFungibleTokenOfAccount( - apiResponse: NonFungibleTokenOfAccountOnNetwork, - proxyResponse: NonFungibleTokenOfAccountOnNetwork, - ) { - // unset unconsistent fields - apiResponse.type = ""; - proxyResponse.type = ""; - apiResponse.name = ""; - proxyResponse.name = ""; - apiResponse.decimals = 0; - proxyResponse.decimals = 0; - } - it("should be able to send transaction(s)", async function () { this.timeout(5000); @@ -330,22 +263,6 @@ describe("test network providers on devnet: Proxy and API", function () { } }); - it("should have same response for getNonFungibleToken()", async function () { - this.timeout(10000); - - let tokens = [{ id: "TEST-37adcf", nonce: 1 }]; - - for (const token of tokens) { - let apiResponse = await apiProvider.getNonFungibleToken(token.id, token.nonce); - - assert.equal(apiResponse.collection, token.id); - - // TODO: Uncomment after implementing the function in the proxy provider. - // let proxyResponse = await proxyProvider.getNonFungibleToken(token.id, token.nonce); - // assert.deepEqual(apiResponse, proxyResponse); - } - }); - it("should have same response for queryContract()", async function () { this.timeout(10000); diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index c06f5708c..fe267ccdd 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -9,7 +9,6 @@ import { TransactionStatus } from "../transactionStatus"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; import { AccountOnNetwork, GuardianData } from "./accounts"; -import { BlockOnNetwork } from "./blockOnNetwork"; import { defaultAxiosConfig } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; @@ -21,6 +20,7 @@ import { AccountStorage, AccountStorageEntry, AwaitingOptions, + BlockOnNetwork, GetBlockArguments, TransactionCostEstimationResponse, } from "./resources"; @@ -218,27 +218,6 @@ export class ProxyNetworkProvider implements INetworkProvider { return tokens; } - async getFungibleTokenOfAccount( - address: Address, - tokenIdentifier: string, - ): Promise { - const response = await this.doGetGeneric(`address/${address.toBech32()}/esdt/${tokenIdentifier}`); - const tokenData = FungibleTokenOfAccountOnNetwork.fromHttpResponse(response.tokenData); - return tokenData; - } - - async getNonFungibleTokenOfAccount( - address: Address, - collection: string, - nonce: number, - ): Promise { - const response = await this.doGetGeneric( - `address/${address.toBech32()}/nft/${collection}/nonce/${nonce.valueOf()}`, - ); - const tokenData = NonFungibleTokenOfAccountOnNetwork.fromProxyHttpResponseByNonce(response.tokenData); - return tokenData; - } - async getTransactionStatus(txHash: string): Promise { const response = await this.doGetGeneric(`transaction/${txHash}/process-status`); const status = new TransactionStatus(response.status); @@ -286,10 +265,6 @@ export class ProxyNetworkProvider implements INetworkProvider { return definition; } - async getNonFungibleToken(_collection: string, _nonce: number): Promise { - throw new Error("Method not implemented."); - } - async doGetGeneric(resourceUrl: string): Promise { const response = await this.doGet(resourceUrl); return response; diff --git a/src/networkProviders/resources.ts b/src/networkProviders/resources.ts index e4ba375ec..4c03baa94 100644 --- a/src/networkProviders/resources.ts +++ b/src/networkProviders/resources.ts @@ -44,6 +44,69 @@ export class AccountStorage { } } +/** + * An object holding network status configuration parameters. + */ +export class BlockOnNetwork { + /** + * The raw data return by provider. + */ + public raw: Record = {}; + + /** + * The shard number. + */ + public shard: number = 0; + + /** + * The shard nonce. + */ + public nonce: bigint = 0n; + + /** + * The block hash. + */ + public hash: string = ""; + + /** + * The block previous hash. + */ + public previousHash: string = ""; + + /** + * The block timestamp. + */ + public timestamp: number = 0; + + /** + * The block timestamp. + */ + public round: number = 0; + + /** + * The block timestamp. + */ + public epoch: number = 0; + + /** + * Constructs a configuration object from a HTTP response (as returned by the provider). + */ + static fromHttpResponse(payload: any): BlockOnNetwork { + let blockOnNetwork = new BlockOnNetwork(); + + blockOnNetwork.raw = payload; + blockOnNetwork.shard = Number(payload["shard"]) ?? 0; + blockOnNetwork.nonce = BigInt(payload["nonce"] ?? 0); + blockOnNetwork.hash = payload["hash"]; + blockOnNetwork.previousHash = payload["prevBlockHash"] ?? payload["prevHash"] ?? ""; + blockOnNetwork.timestamp = Number(payload["timestamp"] ?? 0); + blockOnNetwork.round = Number(payload["round"] ?? 0); + blockOnNetwork.epoch = Number(payload["epoch"] ?? 0); + + return blockOnNetwork; + } +} + export class BlockCoordinates { nonce: bigint = 0n; hash: string = ""; diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 18af52ab7..2e7a6964a 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -12,12 +12,12 @@ import { NetworkStatus, NonFungibleTokenOfAccountOnNetwork, } from "../networkProviders"; -import { BlockOnNetwork } from "../networkProviders/blockOnNetwork"; import { INetworkProvider, IPagination } from "../networkProviders/interface"; import { AccountStorage, AccountStorageEntry, AwaitingOptions, + BlockOnNetwork, TransactionCostEstimationResponse, } from "../networkProviders/resources"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; @@ -113,16 +113,6 @@ export class MockNetworkProvider implements INetworkProvider { ): Promise { throw new Error("Method not implemented."); } - getFungibleTokenOfAccount(_address: Address, _tokenIdentifier: string): Promise { - throw new Error("Method not implemented."); - } - getNonFungibleTokenOfAccount( - _address: Address, - _collection: string, - _nonce: number, - ): Promise { - throw new Error("Method not implemented."); - } sendTransactions(_txs: Transaction[]): Promise { throw new Error("Method not implemented."); } @@ -132,9 +122,6 @@ export class MockNetworkProvider implements INetworkProvider { getDefinitionOfTokenCollection(_collection: string): Promise { throw new Error("Method not implemented."); } - getNonFungibleToken(_collection: string, _nonce: number): Promise { - throw new Error("Method not implemented."); - } doGetGeneric(_resourceUrl: string): Promise { throw new Error("Method not implemented."); } From 761069eaae46372ee51eedadc8dd4bc04e90e1bb Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 15 Jan 2025 16:29:13 +0200 Subject: [PATCH 110/214] Add proxy provider tests --- src/networkProviders/accounts.ts | 51 +++++++- src/networkProviders/apiNetworkProvider.ts | 22 ++-- src/networkProviders/interface.ts | 11 +- .../proxyNetworkProvider.dev.net.spec.ts | 112 ++++++++++++++++++ src/networkProviders/proxyNetworkProvider.ts | 36 ++---- src/networkProviders/resources.ts | 58 ++++++--- src/testutils/mockNetworkProvider.ts | 15 +-- 7 files changed, 231 insertions(+), 74 deletions(-) create mode 100644 src/networkProviders/proxyNetworkProvider.dev.net.spec.ts diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index 086885d89..4f564f282 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -1,3 +1,4 @@ +import { CodeMetadata } from "../abi"; import { Address } from "../address"; /** @@ -7,22 +8,66 @@ export class AccountOnNetwork { address: Address = Address.empty(); nonce: bigint = 0n; balance: bigint = 0n; - code: string = ""; userName: string = ""; + contractCodeHash?: string; + contractCode?: Uint8Array; + contractDeveloperReward?: bigint; + contractOwnerAddress?: Address; + + isContractUpgradable?: boolean; + isContractReadable?: boolean; + isContractPayable?: boolean; + isContractPayableByContract?: boolean; + + isGuarded: boolean = false; + constructor(init?: Partial) { Object.assign(this, init); } - static fromHttpResponse(payload: any): AccountOnNetwork { + static fromApiHttpResponse(payload: any): AccountOnNetwork { let result = new AccountOnNetwork(); result.address = new Address(payload["address"] || ""); result.nonce = BigInt(payload["nonce"] || 0); result.balance = BigInt(payload["balance"] || 0); - result.code = payload["code"] || ""; result.userName = payload["username"] || ""; + result.contractCodeHash = payload["codeHash"] || ""; + result.contractCode = Buffer.from(payload["code"] || ""); + result.contractDeveloperReward = payload["developerReward"] || 0n; + result.contractOwnerAddress = new Address(payload["ownerAddress"] || ""); + result.isContractUpgradable = Boolean(payload["isUpgradeable"]); + result.isContractReadable = Boolean(payload["isReadable"]); + result.isContractPayable = Boolean(payload["isPayable"]); + result.isContractPayableByContract = Boolean(payload["isPayableBySmartContract"]); + result.isGuarded = Boolean(payload["isGuarded"]); + return result; + } + + static fromProxyHttpResponse(payload: any): AccountOnNetwork { + let result = new AccountOnNetwork(); + + result.address = payload["address"] ? new Address(payload["address"]) : Address.empty(); + result.nonce = BigInt(payload["nonce"] || 0); + result.balance = BigInt(payload["balance"] || 0); + result.userName = payload["username"] || undefined; + + const codeMetadata = payload["codeMetadata"] ?? null; + if (codeMetadata) { + const metadataBuffer = Buffer.from(codeMetadata, "base64"); + const metadata = CodeMetadata.newFromBytes(metadataBuffer); + result.isContractUpgradable = metadata.upgradeable; + result.isContractReadable = metadata.readable; + result.isContractPayable = metadata.payable; + result.isContractPayableByContract = metadata.payableBySc; + } + result.contractCodeHash = payload["codeHash"] || ""; + result.contractCode = Buffer.from(payload["code"] || ""); + result.contractDeveloperReward = payload["developerReward"] || 0n; + result.contractOwnerAddress = payload["ownerAddress"] ? new Address(payload["ownerAddress"]) : undefined; + result.isGuarded = Boolean(payload["isGuarded"]); return result; } } diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index b5587e493..045418fb1 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -23,10 +23,10 @@ import { AwaitingOptions, BlockOnNetwork, GetBlockArguments, + TokenAmountOnNetwork, TransactionCostEstimationResponse, } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; -import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; import { extendUserAgentIfBackend } from "./userAgent"; // TODO: Find & remove duplicate code between "ProxyNetworkProvider" and "ApiNetworkProvider". @@ -72,7 +72,7 @@ export class ApiNetworkProvider implements INetworkProvider { async getAccount(address: Address): Promise { const response = await this.doGetGeneric(`accounts/${address.toBech32()}`); - const account = AccountOnNetwork.fromHttpResponse(response); + const account = AccountOnNetwork.fromApiHttpResponse(response); return account; } @@ -155,7 +155,7 @@ export class ApiNetworkProvider implements INetworkProvider { } //TODO check this - async getTokenOfAccount(address: Address, token: Token): Promise { + async getTokenOfAccount(address: Address, token: Token): Promise { let response; if (token.nonce === 0n) { response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${token.identifier}`); @@ -164,34 +164,28 @@ export class ApiNetworkProvider implements INetworkProvider { `accounts/${address.toBech32()}/nfts/${token.identifier}/nonce/${token.nonce}`, ); } - return FungibleTokenOfAccountOnNetwork.fromHttpResponse(response); + return TokenAmountOnNetwork.fromApiResponse(response); } async getGuardianData(address: Address): Promise { return await this.backingProxyNetworkProvider.getGuardianData(address); } - async getFungibleTokensOfAccount( - address: Address, - pagination?: IPagination, - ): Promise { + async getFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise { pagination = pagination || defaultPagination; const url = `accounts/${address.toBech32()}/tokens?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); - const tokens = response.map((item) => FungibleTokenOfAccountOnNetwork.fromHttpResponse(item)); + const tokens = response.map((item) => TokenAmountOnNetwork.fromApiResponse(item)); return tokens; } - async getNonFungibleTokensOfAccount( - address: Address, - pagination?: IPagination, - ): Promise { + async getNonFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise { pagination = pagination || defaultPagination; const url = `accounts/${address.toBech32()}/nfts?${this.buildPaginationParams(pagination)}`; const response: any[] = await this.doGetGeneric(url); - const tokens = response.map((item) => NonFungibleTokenOfAccountOnNetwork.fromApiHttpResponse(item)); + const tokens = response.map((item) => TokenAmountOnNetwork.fromApiResponse(item)); return tokens; } diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index a4bbb96bc..9f8f640bd 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -12,10 +12,10 @@ import { AwaitingOptions, BlockOnNetwork, GetBlockArguments, + TokenAmountOnNetwork, TransactionCostEstimationResponse, } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; -import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; /** * An interface that defines the endpoints of an HTTP API Provider. @@ -115,20 +115,17 @@ export interface INetworkProvider { /** * Fetches the balance of an account, for a given token. */ - getTokenOfAccount(address: Address, token: Token): Promise; + getTokenOfAccount(address: Address, token: Token): Promise; /** * Fetches data about the fungible tokens held by an account. */ - getFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise; + getFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise; /** * Fetches data about the non-fungible tokens held by account. */ - getNonFungibleTokensOfAccount( - address: Address, - pagination?: IPagination, - ): Promise; + getNonFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise; /** * Fetches the definition of a fungible token. diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts new file mode 100644 index 000000000..86c0e5674 --- /dev/null +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -0,0 +1,112 @@ +import { assert, expect } from "chai"; +import { Address } from "../address"; +import { ProxyNetworkProvider } from "./proxyNetworkProvider"; + +describe("ProxyNetworkProvider Tests", () => { + const proxy = new ProxyNetworkProvider("https://devnet-gateway.multiversx.com"); + + it("should fetch network configuration", async () => { + const result = await proxy.getNetworkConfig(); + assert.equal(result.ChainID, "D"); + assert.equal(result.GasPerDataByte, 1500); + assert.equal(result.RoundDuration, 6000); + assert.equal(result.MinGasLimit, 50000); + assert.equal(result.MinGasPrice, 1_000_000_000); + }); + + it("should fetch network status", async () => { + const result = await proxy.getNetworkStatus(); + assert.exists(result.Nonce); + assert.exists(result.CurrentRound); + assert.exists(result.HighestFinalNonce); + }); + + it("should fetch block details by hash and nonce", async () => { + const shard = 1; + const blockHash = "ded535cc0afb2dc5f9787e9560dc48d0b83564a3f994a390b228d894d854699f"; + const resultByHash = await proxy.getBlock({ shard, blockHash }); + + const blockNonce = 5949242n; + const resultByNonce = await proxy.getBlock({ shard, blockNonce }); + + assert.equal(resultByHash.hash, blockHash); + assert.equal(resultByHash.nonce, 5949242n); + assert.equal(resultByHash.shard, 1); + assert.equal(resultByHash.timestamp, 1730112578); + assert.deepEqual(resultByHash, resultByNonce); + }); + + it("should fetch the latest block", async () => { + const result = await proxy.getLatestBlock(); + expect(result).to.exist; + }); + + it("should fetch account details", async () => { + const address1 = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + const result1 = await proxy.getAccount(address1); + + assert.equal(result1.address.toBech32(), "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + assert.isUndefined(result1.userName); + assert.isUndefined(result1.contractOwnerAddress); + + const address2 = Address.newFromBech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"); + const result2 = await proxy.getAccount(address2); + + assert.equal(result2.address.toBech32(), "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"); + assert.isUndefined(result2.userName); + assert.equal( + result2.contractOwnerAddress?.toBech32(), + "erd1wzx0tak22f2me4g7wpxfae2w3htfue7khrg28fy6wu8x9hzq05vqm8qhnm", + ); + assert.isFalse(result2.isContractPayable); + assert.isTrue(result2.isContractReadable); + }); + + it("should fetch account storage", async () => { + const address = Address.newFromBech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"); + const result = await proxy.getAccountStorage(address); + + assert.equal(result.entries.length, 1); + assert.equal(result.entries[0].key, "sum"); + assert.exists(result.entries[0].value); + }); + + it("should fetch a storage entry for an account", async () => { + const address = Address.newFromBech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"); + const result = await proxy.getAccountStorageEntry(address, "sum"); + + assert.equal(result.key, "sum"); + assert.exists(result.value); + }); + + it("should fetch fungible tokens of an account", async () => { + const address = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + const tokens = await proxy.getFungibleTokensOfAccount(address); + assert.isTrue(tokens.length > 0); + + const filtered = tokens.filter((token) => token.token.identifier === "TEST-ff155e"); + assert.equal(filtered.length, 1); + assert.equal(filtered[0].token.identifier, "TEST-ff155e"); + assert.equal(filtered[0].amount.toString(), "99999999999980000"); + }); + + it("should fetch non-fungible tokens of an account", async () => { + const address = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + const tokens = await proxy.getNonFungibleTokensOfAccount(address); + assert.isTrue(tokens.length > 0); + + const filtered = tokens.filter((token) => token.token.identifier === "NFTEST-ec88b8-01"); + assert.equal(filtered.length, 1); + assert.equal(filtered[0].token.identifier, "NFTEST-ec88b8-01"); + assert.equal(filtered[0].token.nonce, 1n); + assert.equal(filtered[0].amount, 1n); + }); + + it("should fetch transaction status", async () => { + const txHash = "9d47c4b4669cbcaa26f5dec79902dd20e55a0aa5f4b92454a74e7dbd0183ad6c"; + const result = await proxy.getTransactionStatus(txHash); + expect(result.status).to.equal("success"); + }); + + // Additional tests would follow the same pattern, adjusting for async/await where needed. +}); diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index fe267ccdd..701a75db5 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -22,10 +22,10 @@ import { AwaitingOptions, BlockOnNetwork, GetBlockArguments, + TokenAmountOnNetwork, TransactionCostEstimationResponse, } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; -import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; import { extendUserAgentIfBackend } from "./userAgent"; // TODO: Find & remove duplicate code between "ProxyNetworkProvider" and "ApiNetworkProvider". @@ -54,16 +54,16 @@ export class ProxyNetworkProvider implements INetworkProvider { return networkStatus; } async getBlock(blockArgs: GetBlockArguments): Promise { - let response = {}; + let response; if (blockArgs.blockHash) { response = await this.doGetGeneric(`block/${blockArgs.shard}/by-hash/${blockArgs.blockHash}`); } else if (blockArgs.blockNonce) { response = await this.doGetGeneric(`block/${blockArgs.shard}/by-nonce/${blockArgs.blockNonce}`); } else throw new Error("Block hash or block nonce not provided."); - return BlockOnNetwork.fromHttpResponse(response); + return BlockOnNetwork.fromHttpResponse(response.block); } - async getLatestBlock(shard: number): Promise { + async getLatestBlock(shard: number = METACHAIN_ID): Promise { const blockNonce = (await this.getNetworkStatus(shard)).Nonce; const response = await this.doGetGeneric(`block/${shard}/by-nonce/${blockNonce}`); return BlockOnNetwork.fromHttpResponse(response); @@ -71,7 +71,7 @@ export class ProxyNetworkProvider implements INetworkProvider { async getAccount(address: Address): Promise { const response = await this.doGetGeneric(`address/${address.toBech32()}`); - const account = AccountOnNetwork.fromHttpResponse(response.account); + const account = AccountOnNetwork.fromProxyHttpResponse(response.account); return account; } @@ -89,7 +89,7 @@ export class ProxyNetworkProvider implements INetworkProvider { async getAccountStorageEntry(address: Address, entryKey: string): Promise { const keyAsHex = Buffer.from(entryKey).toString("hex"); - const response = await this.doGetGeneric(`address/${address.toBech32()}/keys/${keyAsHex}`); + const response = await this.doGetGeneric(`address/${address.toBech32()}/key/${keyAsHex}`); const account = AccountStorageEntry.fromHttpResponse(response, entryKey); return account; } @@ -172,7 +172,7 @@ export class ProxyNetworkProvider implements INetworkProvider { return await awaiter.awaitCompleted(transactionHash); } - async getTokenOfAccount(address: Address, token: Token): Promise { + async getTokenOfAccount(address: Address, token: Token): Promise { let response; if (token.nonce === 0n) { response = await this.doGetGeneric(`address/${address.toBech32()}/esdt/${token.identifier}`); @@ -181,40 +181,28 @@ export class ProxyNetworkProvider implements INetworkProvider { `address/${address.toBech32()}/nft/${token.identifier}/nonce/${token.nonce}`, ); } - return FungibleTokenOfAccountOnNetwork.fromHttpResponse(response); + return TokenAmountOnNetwork.fromProxyResponse(response); } - async getFungibleTokensOfAccount( - address: Address, - _pagination?: IPagination, - ): Promise { + async getFungibleTokensOfAccount(address: Address, _pagination?: IPagination): Promise { const url = `address/${address.toBech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); // Skip NFTs / SFTs. const responseItemsFiltered = responseItems.filter((item) => !item.nonce); - const tokens = responseItemsFiltered.map((item) => FungibleTokenOfAccountOnNetwork.fromHttpResponse(item)); + const tokens = responseItemsFiltered.map((item) => TokenAmountOnNetwork.fromProxyResponse(item)); - // TODO: Fix sorting - tokens.sort((a, b) => a.identifier.localeCompare(b.identifier)); return tokens; } - async getNonFungibleTokensOfAccount( - address: Address, - _pagination?: IPagination, - ): Promise { + async getNonFungibleTokensOfAccount(address: Address, _pagination?: IPagination): Promise { const url = `address/${address.toBech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); // Skip fungible tokens. const responseItemsFiltered = responseItems.filter((item) => item.nonce >= 0); - const tokens = responseItemsFiltered.map((item) => - NonFungibleTokenOfAccountOnNetwork.fromProxyHttpResponse(item), - ); + const tokens = responseItemsFiltered.map((item) => TokenAmountOnNetwork.fromProxyResponse(item)); - // TODO: Fix sorting - tokens.sort((a, b) => a.identifier.localeCompare(b.identifier)); return tokens; } diff --git a/src/networkProviders/resources.ts b/src/networkProviders/resources.ts index 4c03baa94..63196fa57 100644 --- a/src/networkProviders/resources.ts +++ b/src/networkProviders/resources.ts @@ -1,5 +1,6 @@ import { BytesValue } from "../abi"; import { Address } from "../address"; +import { Token } from "../tokens"; import { TransactionStatus } from "../transactionStatus"; import { DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS, @@ -22,20 +23,17 @@ export class AccountStorage { let result = new AccountStorage(); const pairs = payload["pairs"] || {}; - const entries: AccountStorageEntry[] = []; - - for (const element of pairs.items) { - const decodedKey = BytesValue.fromHex(element.key).toString(); - const decodedValue = BytesValue.fromHex(element.value); - entries.push( - new AccountStorageEntry({ - raw: { key: element.value }, - key: decodedKey, - value: decodedValue.toString(), - }), - ); - } - + const entries: AccountStorageEntry[] = Object.entries(pairs).map(([key, value]) => { + const decodedKey = Buffer.from(key, "hex").toString("utf8"); + const val: string = value ? (value as string).toString() : ""; + const decodedValue = Buffer.from(val).toString(); + + return new AccountStorageEntry({ + raw: { [key]: value }, + key: decodedKey, + value: decodedValue, + }); + }); result.raw = payload; result.entries = entries; result.blockCoordinates = BlockCoordinates.fromHttpResponse(payload); @@ -97,7 +95,7 @@ export class BlockOnNetwork { blockOnNetwork.raw = payload; blockOnNetwork.shard = Number(payload["shard"]) ?? 0; blockOnNetwork.nonce = BigInt(payload["nonce"] ?? 0); - blockOnNetwork.hash = payload["hash"]; + blockOnNetwork.hash = payload["hash"] ?? ""; blockOnNetwork.previousHash = payload["prevBlockHash"] ?? payload["prevHash"] ?? ""; blockOnNetwork.timestamp = Number(payload["timestamp"] ?? 0); blockOnNetwork.round = Number(payload["round"] ?? 0); @@ -177,3 +175,33 @@ export class GetBlockArguments { Object.assign(this, init); } } + +export class TokenAmountOnNetwork { + raw: Record = {}; + token: Token = new Token({ identifier: "" }); + amount: bigint = 0n; + block_coordinates?: BlockCoordinates; + constructor(init?: Partial) { + Object.assign(this, init); + } + + static fromProxyResponse(payload: any): TokenAmountOnNetwork { + const result = new TokenAmountOnNetwork(); + + result.raw = payload; + result.amount = BigInt(payload["balance"] ?? 0); + result.token = new Token({ identifier: payload["tokenIdentifier"] ?? "", nonce: payload["nonce"] ?? 0 }); + + return result; + } + + static fromApiResponse(payload: any): TokenAmountOnNetwork { + const result = new TokenAmountOnNetwork(); + + result.raw = payload; + result.amount = BigInt(payload["balance"] ?? 0); + result.token = new Token({ identifier: payload["identifier"] ?? "", nonce: payload["nonce"] ?? 0 }); + + return result; + } +} diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 2e7a6964a..fb14354ea 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -7,10 +7,8 @@ import { AccountOnNetwork, DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork, - FungibleTokenOfAccountOnNetwork, NetworkConfig, NetworkStatus, - NonFungibleTokenOfAccountOnNetwork, } from "../networkProviders"; import { INetworkProvider, IPagination } from "../networkProviders/interface"; import { @@ -18,6 +16,7 @@ import { AccountStorageEntry, AwaitingOptions, BlockOnNetwork, + TokenAmountOnNetwork, TransactionCostEstimationResponse, } from "../networkProviders/resources"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; @@ -94,23 +93,17 @@ export class MockNetworkProvider implements INetworkProvider { awaitTransactionCompleted(_transactionHash: string, _options?: AwaitingOptions): Promise { throw new Error("Method not implemented."); } - getTokenOfAccount(_address: Address, _token: Token): Promise { + getTokenOfAccount(_address: Address, _token: Token): Promise { throw new Error("Method not implemented."); } getNetworkStatus(): Promise { throw new Error("Method not implemented."); } - getFungibleTokensOfAccount( - _address: Address, - _pagination?: IPagination, - ): Promise { + getFungibleTokensOfAccount(_address: Address, _pagination?: IPagination): Promise { throw new Error("Method not implemented."); } - getNonFungibleTokensOfAccount( - _address: Address, - _pagination?: IPagination, - ): Promise { + getNonFungibleTokensOfAccount(_address: Address, _pagination?: IPagination): Promise { throw new Error("Method not implemented."); } sendTransactions(_txs: Transaction[]): Promise { From 86aed286e0205fe6226ffc8686e96081106b46cb Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 16 Jan 2025 13:28:16 +0200 Subject: [PATCH 111/214] Add proxy provider tests --- .../proxyNetworkProvider.dev.net.spec.ts | 290 +++++++++++++++++- src/networkProviders/proxyNetworkProvider.ts | 7 +- 2 files changed, 290 insertions(+), 7 deletions(-) diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 86c0e5674..27ec55ab8 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -1,8 +1,15 @@ import { assert, expect } from "chai"; import { Address } from "../address"; +import { SmartContractQuery } from "../smartContractQuery"; +import { loadTestWallet } from "../testutils/wallets"; +import { Token } from "../tokens"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { TransactionStatus } from "../transactionStatus"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; -describe("ProxyNetworkProvider Tests", () => { +describe.only("ProxyNetworkProvider Tests", () => { const proxy = new ProxyNetworkProvider("https://devnet-gateway.multiversx.com"); it("should fetch network configuration", async () => { @@ -79,6 +86,20 @@ describe("ProxyNetworkProvider Tests", () => { assert.exists(result.value); }); + it("should fetch token of an account", async () => { + const address = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + let token = await proxy.getTokenOfAccount(address, new Token({ identifier: "TEST-ff155e" })); + + assert.equal(token.token.identifier, "TEST-ff155e"); + assert.equal(token.amount, 99999999999980000n); + + token = await proxy.getTokenOfAccount(address, new Token({ identifier: "NFTEST-ec88b8", nonce: 1n })); + + assert.equal(token.token.identifier, "NFTEST-ec88b8"); + assert.equal(token.amount, 1n); + assert.equal(token.token.nonce, 1n); + }); + it("should fetch fungible tokens of an account", async () => { const address = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); const tokens = await proxy.getFungibleTokensOfAccount(address); @@ -102,11 +123,274 @@ describe("ProxyNetworkProvider Tests", () => { assert.equal(filtered[0].amount, 1n); }); + it("should fetch definition of fungible token", async () => { + const token = await proxy.getDefinitionOfFungibleToken("TEST-ff155e"); + + assert.equal(token.identifier, "TEST-ff155e"); + assert.equal(token.owner.toBech32(), "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + assert.equal(token.decimals, 6); + }); + + it("should fetch definition of token collection", async () => { + const token = await proxy.getDefinitionOfTokenCollection("NFTEST-ec88b8"); + + assert.equal(token.collection, "NFTEST-ec88b8"); + assert.equal(token.owner.toBech32(), "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + assert.equal(token.type, "NonFungibleESDT"); + assert.equal(token.decimals, 0); + }); + + it("should fetch transaction", async () => { + const transaction = await proxy.getTransaction( + "9d47c4b4669cbcaa26f5dec79902dd20e55a0aa5f4b92454a74e7dbd0183ad6c", + ); + + assert.equal(transaction.nonce, 0n); + assert.equal(transaction.epoch, 348); + assert.equal(transaction.hash, "9d47c4b4669cbcaa26f5dec79902dd20e55a0aa5f4b92454a74e7dbd0183ad6c"); + assert.isTrue(transaction.status.isCompleted()); + assert.equal(transaction.sender.toBech32(), "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + assert.deepEqual(transaction.smartContractResults, []); + }); + + it("should fetch transaction with events", async () => { + const transaction = await proxy.getTransaction( + "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb", + ); + + assert.exists(transaction.logs); + assert.exists(transaction.logs.events); + assert.equal(transaction.logs.events.length, 2); + assert.equal(transaction.logs.events[0].topics.length, 8); + assert.equal(Buffer.from(transaction.logs.events[0].topics[0]).toString("hex"), "544553542d666631353565"); + assert.equal(Buffer.from(transaction.logs.events[0].topics[1]).toString("hex"), ""); + assert.equal(Buffer.from(transaction.logs.events[0].topics[2]).toString("hex"), "63616e4368616e67654f776e6572"); + assert.equal(transaction.hash, "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb"); + assert.isTrue(transaction.status.isCompleted()); + }); + + it("should fetch smart contract invoking transaction", async () => { + const transaction = await proxy.getTransaction( + "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb", + ); + + assert.isTrue(transaction.status.isCompleted()); + assert.isTrue(transaction.smartContractResults.length > 2); + assert.deepEqual( + transaction.data, + Buffer.from( + "issue@54455354546f6b656e@54455354@016345785d8a0000@06@63616e4368616e67654f776e6572@74727565@63616e55706772616465@74727565@63616e4164645370656369616c526f6c6573@74727565", + ), + ); + assert.equal(Buffer.from(transaction.logs.events[0].topics[0]).toString("hex"), "544553542d666631353565"); + assert.equal(Buffer.from(transaction.logs.events[0].topics[1]).toString("hex"), ""); + assert.equal(Buffer.from(transaction.logs.events[0].topics[2]).toString("hex"), "63616e4368616e67654f776e6572"); + assert.equal(transaction.hash, "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb"); + }); + + it("should send transaction", async () => { + const transaction = new Transaction({ + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 50000n, + chainID: "D", + value: 5000000000000000000n, + nonce: 100n, + gasPrice: 1000000000n, + version: 2, + signature: Buffer.from( + "faf50b8368cb2c20597dad671a14aa76d4c65937d6e522c64946f16ad6a250262463e444596fa7ee2af1273f6ad0329d43af48d1ae5f3b295bc8f48fdba41a05", + "hex", + ), + }); + + const expectedHash = "fc914860c1d137ed8baa602e561381f97c7bad80d150c5bf90760d3cfd3a4cea"; + assert.equal(await proxy.sendTransaction(transaction), expectedHash); + }); + + it("should send transaction with data", async () => { + const transaction = new Transaction({ + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 70000n, + chainID: "D", + value: 5000000000000000000n, + nonce: 105n, + gasPrice: 1000000000n, + version: 2, + data: new Uint8Array(Buffer.from("foo")), + signature: Buffer.from( + "7a8bd08351bac6b1113545f5a896cb0b63806abd93d639bc4d16bfbc82c7b514f68ed7b36c743f4c3d2d1e1d3cb356824041d51dfe587a149f6fc9ab0dd9c408", + "hex", + ), + }); + + const expectedHash = "fc914860c1d137ed8baa602e561381f97c7bad80d150c5bf90760d3cfd3a4cea"; + assert.equal(await proxy.sendTransaction(transaction), expectedHash); + }); + + it("should send transactions", async () => { + const firstTransaction = new Transaction({ + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 50000n, + chainID: "D", + value: 5000000000000000000n, + nonce: 103n, + gasPrice: 1000000000n, + version: 2, + signature: Buffer.from( + "498d5abb9f8eb69cc75f24320e8929dadbfa855ffac220d5e92175a83be68e0437801af3a1411e3d839738230097a1c38da5c8c4df3f345defc5d40300675900", + "hex", + ), + }); + const invalidTransaction = new Transaction({ + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 50000n, + chainID: "D", + nonce: 77n, + }); + + const lastTransaction = new Transaction({ + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 50000n, + chainID: "D", + value: 5000000000000000000n, + nonce: 104n, + gasPrice: 1000000000n, + version: 2, + signature: Buffer.from( + "341a2f3b738fbd20692e3bbd1cb36cb5f4ce9c0a9acc0cf4322269c0fcf34fd6bb59cd94062a9a4730e47f41b1ef3e29b69c6ab2a2a4dca9c9a7724681bc1708", + "hex", + ), + }); + + const transactions = [firstTransaction, invalidTransaction, lastTransaction]; + const expectedHashes = [ + "61b4f2561fc57bfb8b8971ed23cd64259b664bc0404ea7a0449def8ceef24b08", + "", + "30274b60b5635f981fa89ccfe726a34ca7121caa5d34123021c77a5c64cc9163", + ]; + const hashes = await proxy.sendTransactions(transactions); + assert.equal(hashes.length, 3); + assert.equal(hashes, expectedHashes); + }); + + it("should simulate transaction", async () => { + const bob = await loadTestWallet("bob"); + const transactionComputer = new TransactionComputer(); + let transaction = new Transaction({ + sender: bob.address, + receiver: bob.address, + gasLimit: 50000n, + chainID: "D", + signature: Buffer.from(Array(128).fill("0").join(""), "hex"), + }); + const nonce = (await proxy.getAccount(bob.address)).nonce; + transaction.nonce = nonce; + let txOnNetwork = await proxy.simulateTransaction(transaction); + assert.equal(txOnNetwork.status, new TransactionStatus("success")); + + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + txOnNetwork = await proxy.simulateTransaction(transaction); + + transaction = new Transaction({ + sender: bob.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"), + gasLimit: 10000000n, + chainID: "D", + gasPrice: 1000000000n, + version: 2, + data: new Uint8Array(Buffer.from("add@07")), + nonce: nonce, + signature: Buffer.from(Array(128).fill("0").join(""), "hex"), + }); + + txOnNetwork = await proxy.simulateTransaction(transaction); + assert.equal(txOnNetwork.smartContractResults.length, 1); + assert.equal( + txOnNetwork.smartContractResults[0].sender.toBech32(), + "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen", + ); + assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); + assert.equal(txOnNetwork.smartContractResults[0].data, Buffer.from("@6f6b", "base64")); + + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + txOnNetwork = await proxy.simulateTransaction(transaction); + + assert.equal(txOnNetwork.status, new TransactionStatus("success")); + assert.equal(txOnNetwork.smartContractResults.length, 1); + assert.equal( + txOnNetwork.smartContractResults[0].sender.toBech32(), + "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen", + ); + assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); + assert.equal(txOnNetwork.smartContractResults[0].data, Buffer.from("@6f6b", "base64")); + }); + + it("should estimate transaction cost", async () => { + const bob = await loadTestWallet("bob"); + const transactionComputer = new TransactionComputer(); + const transaction = new Transaction({ + sender: bob.address, + receiver: bob.address, + gasLimit: 50000n, + chainID: "D", + data: new Uint8Array(Buffer.from("test transaction")), + }); + transaction.nonce = (await proxy.getAccount(bob.address)).nonce; + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + const response = await proxy.estimateTransactionCost(transaction); + assert.equal(response.gasLimit, 74000); + }); + + it("should send and await for completed transaction", async () => { + const bob = await loadTestWallet("bob"); + const transactionComputer = new TransactionComputer(); + let transaction = new Transaction({ + sender: bob.address, + receiver: bob.address, + gasLimit: 50000n, + chainID: "D", + }); + const nonce = (await proxy.getAccount(bob.address)).nonce; + transaction.nonce = nonce; + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + let hash = await proxy.sendTransaction(transaction); + let transactionOnNetwork = await proxy.awaitTransactionCompleted(hash); + assert.isTrue(transactionOnNetwork.status.isCompleted()); + + transaction = new Transaction({ + sender: bob.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhdqz9j3zgpl8fg2z0jzx9n605gwxx4djd8ssruw094"), + gasLimit: 5000000n, + chainID: "D", + data: new Uint8Array(Buffer.from("dummy@05")), + }); + transaction.nonce = nonce + 1n; + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + const condition = (txOnNetwork: TransactionOnNetwork) => !txOnNetwork.status.isSuccessful(); + + hash = await proxy.sendTransaction(transaction); + transactionOnNetwork = await proxy.awaitTransactionOnCondition(hash, condition); + assert.isTrue(transactionOnNetwork.status.isSuccessful()); + }); + it("should fetch transaction status", async () => { const txHash = "9d47c4b4669cbcaa26f5dec79902dd20e55a0aa5f4b92454a74e7dbd0183ad6c"; const result = await proxy.getTransactionStatus(txHash); - expect(result.status).to.equal("success"); + assert.equal(result.status, "success"); }); - // Additional tests would follow the same pattern, adjusting for async/await where needed. + it("should query contract", async () => { + const query = new SmartContractQuery({ + contract: Address.newFromBech32("erd1qqqqqqqqqqqqqpgqqy34h7he2ya6qcagqre7ur7cc65vt0mxrc8qnudkr4"), + function: "getSum", + arguments: [], + }); + const result = await proxy.queryContract(query); + assert.equal(result.returnDataParts.length, 1); + }); }); diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 701a75db5..80abb627b 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -111,10 +111,10 @@ export class ProxyNetworkProvider implements INetworkProvider { return response.txHash; } - async simulateTransaction(tx: Transaction): Promise { + async simulateTransaction(tx: Transaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transaction/simulate", transaction); - return response; + return TransactionOnNetwork.fromProxyHttpResponse("txHash", response.transaction); } async estimateTransactionCost(tx: Transaction): Promise { @@ -132,7 +132,6 @@ export class ProxyNetworkProvider implements INetworkProvider { for (let i = 0; i < txs.length; i++) { hashes[i] = response.txsHashes[i.toString()] || null; } - return hashes; } @@ -181,7 +180,7 @@ export class ProxyNetworkProvider implements INetworkProvider { `address/${address.toBech32()}/nft/${token.identifier}/nonce/${token.nonce}`, ); } - return TokenAmountOnNetwork.fromProxyResponse(response); + return TokenAmountOnNetwork.fromProxyResponse(response["tokenData"]); } async getFungibleTokensOfAccount(address: Address, _pagination?: IPagination): Promise { From 135012d4df51e13467219a2aaf26369ccdc7744b Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 16 Jan 2025 15:54:03 +0200 Subject: [PATCH 112/214] Add api provider tests --- src/networkProviders/accounts.ts | 6 +- .../apiNetworkProvider.dev.net.spec.ts | 382 ++++++++++++++++++ src/networkProviders/apiNetworkProvider.ts | 21 +- .../proxyNetworkProvider.dev.net.spec.ts | 90 ++--- src/networkProviders/proxyNetworkProvider.ts | 10 +- src/networkProviders/resources.ts | 1 - src/transactionOnNetwork.ts | 45 +++ 7 files changed, 494 insertions(+), 61 deletions(-) create mode 100644 src/networkProviders/apiNetworkProvider.dev.net.spec.ts diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index 4f564f282..74818ca19 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -29,15 +29,15 @@ export class AccountOnNetwork { static fromApiHttpResponse(payload: any): AccountOnNetwork { let result = new AccountOnNetwork(); - result.address = new Address(payload["address"] || ""); + result.address = payload["address"] ? new Address(payload["address"]) : Address.empty(); result.nonce = BigInt(payload["nonce"] || 0); result.balance = BigInt(payload["balance"] || 0); - result.userName = payload["username"] || ""; + result.userName = payload["username"] || undefined; result.contractCodeHash = payload["codeHash"] || ""; result.contractCode = Buffer.from(payload["code"] || ""); result.contractDeveloperReward = payload["developerReward"] || 0n; - result.contractOwnerAddress = new Address(payload["ownerAddress"] || ""); + result.contractOwnerAddress = payload["ownerAddress"] ? new Address(payload["ownerAddress"]) : undefined; result.isContractUpgradable = Boolean(payload["isUpgradeable"]); result.isContractReadable = Boolean(payload["isReadable"]); result.isContractPayable = Boolean(payload["isPayable"]); diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts new file mode 100644 index 000000000..7ba8222d0 --- /dev/null +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -0,0 +1,382 @@ +import { assert, expect } from "chai"; +import { Address } from "../address"; +import { SmartContractQuery } from "../smartContractQuery"; +import { loadTestWallet } from "../testutils/wallets"; +import { Token } from "../tokens"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { TransactionStatus } from "../transactionStatus"; +import { ApiNetworkProvider } from "./apiNetworkProvider"; + +describe.only("ApiNetworkProvider Tests", () => { + const apiProvider = new ApiNetworkProvider("https://devnet-api.multiversx.com"); + + it("should fetch network configuration", async () => { + const result = await apiProvider.getNetworkConfig(); + assert.equal(result.ChainID, "D"); + assert.equal(result.GasPerDataByte, 1500); + assert.equal(result.RoundDuration, 6000); + assert.equal(result.MinGasLimit, 50000); + assert.equal(result.MinGasPrice, 1_000_000_000); + }); + + it("should fetch network status", async () => { + const result = await apiProvider.getNetworkStatus(); + assert.exists(result.Nonce); + assert.exists(result.CurrentRound); + assert.exists(result.HighestFinalNonce); + }); + + it("should fetch block details by hash and nonce", async () => { + const blockHash = "ded535cc0afb2dc5f9787e9560dc48d0b83564a3f994a390b228d894d854699f"; + const resultByHash = await apiProvider.getBlock({ blockHash }); + + assert.equal(resultByHash.hash, blockHash); + assert.equal(resultByHash.nonce, 5949242n); + assert.equal(resultByHash.shard, 1); + assert.equal(resultByHash.timestamp, 1730112578); + }); + + it("should fetch the latest block", async () => { + const result = await apiProvider.getLatestBlock(); + expect(result).to.exist; + }); + + it("should fetch account details", async () => { + const address1 = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + const result1 = await apiProvider.getAccount(address1); + + assert.equal(result1.address.toBech32(), "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + assert.isUndefined(result1.userName); + assert.isUndefined(result1.contractOwnerAddress); + + const address2 = Address.newFromBech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"); + const result2 = await apiProvider.getAccount(address2); + + assert.equal(result2.address.toBech32(), "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"); + assert.isUndefined(result2.userName); + assert.equal( + result2.contractOwnerAddress?.toBech32(), + "erd1wzx0tak22f2me4g7wpxfae2w3htfue7khrg28fy6wu8x9hzq05vqm8qhnm", + ); + assert.isFalse(result2.isContractPayable); + assert.isTrue(result2.isContractReadable); + }); + + it("should fetch account storage", async () => { + const address = Address.newFromBech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"); + const result = await apiProvider.getAccountStorage(address); + + assert.equal(result.entries.length, 1); + assert.equal(result.entries[0].key, "sum"); + assert.exists(result.entries[0].value); + }); + + it("should fetch a storage entry for an account", async () => { + const address = Address.newFromBech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"); + const result = await apiProvider.getAccountStorageEntry(address, "sum"); + + assert.equal(result.key, "sum"); + assert.exists(result.value); + }); + + it("should fetch token of an account", async () => { + const address = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + let token = await apiProvider.getTokenOfAccount(address, new Token({ identifier: "TEST-ff155e" })); + + assert.equal(token.token.identifier, "TEST-ff155e"); + assert.equal(token.amount, 99999999999980000n); + + token = await apiProvider.getTokenOfAccount(address, new Token({ identifier: "NFTEST-ec88b8", nonce: 1n })); + + assert.equal(token.token.identifier, "NFTEST-ec88b8-01"); + assert.equal(token.amount, 1n); + assert.equal(token.token.nonce, 1n); + }); + + it("should fetch fungible tokens of an account", async () => { + const address = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + const tokens = await apiProvider.getFungibleTokensOfAccount(address); + assert.isTrue(tokens.length > 0); + + const filtered = tokens.filter((token) => token.token.identifier === "TEST-ff155e"); + assert.equal(filtered.length, 1); + assert.equal(filtered[0].token.identifier, "TEST-ff155e"); + assert.equal(filtered[0].amount.toString(), "99999999999980000"); + }); + + it("should fetch non-fungible tokens of an account", async () => { + const address = Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + const tokens = await apiProvider.getNonFungibleTokensOfAccount(address); + assert.isTrue(tokens.length > 0); + + const filtered = tokens.filter((token) => token.token.identifier === "NFTEST-ec88b8-01"); + assert.equal(filtered.length, 1); + assert.equal(filtered[0].token.identifier, "NFTEST-ec88b8-01"); + assert.equal(filtered[0].token.nonce, 1n); + assert.equal(filtered[0].amount, 1n); + }); + + it("should fetch definition of fungible token", async () => { + const token = await apiProvider.getDefinitionOfFungibleToken("TEST-ff155e"); + + assert.equal(token.identifier, "TEST-ff155e"); + assert.equal(token.owner.toBech32(), "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + assert.equal(token.decimals, 6); + }); + + it("should fetch definition of token collection", async () => { + const token = await apiProvider.getDefinitionOfTokenCollection("NFTEST-ec88b8"); + + assert.equal(token.collection, "NFTEST-ec88b8"); + assert.equal(token.owner.toBech32(), "erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"); + assert.equal(token.type, "NonFungibleESDT"); + assert.equal(token.decimals, 0); + }); + + it("should fetch transaction", async () => { + const transaction = await apiProvider.getTransaction( + "9d47c4b4669cbcaa26f5dec79902dd20e55a0aa5f4b92454a74e7dbd0183ad6c", + ); + + assert.equal(transaction.nonce, 0n); + assert.equal(transaction.hash, "9d47c4b4669cbcaa26f5dec79902dd20e55a0aa5f4b92454a74e7dbd0183ad6c"); + assert.isTrue(transaction.status.isCompleted()); + assert.equal(transaction.sender.toBech32(), "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + assert.deepEqual(transaction.smartContractResults, []); + }); + + it("should fetch transaction with events", async () => { + const transaction = await apiProvider.getTransaction( + "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb", + ); + + assert.exists(transaction.logs); + assert.exists(transaction.logs.events); + assert.equal(transaction.logs.events.length, 2); + assert.equal(transaction.logs.events[0].topics.length, 8); + assert.equal(Buffer.from(transaction.logs.events[0].topics[0]).toString("hex"), "544553542d666631353565"); + assert.equal(Buffer.from(transaction.logs.events[0].topics[1]).toString("hex"), ""); + assert.equal(Buffer.from(transaction.logs.events[0].topics[2]).toString("hex"), "63616e4368616e67654f776e6572"); + assert.equal(transaction.hash, "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb"); + assert.isTrue(transaction.status.isCompleted()); + }); + + it("should fetch smart contract invoking transaction", async () => { + const transaction = await apiProvider.getTransaction( + "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb", + ); + + assert.isTrue(transaction.status.isCompleted()); + assert.isTrue(transaction.smartContractResults.length > 2); + assert.deepEqual( + transaction.data, + Buffer.from( + "issue@54455354546f6b656e@54455354@016345785d8a0000@06@63616e4368616e67654f776e6572@74727565@63616e55706772616465@74727565@63616e4164645370656369616c526f6c6573@74727565", + ), + ); + assert.equal(Buffer.from(transaction.logs.events[0].topics[0]).toString("hex"), "544553542d666631353565"); + assert.equal(Buffer.from(transaction.logs.events[0].topics[1]).toString("hex"), ""); + assert.equal(Buffer.from(transaction.logs.events[0].topics[2]).toString("hex"), "63616e4368616e67654f776e6572"); + assert.equal(transaction.hash, "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb"); + }); + + it("should send transaction", async () => { + const transaction = new Transaction({ + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 50000n, + chainID: "D", + value: 5000000000000000000n, + nonce: 100n, + gasPrice: 1000000000n, + version: 2, + signature: Buffer.from( + "faf50b8368cb2c20597dad671a14aa76d4c65937d6e522c64946f16ad6a250262463e444596fa7ee2af1273f6ad0329d43af48d1ae5f3b295bc8f48fdba41a05", + "hex", + ), + }); + + const expectedHash = "fc914860c1d137ed8baa602e561381f97c7bad80d150c5bf90760d3cfd3a4cea"; + assert.equal(await apiProvider.sendTransaction(transaction), expectedHash); + }); + + it("should send transaction with data", async () => { + const transaction = new Transaction({ + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 70000n, + chainID: "D", + nonce: 105n, + gasPrice: 1000000000n, + version: 2, + data: new Uint8Array(Buffer.from("foo")), + signature: Buffer.from( + "7a8bd08351bac6b1113545f5a896cb0b63806abd93d639bc4d16bfbc82c7b514f68ed7b36c743f4c3d2d1e1d3cb356824041d51dfe587a149f6fc9ab0dd9c408", + "hex", + ), + }); + + const expectedHash = "4dc7d4e18c0cf9ca7f17677ef0ac3d1363528e892996b518bee909bb17cf7929"; + assert.equal(await apiProvider.sendTransaction(transaction), expectedHash); + }); + + it("should send transactions", async () => { + const txs = [ + new Transaction({ + nonce: 103n, + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasPrice: 1000000000n, + gasLimit: 50000n, + chainID: "D", + version: 2, + signature: Buffer.from( + "498d5abb9f8eb69cc75f24320e8929dadbfa855ffac220d5e92175a83be68e0437801af3a1411e3d839738230097a1c38da5c8c4df3f345defc5d40300675900", + "hex", + ), + }), + new Transaction({ + nonce: 77n, + chainID: "D", + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 50000n, + gasPrice: 1000000000n, + }), + new Transaction({ + nonce: 104n, + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasPrice: 1000000000n, + gasLimit: 50000n, + chainID: "D", + version: 2, + signature: Buffer.from( + "341a2f3b738fbd20692e3bbd1cb36cb5f4ce9c0a9acc0cf4322269c0fcf34fd6bb59cd94062a9a4730e47f41b1ef3e29b69c6ab2a2a4dca9c9a7724681bc1708", + "hex", + ), + }), + ]; + + const expectedHashes = [ + "61b4f2561fc57bfb8b8971ed23cd64259b664bc0404ea7a0449def8ceef24b08", + null, + "30274b60b5635f981fa89ccfe726a34ca7121caa5d34123021c77a5c64cc9163", + ]; + const hashes = await apiProvider.sendTransactions(txs); + assert.equal(hashes.length, 3); + assert.deepEqual(hashes, expectedHashes); + }); + + it("should simulate transaction", async () => { + const bob = await loadTestWallet("bob"); + const transactionComputer = new TransactionComputer(); + let transaction = new Transaction({ + sender: bob.address, + receiver: bob.address, + gasLimit: 50000n, + chainID: "D", + signature: Buffer.from(Array(128).fill("0").join(""), "hex"), + }); + const nonce = (await apiProvider.getAccount(bob.address)).nonce; + transaction.nonce = nonce; + let txOnNetwork = await apiProvider.simulateTransaction(transaction); + assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); + + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + txOnNetwork = await apiProvider.simulateTransaction(transaction, true); + + transaction = new Transaction({ + sender: bob.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"), + gasLimit: 10000000n, + chainID: "D", + gasPrice: 1000000000n, + version: 2, + data: new Uint8Array(Buffer.from("add@07")), + nonce: nonce, + signature: Buffer.from(Array(128).fill("0").join(""), "hex"), + }); + + txOnNetwork = await apiProvider.simulateTransaction(transaction); + assert.equal(txOnNetwork.smartContractResults.length, 1); + assert.equal( + txOnNetwork.smartContractResults[0].sender.toBech32(), + "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen", + ); + assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); + assert.deepEqual(txOnNetwork.smartContractResults[0].data, "@6f6b"); + + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + txOnNetwork = await apiProvider.simulateTransaction(transaction, true); + + assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); + assert.equal(txOnNetwork.smartContractResults.length, 1); + assert.equal( + txOnNetwork.smartContractResults[0].sender.toBech32(), + "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen", + ); + assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); + assert.equal(txOnNetwork.smartContractResults[0].data, "@6f6b"); + }); + + it("should estimate transaction cost", async () => { + const bob = await loadTestWallet("bob"); + const transactionComputer = new TransactionComputer(); + const transaction = new Transaction({ + sender: bob.address, + receiver: bob.address, + gasLimit: 50000n, + chainID: "D", + data: new Uint8Array(Buffer.from("test transaction")), + }); + transaction.nonce = (await apiProvider.getAccount(bob.address)).nonce; + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + const response = await apiProvider.estimateTransactionCost(transaction); + assert.equal(response.gasLimit, 74000); + }); + + it("should send and await for completed transaction", async () => { + const bob = await loadTestWallet("bob"); + const transactionComputer = new TransactionComputer(); + let transaction = new Transaction({ + sender: bob.address, + receiver: bob.address, + gasLimit: 50000n, + chainID: "D", + }); + const nonce = (await apiProvider.getAccount(bob.address)).nonce; + transaction.nonce = nonce; + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + let hash = await apiProvider.sendTransaction(transaction); + let transactionOnNetwork = await apiProvider.awaitTransactionCompleted(hash); + assert.isTrue(transactionOnNetwork.status.isCompleted()); + + transaction = new Transaction({ + sender: bob.address, + receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhdqz9j3zgpl8fg2z0jzx9n605gwxx4djd8ssruw094"), + gasLimit: 5000000n, + chainID: "D", + data: new Uint8Array(Buffer.from("dummy@05")), + }); + transaction.nonce = nonce + 1n; + transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + const condition = (txOnNetwork: TransactionOnNetwork) => !txOnNetwork.status.isSuccessful(); + + hash = await apiProvider.sendTransaction(transaction); + transactionOnNetwork = await apiProvider.awaitTransactionOnCondition(hash, condition); + assert.isTrue(transactionOnNetwork.status.isSuccessful()); + }); + + it("should query contract", async () => { + const query = new SmartContractQuery({ + contract: Address.newFromBech32("erd1qqqqqqqqqqqqqpgqqy34h7he2ya6qcagqre7ur7cc65vt0mxrc8qnudkr4"), + function: "getSum", + arguments: [], + }); + const result = await apiProvider.queryContract(query); + assert.equal(result.returnDataParts.length, 1); + }); +}); diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 045418fb1..de09f54f5 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -65,8 +65,8 @@ export class ApiNetworkProvider implements INetworkProvider { return BlockOnNetwork.fromHttpResponse(response); } - async getLatestBlock(_shard: number): Promise { - const response = await this.doGetGeneric("block/latest"); + async getLatestBlock(_shard?: number): Promise { + const response = await this.doGetGeneric("blocks/latest"); return BlockOnNetwork.fromHttpResponse(response); } @@ -106,13 +106,20 @@ export class ApiNetworkProvider implements INetworkProvider { return response.txHash; } - async simulateTransaction(tx: Transaction): Promise { - return await this.backingProxyNetworkProvider.simulateTransaction(tx); + async simulateTransaction(tx: Transaction, checkSignature: boolean = false): Promise { + const transaction = prepareTransactionForBroadcasting(tx); + let url = "transaction/simulate?checkSignature=false"; + if (checkSignature) { + url = "transaction/simulate"; + } + const response = await this.doPostGeneric(url, transaction); + const data = response["data"] ?? {}; + return TransactionOnNetwork.fromSimulateResponse(transaction, data["result"] ?? {}); } async estimateTransactionCost(tx: Transaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transaction/cost", transaction); - return TransactionCostEstimationResponse.fromHttpResponse(response); + return TransactionCostEstimationResponse.fromHttpResponse(response.data); } async sendTransactions(txs: Transaction[]): Promise { @@ -160,9 +167,7 @@ export class ApiNetworkProvider implements INetworkProvider { if (token.nonce === 0n) { response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${token.identifier}`); } else { - response = await this.doGetGeneric( - `accounts/${address.toBech32()}/nfts/${token.identifier}/nonce/${token.nonce}`, - ); + response = await this.doGetGeneric(`accounts/${address.toBech32()}/nfts/${token.identifier}-01`); } return TokenAmountOnNetwork.fromApiResponse(response); } diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 27ec55ab8..43b866500 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -214,7 +214,6 @@ describe.only("ProxyNetworkProvider Tests", () => { receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), gasLimit: 70000n, chainID: "D", - value: 5000000000000000000n, nonce: 105n, gasPrice: 1000000000n, version: 2, @@ -225,57 +224,56 @@ describe.only("ProxyNetworkProvider Tests", () => { ), }); - const expectedHash = "fc914860c1d137ed8baa602e561381f97c7bad80d150c5bf90760d3cfd3a4cea"; + const expectedHash = "4dc7d4e18c0cf9ca7f17677ef0ac3d1363528e892996b518bee909bb17cf7929"; assert.equal(await proxy.sendTransaction(transaction), expectedHash); }); it("should send transactions", async () => { - const firstTransaction = new Transaction({ - sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), - receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), - gasLimit: 50000n, - chainID: "D", - value: 5000000000000000000n, - nonce: 103n, - gasPrice: 1000000000n, - version: 2, - signature: Buffer.from( - "498d5abb9f8eb69cc75f24320e8929dadbfa855ffac220d5e92175a83be68e0437801af3a1411e3d839738230097a1c38da5c8c4df3f345defc5d40300675900", - "hex", - ), - }); - const invalidTransaction = new Transaction({ - sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), - receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), - gasLimit: 50000n, - chainID: "D", - nonce: 77n, - }); - - const lastTransaction = new Transaction({ - sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), - receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), - gasLimit: 50000n, - chainID: "D", - value: 5000000000000000000n, - nonce: 104n, - gasPrice: 1000000000n, - version: 2, - signature: Buffer.from( - "341a2f3b738fbd20692e3bbd1cb36cb5f4ce9c0a9acc0cf4322269c0fcf34fd6bb59cd94062a9a4730e47f41b1ef3e29b69c6ab2a2a4dca9c9a7724681bc1708", - "hex", - ), - }); + const txs = [ + new Transaction({ + nonce: 103n, + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasPrice: 1000000000n, + gasLimit: 50000n, + chainID: "D", + version: 2, + signature: Buffer.from( + "498d5abb9f8eb69cc75f24320e8929dadbfa855ffac220d5e92175a83be68e0437801af3a1411e3d839738230097a1c38da5c8c4df3f345defc5d40300675900", + "hex", + ), + }), + new Transaction({ + nonce: 77n, + chainID: "D", + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasLimit: 50000n, + gasPrice: 1000000000n, + }), + new Transaction({ + nonce: 104n, + receiver: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), + gasPrice: 1000000000n, + gasLimit: 50000n, + chainID: "D", + version: 2, + signature: Buffer.from( + "341a2f3b738fbd20692e3bbd1cb36cb5f4ce9c0a9acc0cf4322269c0fcf34fd6bb59cd94062a9a4730e47f41b1ef3e29b69c6ab2a2a4dca9c9a7724681bc1708", + "hex", + ), + }), + ]; - const transactions = [firstTransaction, invalidTransaction, lastTransaction]; const expectedHashes = [ "61b4f2561fc57bfb8b8971ed23cd64259b664bc0404ea7a0449def8ceef24b08", - "", + null, "30274b60b5635f981fa89ccfe726a34ca7121caa5d34123021c77a5c64cc9163", ]; - const hashes = await proxy.sendTransactions(transactions); + const hashes = await proxy.sendTransactions(txs); assert.equal(hashes.length, 3); - assert.equal(hashes, expectedHashes); + assert.deepEqual(hashes, expectedHashes); }); it("should simulate transaction", async () => { @@ -291,7 +289,7 @@ describe.only("ProxyNetworkProvider Tests", () => { const nonce = (await proxy.getAccount(bob.address)).nonce; transaction.nonce = nonce; let txOnNetwork = await proxy.simulateTransaction(transaction); - assert.equal(txOnNetwork.status, new TransactionStatus("success")); + assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); txOnNetwork = await proxy.simulateTransaction(transaction); @@ -315,19 +313,19 @@ describe.only("ProxyNetworkProvider Tests", () => { "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen", ); assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); - assert.equal(txOnNetwork.smartContractResults[0].data, Buffer.from("@6f6b", "base64")); + assert.equal(txOnNetwork.smartContractResults[0].data, "@6f6b"); transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); txOnNetwork = await proxy.simulateTransaction(transaction); - assert.equal(txOnNetwork.status, new TransactionStatus("success")); + assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); assert.equal(txOnNetwork.smartContractResults.length, 1); assert.equal( txOnNetwork.smartContractResults[0].sender.toBech32(), "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen", ); assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); - assert.equal(txOnNetwork.smartContractResults[0].data, Buffer.from("@6f6b", "base64")); + assert.equal(txOnNetwork.smartContractResults[0].data, "@6f6b", "base64"); }); it("should estimate transaction cost", async () => { diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 80abb627b..253e679ce 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -111,10 +111,14 @@ export class ProxyNetworkProvider implements INetworkProvider { return response.txHash; } - async simulateTransaction(tx: Transaction): Promise { + async simulateTransaction(tx: Transaction, checkSignature: boolean = false): Promise { const transaction = prepareTransactionForBroadcasting(tx); - const response = await this.doPostGeneric("transaction/simulate", transaction); - return TransactionOnNetwork.fromProxyHttpResponse("txHash", response.transaction); + let url = "transaction/simulate?checkSignature=false"; + if (checkSignature) { + url = "transaction/simulate"; + } + const response = await this.doPostGeneric(url, transaction); + return TransactionOnNetwork.fromSimulateResponse(transaction, response["result"] ?? {}); } async estimateTransactionCost(tx: Transaction): Promise { diff --git a/src/networkProviders/resources.ts b/src/networkProviders/resources.ts index 63196fa57..45364d4f3 100644 --- a/src/networkProviders/resources.ts +++ b/src/networkProviders/resources.ts @@ -158,7 +158,6 @@ export class TransactionCostEstimationResponse { static fromHttpResponse(payload: any): TransactionCostEstimationResponse { const result = new TransactionCostEstimationResponse(); - result.raw = payload; result.gasLimit = payload["txGasUnits"] ?? 0; result.status = new TransactionStatus(""); diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 2b4746a42..4bd3d872f 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -88,6 +88,51 @@ export class TransactionOnNetwork { return result; } + static fromSimulateResponse(originalTx: Transaction, response: any): TransactionOnNetwork { + const status = new TransactionStatus(response["status"]); + const txHash = response["hash"] ?? ""; + const scResults: SmartContractResult[] = []; + const results = response["scResults"] || {}; + for (const hash in results) { + const result = results[hash]; + + const scResult = new SmartContractResult({ + ...result, + receiver: result.receiver ? new Address(result.receiver) : undefined, + sender: result.sender ? new Address(result.sender) : undefined, + raw: result, + }); + scResults.push(scResult); + } + + let result = new TransactionOnNetwork(); + result.hash = txHash; + result.type = response.type || ""; + result.nonce = BigInt(originalTx.nonce || 0); + result.round = -1n; + result.epoch = -1; + result.value = BigInt((originalTx.value || 0).toString()); + result.sender = new Address(originalTx.sender); + result.receiver = new Address(originalTx.receiver); + result.gasPrice = BigInt(originalTx.gasPrice) || 0n; + result.gasLimit = BigInt(originalTx.gasLimit) || 0n; + result.function = ""; + result.data = originalTx.data ? Buffer.from(originalTx.data?.toString()) : Buffer.from(""); + result.version = originalTx.version || 1; + result.options = originalTx.options || 0; + result.timestamp = 0; + result.miniblockHash = ""; + result.blockHash = ""; + result.logs = TransactionLogs.fromHttpResponse(response.logs || {}); + result.raw = response; + result.smartContractResults = scResults; + + result.status = status; + result.isCompleted = status.isSuccessful() || status.isFailed(); + + return result; + } + static fromApiHttpResponse(txHash: string, response: any): TransactionOnNetwork { let result = TransactionOnNetwork.fromHttpResponse(txHash, response); result.smartContractResults = From a9448f024613f2472db3ecfc7bccfd297dbfc677 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 16 Jan 2025 16:09:42 +0200 Subject: [PATCH 113/214] Fix failing tests --- src/networkProviders/apiNetworkProvider.dev.net.spec.ts | 9 +++++---- .../proxyNetworkProvider.dev.net.spec.ts | 7 ++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index 7ba8222d0..bcd44e714 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -9,7 +9,7 @@ import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { ApiNetworkProvider } from "./apiNetworkProvider"; -describe.only("ApiNetworkProvider Tests", () => { +describe.only("ApiNetworkProvider Tests", function () { const apiProvider = new ApiNetworkProvider("https://devnet-api.multiversx.com"); it("should fetch network configuration", async () => { @@ -322,7 +322,7 @@ describe.only("ApiNetworkProvider Tests", () => { assert.equal(txOnNetwork.smartContractResults[0].data, "@6f6b"); }); - it("should estimate transaction cost", async () => { + it("should estimate transaction cost", async function () { const bob = await loadTestWallet("bob"); const transactionComputer = new TransactionComputer(); const transaction = new Transaction({ @@ -338,7 +338,8 @@ describe.only("ApiNetworkProvider Tests", () => { assert.equal(response.gasLimit, 74000); }); - it("should send and await for completed transaction", async () => { + it("should send and await for completed transaction", async function () { + this.timeout(20000); const bob = await loadTestWallet("bob"); const transactionComputer = new TransactionComputer(); let transaction = new Transaction({ @@ -367,7 +368,7 @@ describe.only("ApiNetworkProvider Tests", () => { hash = await apiProvider.sendTransaction(transaction); transactionOnNetwork = await apiProvider.awaitTransactionOnCondition(hash, condition); - assert.isTrue(transactionOnNetwork.status.isSuccessful()); + assert.isFalse(transactionOnNetwork.status.isSuccessful()); }); it("should query contract", async () => { diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 43b866500..ba16c1539 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -9,7 +9,7 @@ import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; -describe.only("ProxyNetworkProvider Tests", () => { +describe.only("ProxyNetworkProvider Tests", function () { const proxy = new ProxyNetworkProvider("https://devnet-gateway.multiversx.com"); it("should fetch network configuration", async () => { @@ -328,7 +328,7 @@ describe.only("ProxyNetworkProvider Tests", () => { assert.equal(txOnNetwork.smartContractResults[0].data, "@6f6b", "base64"); }); - it("should estimate transaction cost", async () => { + it("should estimate transaction cost", async function () { const bob = await loadTestWallet("bob"); const transactionComputer = new TransactionComputer(); const transaction = new Transaction({ @@ -344,7 +344,8 @@ describe.only("ProxyNetworkProvider Tests", () => { assert.equal(response.gasLimit, 74000); }); - it("should send and await for completed transaction", async () => { + it("should send and await for completed transaction", async function () { + this.timeout(30000); const bob = await loadTestWallet("bob"); const transactionComputer = new TransactionComputer(); let transaction = new Transaction({ From 8855cb4ea80e67cb1c0eb42df55f4c7f1c783b7e Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 12:28:35 +0200 Subject: [PATCH 114/214] Fix integration test and skip proxy test that returns timeout --- src/abi/smartContract.local.net.spec.ts | 6 ++++-- src/networkProviders/proxyNetworkProvider.dev.net.spec.ts | 3 ++- src/transaction.local.net.spec.ts | 5 +++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 6a99bde98..bd83763bd 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -23,6 +23,8 @@ import { U32Value, } from "./typesystem"; +const JSONbig = require("json-bigint")({ constructorAction: "ignore" }); + describe("test on local testnet", function () { let alice: TestWallet, bob: TestWallet, carol: TestWallet; let provider = createLocalnetProvider(); @@ -122,8 +124,8 @@ describe("test on local testnet", function () { assert.isTrue(response.returnCode == "ok"); // Simulate - Logger.trace(JSON.stringify(await provider.simulateTransaction(simulateOne), null, 4)); - Logger.trace(JSON.stringify(await provider.simulateTransaction(simulateTwo), null, 4)); + Logger.trace(JSONbig.parse(await provider.simulateTransaction(simulateOne), null, 4)); + Logger.trace(JSONbig.parse(await provider.simulateTransaction(simulateTwo), null, 4)); }); it("counter: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index ba16c1539..aba5493ef 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -344,7 +344,8 @@ describe.only("ProxyNetworkProvider Tests", function () { assert.equal(response.gasLimit, 74000); }); - it("should send and await for completed transaction", async function () { + //TODO Investigate why this returns timeout + it.skip("should send and await for completed transaction", async function () { this.timeout(30000); const bob = await loadTestWallet("bob"); const transactionComputer = new TransactionComputer(); diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 4e8c72596..8babf176d 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -114,6 +114,7 @@ describe("test transaction", function () { it("should simulate transactions", async function () { this.timeout(20000); + const JSONbig = require("json-bigint")({ constructorAction: "ignore" }); let provider = createLocalnetProvider(); let network = await provider.getNetworkConfig(); @@ -143,8 +144,8 @@ describe("test transaction", function () { await signTransaction({ transaction: transactionOne, wallet: alice }); await signTransaction({ transaction: transactionTwo, wallet: alice }); - Logger.trace(JSON.stringify(await provider.simulateTransaction(transactionOne), null, 4)); - Logger.trace(JSON.stringify(await provider.simulateTransaction(transactionTwo), null, 4)); + Logger.trace(JSONbig.parse(await provider.simulateTransaction(transactionOne), null, 4)); + Logger.trace(JSONbig.parse(await provider.simulateTransaction(transactionTwo), null, 4)); }); it("should create transaction using the TokenTransferFactory", async function () { From e3c1738fd30e00827a43e56a834f9e56511ea81e Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 13:00:22 +0200 Subject: [PATCH 115/214] Update network config to follow specs --- .../apiNetworkProvider.dev.net.spec.ts | 7 +- src/networkProviders/networkConfig.ts | 67 ++++++++++--------- .../proxyNetworkProvider.dev.net.spec.ts | 7 +- 3 files changed, 42 insertions(+), 39 deletions(-) diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index bcd44e714..b29afb30b 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -15,10 +15,11 @@ describe.only("ApiNetworkProvider Tests", function () { it("should fetch network configuration", async () => { const result = await apiProvider.getNetworkConfig(); assert.equal(result.ChainID, "D"); - assert.equal(result.GasPerDataByte, 1500); + assert.equal(result.GasPerDataByte, 1500n); assert.equal(result.RoundDuration, 6000); - assert.equal(result.MinGasLimit, 50000); - assert.equal(result.MinGasPrice, 1_000_000_000); + assert.equal(result.MinGasLimit, 50000n); + assert.equal(result.MinGasPrice, 1_000_000_000n); + assert.exists(result.raw); }); it("should fetch network status", async () => { diff --git a/src/networkProviders/networkConfig.ts b/src/networkProviders/networkConfig.ts index be931e3c4..986826087 100644 --- a/src/networkProviders/networkConfig.ts +++ b/src/networkProviders/networkConfig.ts @@ -1,9 +1,8 @@ -import BigNumber from "bignumber.js"; - /** * An object holding Network configuration parameters. */ export class NetworkConfig { + raw: Record = {}; /** * The chain ID. E.g. "1" for the Mainnet. */ @@ -12,54 +11,55 @@ export class NetworkConfig { /** * The gas required by the Network to process a byte of the transaction data. */ - public GasPerDataByte: number; + public GasPerDataByte: bigint; + + public GasPriceModifier: number; + /** - * The round duration. + * The minimum gas limit required to be set when broadcasting a transaction. */ - public RoundDuration: number; + public MinGasLimit: bigint; + /** - * The number of rounds per epoch. + * The minimum gas price required to be set when broadcasting a transaction. */ - public RoundsPerEpoch: number; + public MinGasPrice: bigint; /** - * The Top Up Factor for APR calculation + * The extra gas needed for guarded transactions. */ - public TopUpFactor: number; + public ExtraGasLimitForGuardedTransactions: bigint; /** - * The Top Up Factor for APR calculation + * The number of rounds per epoch. */ - public TopUpRewardsGradientPoint: BigNumber; - - public GasPriceModifier: number; + public NumberOfShards: number; /** - * The minimum gas limit required to be set when broadcasting a transaction. + * The round duration. */ - public MinGasLimit: number; - + public RoundDuration: number; /** - * The minimum gas price required to be set when broadcasting a transaction. + * The number of rounds per epoch. */ - public MinGasPrice: number; + public RoundsPerEpoch: number; /** - * The oldest transaction version accepted by the Network. + * The genesis timestamp */ - public MinTransactionVersion: number; + public GenesisTimestamp: number; constructor() { this.ChainID = "T"; - this.GasPerDataByte = 1500; - this.TopUpFactor = 0; + this.GasPerDataByte = 1500n; + this.GenesisTimestamp = 0; this.RoundDuration = 0; this.RoundsPerEpoch = 0; - this.TopUpRewardsGradientPoint = new BigNumber(0); - this.MinGasLimit = 50000; - this.MinGasPrice = 1000000000; + this.MinGasLimit = 50000n; + this.MinGasPrice = 1000000000n; + this.ExtraGasLimitForGuardedTransactions = 0n; this.GasPriceModifier = 1; - this.MinTransactionVersion = 1; + this.NumberOfShards = 0; } /** @@ -68,16 +68,17 @@ export class NetworkConfig { static fromHttpResponse(payload: any): NetworkConfig { let networkConfig = new NetworkConfig(); + networkConfig.raw = payload; networkConfig.ChainID = String(payload["erd_chain_id"]); - networkConfig.GasPerDataByte = Number(payload["erd_gas_per_data_byte"]); - networkConfig.TopUpFactor = Number(payload["erd_top_up_factor"]); + networkConfig.GasPerDataByte = BigInt(payload["erd_gas_per_data_byte"]); + networkConfig.GasPriceModifier = Number(payload["erd_top_up_factor"]); + networkConfig.MinGasLimit = BigInt(payload["erd_min_gas_limit"]); + networkConfig.MinGasPrice = BigInt(payload["erd_min_gas_price"]); + networkConfig.ExtraGasLimitForGuardedTransactions = BigInt(payload["erd_extra_gas_limit_guarded_tx"]); + networkConfig.NumberOfShards = Number(payload["erd_num_shards_without_meta"]); networkConfig.RoundDuration = Number(payload["erd_round_duration"]); networkConfig.RoundsPerEpoch = Number(payload["erd_rounds_per_epoch"]); - networkConfig.TopUpRewardsGradientPoint = new BigNumber(payload["erd_rewards_top_up_gradient_point"]); - networkConfig.MinGasLimit = Number(payload["erd_min_gas_limit"]); - networkConfig.MinGasPrice = Number(payload["erd_min_gas_price"]); - networkConfig.MinTransactionVersion = Number(payload["erd_min_transaction_version"]); - networkConfig.GasPriceModifier = Number(payload["erd_gas_price_modifier"]); + networkConfig.GenesisTimestamp = Number(payload["erd_start_time"]); return networkConfig; } diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index aba5493ef..956a839b9 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -15,10 +15,11 @@ describe.only("ProxyNetworkProvider Tests", function () { it("should fetch network configuration", async () => { const result = await proxy.getNetworkConfig(); assert.equal(result.ChainID, "D"); - assert.equal(result.GasPerDataByte, 1500); + assert.equal(result.GasPerDataByte, 1500n); assert.equal(result.RoundDuration, 6000); - assert.equal(result.MinGasLimit, 50000); - assert.equal(result.MinGasPrice, 1_000_000_000); + assert.equal(result.MinGasLimit, 50000n); + assert.equal(result.MinGasPrice, 1_000_000_000n); + assert.exists(result.raw); }); it("should fetch network status", async () => { From abe84560dc9d85aa612593f954bd838e6027e48d Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 13:09:20 +0200 Subject: [PATCH 116/214] Update Network status --- .../apiNetworkProvider.dev.net.spec.ts | 5 +- src/networkProviders/networkStatus.ts | 69 ++++++------------- .../proxyNetworkProvider.dev.net.spec.ts | 5 +- src/networkProviders/proxyNetworkProvider.ts | 2 +- 4 files changed, 30 insertions(+), 51 deletions(-) diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index b29afb30b..e56a539cc 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -24,9 +24,12 @@ describe.only("ApiNetworkProvider Tests", function () { it("should fetch network status", async () => { const result = await apiProvider.getNetworkStatus(); - assert.exists(result.Nonce); + assert.exists(result.BlockNonce); assert.exists(result.CurrentRound); + assert.exists(result.BlockTimestamp); + assert.exists(result.CurrentEpoch); assert.exists(result.HighestFinalNonce); + assert.exists(result.raw); }); it("should fetch block details by hash and nonce", async () => { diff --git a/src/networkProviders/networkStatus.ts b/src/networkProviders/networkStatus.ts index ec42a479c..5bac27028 100644 --- a/src/networkProviders/networkStatus.ts +++ b/src/networkProviders/networkStatus.ts @@ -2,63 +2,39 @@ * An object holding network status configuration parameters. */ export class NetworkStatus { - private static default: NetworkStatus; + raw: Record = {}; /** - * The current round. + * The block nonce. */ - public CurrentRound: number; + public BlockTimestamp: number; /** - * The epoch number. + * The block nonce. */ - public EpochNumber: number; + public BlockNonce: bigint; /** * The Highest final nonce. */ - public HighestFinalNonce: number; - - /** - * The erd nonce. - */ - public Nonce: number; - - /** - * The nonce at epoch start. - */ - public NonceAtEpochStart: number; + public HighestFinalNonce: bigint; /** - * The nonces passed in current epoch. - */ - public NoncesPassedInCurrentEpoch: number; - - /** - * The round at epoch start - */ - public RoundAtEpochStart: number; - - /** - * The rounds passed in current epoch + * The current round. */ - public RoundsPassedInCurrentEpoch: number; + public CurrentRound: bigint; /** - * The rounds per epoch + * The epoch number. */ - public RoundsPerEpoch: number; + public CurrentEpoch: number; constructor() { - this.CurrentRound = 0; - this.EpochNumber = 0; - this.HighestFinalNonce = 0; - this.Nonce = 0; - this.NonceAtEpochStart = 0; - this.NoncesPassedInCurrentEpoch = 0; - this.RoundAtEpochStart = 0; - this.RoundsPassedInCurrentEpoch = 0; - this.RoundsPerEpoch = 0; + this.CurrentRound = 0n; + this.CurrentEpoch = 0; + this.HighestFinalNonce = 0n; + this.BlockNonce = 0n; + this.BlockTimestamp = 0; } /** @@ -67,15 +43,12 @@ export class NetworkStatus { static fromHttpResponse(payload: any): NetworkStatus { let networkStatus = new NetworkStatus(); - networkStatus.CurrentRound = Number(payload["erd_current_round"]); - networkStatus.EpochNumber = Number(payload["erd_epoch_number"]); - networkStatus.HighestFinalNonce = Number(payload["erd_highest_final_nonce"]); - networkStatus.Nonce = Number(payload["erd_nonce"]); - networkStatus.NonceAtEpochStart = Number(payload["erd_nonce_at_epoch_start"]); - networkStatus.NoncesPassedInCurrentEpoch = Number(payload["erd_nonces_passed_in_current_epoch"]); - networkStatus.RoundAtEpochStart = Number(payload["erd_round_at_epoch_start"]); - networkStatus.RoundsPassedInCurrentEpoch = Number(payload["erd_rounds_passed_in_current_epoch"]); - networkStatus.RoundsPerEpoch = Number(payload["erd_rounds_per_epoch"]); + networkStatus.raw = payload; + networkStatus.CurrentRound = BigInt(payload["erd_current_round"]); + networkStatus.CurrentEpoch = Number(payload["erd_epoch_number"]); + networkStatus.HighestFinalNonce = BigInt(payload["erd_highest_final_nonce"]); + networkStatus.BlockNonce = BigInt(payload["erd_nonce"]); + networkStatus.BlockTimestamp = Number(payload["erd_block_timestamp"]); return networkStatus; } diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 956a839b9..5830392a7 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -24,9 +24,12 @@ describe.only("ProxyNetworkProvider Tests", function () { it("should fetch network status", async () => { const result = await proxy.getNetworkStatus(); - assert.exists(result.Nonce); + assert.exists(result.BlockNonce); assert.exists(result.CurrentRound); + assert.exists(result.BlockTimestamp); + assert.exists(result.CurrentEpoch); assert.exists(result.HighestFinalNonce); + assert.exists(result.raw); }); it("should fetch block details by hash and nonce", async () => { diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 253e679ce..17843cd21 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -64,7 +64,7 @@ export class ProxyNetworkProvider implements INetworkProvider { } async getLatestBlock(shard: number = METACHAIN_ID): Promise { - const blockNonce = (await this.getNetworkStatus(shard)).Nonce; + const blockNonce = (await this.getNetworkStatus(shard)).BlockNonce; const response = await this.doGetGeneric(`block/${shard}/by-nonce/${blockNonce}`); return BlockOnNetwork.fromHttpResponse(response); } From 5453522de46900edc3e0afa7da60b556bd83d703 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 13:42:30 +0200 Subject: [PATCH 117/214] Fix getTokenAccount --- src/networkProviders/apiNetworkProvider.ts | 6 +++--- .../providers.dev.net.spec.ts | 15 --------------- src/tokens.ts | 19 +++++++++++++++++++ 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index de09f54f5..492650a62 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -2,7 +2,7 @@ import { Address } from "../address"; import { METACHAIN_ID } from "../constants"; import { ErrContractQuery, ErrNetworkProvider } from "../errors"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; -import { Token } from "../tokens"; +import { Token, TokenComputer } from "../tokens"; import { Transaction } from "../transaction"; import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionWatcher } from "../transactionWatcher"; @@ -161,13 +161,13 @@ export class ApiNetworkProvider implements INetworkProvider { return await awaiter.awaitCompleted(transactionHash); } - //TODO check this async getTokenOfAccount(address: Address, token: Token): Promise { let response; if (token.nonce === 0n) { response = await this.doGetGeneric(`accounts/${address.toBech32()}/tokens/${token.identifier}`); } else { - response = await this.doGetGeneric(`accounts/${address.toBech32()}/nfts/${token.identifier}-01`); + const identifier = new TokenComputer().computeExtendedIdentifier(token); + response = await this.doGetGeneric(`accounts/${address.toBech32()}/nfts/${identifier}`); } return TokenAmountOnNetwork.fromApiResponse(response); } diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index b512e6a46..5bfd2e976 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -87,21 +87,6 @@ describe("test network providers on devnet: Proxy and API", function () { assert.equal(localProxyProvider.config.headers.getUserAgent(), expectedProxyUserAgent); }); - it("should have same response for getNetworkStatus()", async function () { - let apiResponse = await apiProvider.getNetworkStatus(); - let proxyResponse = await proxyProvider.getNetworkStatus(); - - assert.equal(apiResponse.EpochNumber, proxyResponse.EpochNumber); - assert.equal(apiResponse.NonceAtEpochStart, proxyResponse.NonceAtEpochStart); - assert.equal(apiResponse.RoundAtEpochStart, proxyResponse.RoundAtEpochStart); - assert.equal(apiResponse.RoundsPerEpoch, proxyResponse.RoundsPerEpoch); - // done this way because the nonces may change until both requests are executed - assert.approximately(apiResponse.CurrentRound, proxyResponse.CurrentRound, 1); - assert.approximately(apiResponse.HighestFinalNonce, proxyResponse.HighestFinalNonce, 1); - assert.approximately(apiResponse.Nonce, proxyResponse.Nonce, 1); - assert.approximately(apiResponse.NoncesPassedInCurrentEpoch, proxyResponse.NoncesPassedInCurrentEpoch, 1); - }); - it("should have same response for getAccount()", async function () { let apiResponse = await apiProvider.getAccount(alice); let proxyResponse = await proxyProvider.getAccount(alice); diff --git a/src/tokens.ts b/src/tokens.ts index 8e9d66a35..6e7776bd0 100644 --- a/src/tokens.ts +++ b/src/tokens.ts @@ -1,6 +1,7 @@ import BigNumber from "bignumber.js"; import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "./constants"; import { ErrInvalidArgument, ErrInvalidTokenIdentifier } from "./errors"; +import { numberToPaddedHex } from "./utils.codec"; // Legacy constants: const EGLDTokenIdentifier = "EGLD"; @@ -261,6 +262,24 @@ export class TokenComputer { return ticker + "-" + randomSequence; } + computeExtendedIdentifier(token: Token): string { + const parts = token.identifier.split("-"); + const { prefix, ticker, randomSequence } = this.splitIdentifierIntoComponents(parts); + + this.validateExtendedIdentifier(prefix, ticker, randomSequence, parts); + + if (token.nonce < 0) { + throw new Error("The token nonce can't be less than 0"); + } + + if (token.nonce === 0n) { + return token.identifier; + } + + const nonceAsHex = numberToPaddedHex(token.nonce); + return `${token.identifier}-${nonceAsHex}`; + } + private validateExtendedIdentifier( prefix: string | null, ticker: string, From 04d412def2b858accccb60065e5ff7fcb00f5346 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 13:55:56 +0200 Subject: [PATCH 118/214] Add logging --- src/abi/smartContract.local.net.spec.ts | 2 +- src/transactionOnNetwork.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index bd83763bd..7f99a1e5f 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -42,7 +42,7 @@ describe("test on local testnet", function () { parser = new SmartContractTransactionsOutcomeParser(); }); - it("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { + it.only("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { this.timeout(60000); TransactionWatcher.DefaultPollingInterval = 5000; diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 4bd3d872f..df3cda2f0 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -89,6 +89,7 @@ export class TransactionOnNetwork { } static fromSimulateResponse(originalTx: Transaction, response: any): TransactionOnNetwork { + console.log(response); const status = new TransactionStatus(response["status"]); const txHash = response["hash"] ?? ""; const scResults: SmartContractResult[] = []; From 80d367e311d0883a17e74841a14c0f3f2cb13d95 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 14:18:25 +0200 Subject: [PATCH 119/214] Remove only for tests --- src/abi/smartContract.local.net.spec.ts | 10 +++++----- .../apiNetworkProvider.dev.net.spec.ts | 2 +- .../proxyNetworkProvider.dev.net.spec.ts | 2 +- src/transactionOnNetwork.ts | 1 - 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 7f99a1e5f..3d9f816f7 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -42,7 +42,7 @@ describe("test on local testnet", function () { parser = new SmartContractTransactionsOutcomeParser(); }); - it.only("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { + it("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { this.timeout(60000); TransactionWatcher.DefaultPollingInterval = 5000; @@ -58,7 +58,7 @@ describe("test on local testnet", function () { const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, - gasLimit: 3000000n, + gasLimit: 4000000n, }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); @@ -73,7 +73,7 @@ describe("test on local testnet", function () { const smartContractCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", - gasLimit: 3000000n, + gasLimit: 4000000n, }); smartContractCallTransaction.nonce = BigInt(alice.account.nonce.valueOf()); smartContractCallTransaction.signature = await alice.signer.sign( @@ -85,7 +85,7 @@ describe("test on local testnet", function () { const simulateOne = factory.createTransactionForExecute(alice.address, { function: "increment", contract: contractAddress, - gasLimit: 100000n, + gasLimit: 200000n, }); simulateOne.nonce = BigInt(alice.account.nonce.valueOf()); @@ -98,7 +98,7 @@ describe("test on local testnet", function () { const simulateTwo = factory.createTransactionForExecute(alice.address, { function: "foobar", contract: contractAddress, - gasLimit: 500000n, + gasLimit: 700000n, }); simulateTwo.nonce = BigInt(alice.account.nonce.valueOf()); diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index e56a539cc..882411eff 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -9,7 +9,7 @@ import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { ApiNetworkProvider } from "./apiNetworkProvider"; -describe.only("ApiNetworkProvider Tests", function () { +describe("ApiNetworkProvider Tests", function () { const apiProvider = new ApiNetworkProvider("https://devnet-api.multiversx.com"); it("should fetch network configuration", async () => { diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 5830392a7..3157be61f 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -9,7 +9,7 @@ import { TransactionOnNetwork } from "../transactionOnNetwork"; import { TransactionStatus } from "../transactionStatus"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; -describe.only("ProxyNetworkProvider Tests", function () { +describe("ProxyNetworkProvider Tests", function () { const proxy = new ProxyNetworkProvider("https://devnet-gateway.multiversx.com"); it("should fetch network configuration", async () => { diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index df3cda2f0..4bd3d872f 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -89,7 +89,6 @@ export class TransactionOnNetwork { } static fromSimulateResponse(originalTx: Transaction, response: any): TransactionOnNetwork { - console.log(response); const status = new TransactionStatus(response["status"]); const txHash = response["hash"] ?? ""; const scResults: SmartContractResult[] = []; From 88c9056e95a70b2599f4e622bfd5098c156c5e73 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 14:59:57 +0200 Subject: [PATCH 120/214] Fix proxy account mapping --- src/networkProviders/accounts.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index 74818ca19..467d94b0b 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -55,6 +55,10 @@ export class AccountOnNetwork { result.userName = payload["username"] || undefined; const codeMetadata = payload["codeMetadata"] ?? null; + result.isContractUpgradable = false; + result.isContractReadable = false; + result.isContractPayable = false; + result.isContractPayableByContract = false; if (codeMetadata) { const metadataBuffer = Buffer.from(codeMetadata, "base64"); const metadata = CodeMetadata.newFromBytes(metadataBuffer); From 23ae9069aae752cf550d755b287d6bb9dc8c6207 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 15:17:43 +0200 Subject: [PATCH 121/214] Update to const where posible --- src/networkProviders/accounts.ts | 4 ++-- src/networkProviders/contractResults.ts | 4 ++-- src/networkProviders/pairs.ts | 2 +- src/networkProviders/tokenDefinitions.ts | 4 ++-- src/networkProviders/tokens.ts | 6 +++--- src/transactionOnNetwork.ts | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index 467d94b0b..c163ed6f1 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -27,7 +27,7 @@ export class AccountOnNetwork { } static fromApiHttpResponse(payload: any): AccountOnNetwork { - let result = new AccountOnNetwork(); + const result = new AccountOnNetwork(); result.address = payload["address"] ? new Address(payload["address"]) : Address.empty(); result.nonce = BigInt(payload["nonce"] || 0); @@ -47,7 +47,7 @@ export class AccountOnNetwork { } static fromProxyHttpResponse(payload: any): AccountOnNetwork { - let result = new AccountOnNetwork(); + const result = new AccountOnNetwork(); result.address = payload["address"] ? new Address(payload["address"]) : Address.empty(); result.nonce = BigInt(payload["nonce"] || 0); diff --git a/src/networkProviders/contractResults.ts b/src/networkProviders/contractResults.ts index d8afa3fa5..45e0bb26f 100644 --- a/src/networkProviders/contractResults.ts +++ b/src/networkProviders/contractResults.ts @@ -13,7 +13,7 @@ export class ContractResults { } static fromProxyHttpResponse(results: any[]): ContractResults { - let items = results.map((item) => ContractResultItem.fromProxyHttpResponse(item)); + const items = results.map((item) => ContractResultItem.fromProxyHttpResponse(item)); return new ContractResults(items); } @@ -43,7 +43,7 @@ export class ContractResultItem { } static fromProxyHttpResponse(response: any): ContractResultItem { - let item = ContractResultItem.fromHttpResponse(response); + const item = ContractResultItem.fromHttpResponse(response); return item; } diff --git a/src/networkProviders/pairs.ts b/src/networkProviders/pairs.ts index b54d10ced..f8dd7e797 100644 --- a/src/networkProviders/pairs.ts +++ b/src/networkProviders/pairs.ts @@ -27,7 +27,7 @@ export class PairOnNetwork { } static fromApiHttpResponse(payload: any): PairOnNetwork { - let result = new PairOnNetwork(); + const result = new PairOnNetwork(); result.address = new Address(payload.address || ""); result.id = payload.id || ""; diff --git a/src/networkProviders/tokenDefinitions.ts b/src/networkProviders/tokenDefinitions.ts index 31f04ec5e..150c2c325 100644 --- a/src/networkProviders/tokenDefinitions.ts +++ b/src/networkProviders/tokenDefinitions.ts @@ -20,7 +20,7 @@ export class DefinitionOfFungibleTokenOnNetwork { assets: Record = {}; static fromApiHttpResponse(payload: any): DefinitionOfFungibleTokenOnNetwork { - let result = new DefinitionOfFungibleTokenOnNetwork(); + const result = new DefinitionOfFungibleTokenOnNetwork(); result.identifier = payload.identifier || ""; result.name = payload.name || ""; @@ -87,7 +87,7 @@ export class DefinitionOfTokenCollectionOnNetwork { canCreateMultiShard: boolean = false; static fromApiHttpResponse(payload: any): DefinitionOfTokenCollectionOnNetwork { - let result = new DefinitionOfTokenCollectionOnNetwork(); + const result = new DefinitionOfTokenCollectionOnNetwork(); result.collection = payload.collection || ""; result.type = payload.type || ""; diff --git a/src/networkProviders/tokens.ts b/src/networkProviders/tokens.ts index 04f0d49f9..d61930766 100644 --- a/src/networkProviders/tokens.ts +++ b/src/networkProviders/tokens.ts @@ -38,7 +38,7 @@ export class NonFungibleTokenOfAccountOnNetwork { } static fromProxyHttpResponse(payload: any): NonFungibleTokenOfAccountOnNetwork { - let result = NonFungibleTokenOfAccountOnNetwork.fromHttpResponse(payload); + const result = NonFungibleTokenOfAccountOnNetwork.fromHttpResponse(payload); result.identifier = payload.tokenIdentifier || ""; result.collection = NonFungibleTokenOfAccountOnNetwork.parseCollectionFromIdentifier(result.identifier); @@ -48,7 +48,7 @@ export class NonFungibleTokenOfAccountOnNetwork { } static fromProxyHttpResponseByNonce(payload: any): NonFungibleTokenOfAccountOnNetwork { - let result = NonFungibleTokenOfAccountOnNetwork.fromHttpResponse(payload); + const result = NonFungibleTokenOfAccountOnNetwork.fromHttpResponse(payload); let nonceAsHex = numberToPaddedHex(result.nonce); result.identifier = `${payload.tokenIdentifier}-${nonceAsHex}`; @@ -59,7 +59,7 @@ export class NonFungibleTokenOfAccountOnNetwork { } static fromApiHttpResponse(payload: any): NonFungibleTokenOfAccountOnNetwork { - let result = NonFungibleTokenOfAccountOnNetwork.fromHttpResponse(payload); + const result = NonFungibleTokenOfAccountOnNetwork.fromHttpResponse(payload); result.identifier = payload.identifier || ""; result.collection = payload.collection || ""; diff --git a/src/transactionOnNetwork.ts b/src/transactionOnNetwork.ts index 4bd3d872f..7e9a82c6a 100644 --- a/src/transactionOnNetwork.ts +++ b/src/transactionOnNetwork.ts @@ -68,7 +68,7 @@ export class TransactionOnNetwork { response: any, processStatus?: TransactionStatus | undefined, ): TransactionOnNetwork { - let result = TransactionOnNetwork.fromHttpResponse(txHash, response); + const result = TransactionOnNetwork.fromHttpResponse(txHash, response); result.smartContractResults = response.smartContractResults?.map( (result: Partial) => @@ -134,7 +134,7 @@ export class TransactionOnNetwork { } static fromApiHttpResponse(txHash: string, response: any): TransactionOnNetwork { - let result = TransactionOnNetwork.fromHttpResponse(txHash, response); + const result = TransactionOnNetwork.fromHttpResponse(txHash, response); result.smartContractResults = response.results?.map( (result: Partial) => From 505262beea810b33a8158707d696427b53ed5240 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 15:35:14 +0200 Subject: [PATCH 122/214] Fix proxy test --- src/networkProviders/apiNetworkProvider.dev.net.spec.ts | 2 +- src/networkProviders/proxyNetworkProvider.dev.net.spec.ts | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index 882411eff..ec046678a 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -343,7 +343,7 @@ describe("ApiNetworkProvider Tests", function () { }); it("should send and await for completed transaction", async function () { - this.timeout(20000); + this.timeout(30000); const bob = await loadTestWallet("bob"); const transactionComputer = new TransactionComputer(); let transaction = new Transaction({ diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 3157be61f..055cc7f0c 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -348,9 +348,8 @@ describe("ProxyNetworkProvider Tests", function () { assert.equal(response.gasLimit, 74000); }); - //TODO Investigate why this returns timeout - it.skip("should send and await for completed transaction", async function () { - this.timeout(30000); + it("should send and await for completed transaction", async function () { + this.timeout(40000); const bob = await loadTestWallet("bob"); const transactionComputer = new TransactionComputer(); let transaction = new Transaction({ @@ -379,7 +378,7 @@ describe("ProxyNetworkProvider Tests", function () { hash = await proxy.sendTransaction(transaction); transactionOnNetwork = await proxy.awaitTransactionOnCondition(hash, condition); - assert.isTrue(transactionOnNetwork.status.isSuccessful()); + assert.isFalse(transactionOnNetwork.status.isSuccessful()); }); it("should fetch transaction status", async () => { From 9e14ee40126f5bb1d1b523e6747f87ba94afaff6 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 15:53:49 +0200 Subject: [PATCH 123/214] Add transaction status method --- src/networkProviders/apiNetworkProvider.dev.net.spec.ts | 6 ++++++ src/networkProviders/apiNetworkProvider.ts | 7 +++++++ src/networkProviders/interface.ts | 6 ++++++ 3 files changed, 19 insertions(+) diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index ec046678a..40cdfd13c 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -186,6 +186,12 @@ describe("ApiNetworkProvider Tests", function () { assert.equal(transaction.hash, "6fe05e4ca01d42c96ae5182978a77fe49f26bcc14aac95ad4f19618173f86ddb"); }); + it("should fetch transaction status", async () => { + const txHash = "9d47c4b4669cbcaa26f5dec79902dd20e55a0aa5f4b92454a74e7dbd0183ad6c"; + const result = await apiProvider.getTransactionStatus(txHash); + assert.equal(result.status, "success"); + }); + it("should send transaction", async () => { const transaction = new Transaction({ sender: Address.newFromBech32("erd1487vz5m4zpxjyqw4flwa3xhnkzg4yrr3mkzf5sf0zgt94hjprc8qazcccl"), diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 492650a62..83d4a34f7 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -5,6 +5,7 @@ import { SmartContractQuery, SmartContractQueryResponse } from "../smartContract import { Token, TokenComputer } from "../tokens"; import { Transaction } from "../transaction"; import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../transactionOnNetwork"; +import { TransactionStatus } from "../transactionStatus"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; import { AccountOnNetwork, GuardianData } from "./accounts"; @@ -132,6 +133,12 @@ export class ApiNetworkProvider implements INetworkProvider { return transaction; } + async getTransactionStatus(txHash: string): Promise { + const response = await this.doGetGeneric(`transactions/${txHash}?fields=status`); + const status = new TransactionStatus(response.status); + return status; + } + async awaitTransactionOnCondition( transactionHash: string, condition: (account: TransactionOnNetwork) => boolean, diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 9f8f640bd..3b5fb459f 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -3,6 +3,7 @@ import { SmartContractQuery, SmartContractQueryResponse } from "../smartContract import { Token } from "../tokens"; import { Transaction } from "../transaction"; import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { TransactionStatus } from "../transactionStatus"; import { AccountOnNetwork } from "./accounts"; import { NetworkConfig } from "./networkConfig"; import { NetworkStatus } from "./networkStatus"; @@ -94,6 +95,11 @@ export interface INetworkProvider { */ getTransaction(txHash: string, withProcessStatus?: boolean): Promise; + /** + * Fetches the status of a transaction. + */ + getTransactionStatus(txHash: string): Promise; + /** * Waits until the transaction is completely processed. * Can throw: From 5e94b199f9c6c53c154e74a38b07ce6479618291 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 16:08:50 +0200 Subject: [PATCH 124/214] remove getBlockArguments and add back transactionStatus --- .../apiNetworkProvider.dev.net.spec.ts | 2 +- src/networkProviders/apiNetworkProvider.ts | 7 +++---- src/networkProviders/interface.ts | 12 ------------ src/networkProviders/proxyNetworkProvider.ts | 11 +++++------ src/networkProviders/resources.ts | 11 +---------- src/testutils/mockNetworkProvider.ts | 5 +++++ src/transactionWatcher.spec.ts | 4 ++-- 7 files changed, 17 insertions(+), 35 deletions(-) diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index 40cdfd13c..ed30b8882 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -34,7 +34,7 @@ describe("ApiNetworkProvider Tests", function () { it("should fetch block details by hash and nonce", async () => { const blockHash = "ded535cc0afb2dc5f9787e9560dc48d0b83564a3f994a390b228d894d854699f"; - const resultByHash = await apiProvider.getBlock({ blockHash }); + const resultByHash = await apiProvider.getBlock(blockHash); assert.equal(resultByHash.hash, blockHash); assert.equal(resultByHash.nonce, 5949242n); diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 83d4a34f7..c04121cdd 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -23,7 +23,6 @@ import { AccountStorageEntry, AwaitingOptions, BlockOnNetwork, - GetBlockArguments, TokenAmountOnNetwork, TransactionCostEstimationResponse, } from "./resources"; @@ -61,12 +60,12 @@ export class ApiNetworkProvider implements INetworkProvider { return await this.backingProxyNetworkProvider.getNetworkStatus(shard); } - async getBlock(blockArgs: GetBlockArguments): Promise { - const response = await this.doGetGeneric(`blocks/${blockArgs.blockHash}`); + async getBlock(blockHash: string): Promise { + const response = await this.doGetGeneric(`blocks/${blockHash}`); return BlockOnNetwork.fromHttpResponse(response); } - async getLatestBlock(_shard?: number): Promise { + async getLatestBlock(): Promise { const response = await this.doGetGeneric("blocks/latest"); return BlockOnNetwork.fromHttpResponse(response); } diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 3b5fb459f..f69c63df0 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -11,8 +11,6 @@ import { AccountStorage, AccountStorageEntry, AwaitingOptions, - BlockOnNetwork, - GetBlockArguments, TokenAmountOnNetwork, TransactionCostEstimationResponse, } from "./resources"; @@ -32,16 +30,6 @@ export interface INetworkProvider { */ getNetworkStatus(): Promise; - /** - * Fetches a block by nonce or by hash. - */ - getBlock(blockArgs: GetBlockArguments): Promise; - - /** - * Fetches the latest block of a shard. - */ - getLatestBlock(shard: number): Promise; - /** * Fetches the state of an account. */ diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 17843cd21..217b34c84 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -21,7 +21,6 @@ import { AccountStorageEntry, AwaitingOptions, BlockOnNetwork, - GetBlockArguments, TokenAmountOnNetwork, TransactionCostEstimationResponse, } from "./resources"; @@ -53,12 +52,12 @@ export class ProxyNetworkProvider implements INetworkProvider { const networkStatus = NetworkStatus.fromHttpResponse(response.status); return networkStatus; } - async getBlock(blockArgs: GetBlockArguments): Promise { + async getBlock(args: { shard: number; blockHash?: string; blockNonce?: bigint }): Promise { let response; - if (blockArgs.blockHash) { - response = await this.doGetGeneric(`block/${blockArgs.shard}/by-hash/${blockArgs.blockHash}`); - } else if (blockArgs.blockNonce) { - response = await this.doGetGeneric(`block/${blockArgs.shard}/by-nonce/${blockArgs.blockNonce}`); + if (args.blockHash) { + response = await this.doGetGeneric(`block/${args.shard}/by-hash/${args.blockHash}`); + } else if (args.blockNonce) { + response = await this.doGetGeneric(`block/${args.shard}/by-nonce/${args.blockNonce}`); } else throw new Error("Block hash or block nonce not provided."); return BlockOnNetwork.fromHttpResponse(response.block); } diff --git a/src/networkProviders/resources.ts b/src/networkProviders/resources.ts index 45364d4f3..5d1a82364 100644 --- a/src/networkProviders/resources.ts +++ b/src/networkProviders/resources.ts @@ -166,21 +166,12 @@ export class TransactionCostEstimationResponse { } } -export class GetBlockArguments { - shard?: number; - blockNonce?: bigint; - blockHash?: string; - constructor(init?: Partial) { - Object.assign(this, init); - } -} - export class TokenAmountOnNetwork { raw: Record = {}; token: Token = new Token({ identifier: "" }); amount: bigint = 0n; block_coordinates?: BlockCoordinates; - constructor(init?: Partial) { + constructor(init?: Partial) { Object.assign(this, init); } diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index fb14354ea..2bfdf9b1f 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -232,6 +232,11 @@ export class MockNetworkProvider implements INetworkProvider { throw new ErrMock("Transaction not found"); } + async getTransactionStatus(txHash: string): Promise { + let transaction = await this.getTransaction(txHash); + return transaction.status; + } + async getNetworkConfig(): Promise { throw new errors.ErrNotImplemented(); } diff --git a/src/transactionWatcher.spec.ts b/src/transactionWatcher.spec.ts index aeda03a5b..2629ced71 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/transactionWatcher.spec.ts @@ -35,7 +35,7 @@ describe("test transactionWatcher", () => { watcher.awaitCompleted(dummyTransaction.getHash().hex()), ]); - assert.isTrue((await provider.getTransaction(hash.hex())).status.isCompleted()); + assert.isTrue((await provider.getTransactionStatus(hash.hex())).isCompleted()); }); it("should await status == executed using transaction", async () => { @@ -67,6 +67,6 @@ describe("test transactionWatcher", () => { watcher.awaitCompleted(dummyTransaction), ]); - assert.isTrue((await provider.getTransaction(hash.hex())).status.isCompleted()); + assert.isTrue((await provider.getTransactionStatus(hash.hex())).isCompleted()); }); }); From a1d183443e8f500e7e7184d8ae7dc40c4c851610 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 16:27:20 +0200 Subject: [PATCH 125/214] Add wrapper over JsonBigInt --- src/abi/smartContract.local.net.spec.ts | 11 +++++------ src/testutils/utils.ts | 12 ++++++++++++ src/transaction.local.net.spec.ts | 7 +++---- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 3d9f816f7..6bb6ed953 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -6,6 +6,7 @@ import { SmartContractTransactionsFactory, SmartContractTransactionsOutcomeParser, } from "../smartContracts"; +import { parseBigIntJSON } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { loadTestWallets, TestWallet } from "../testutils/wallets"; import { TransactionComputer } from "../transactionComputer"; @@ -23,8 +24,6 @@ import { U32Value, } from "./typesystem"; -const JSONbig = require("json-bigint")({ constructorAction: "ignore" }); - describe("test on local testnet", function () { let alice: TestWallet, bob: TestWallet, carol: TestWallet; let provider = createLocalnetProvider(); @@ -42,7 +41,7 @@ describe("test on local testnet", function () { parser = new SmartContractTransactionsOutcomeParser(); }); - it("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { + it.only("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { this.timeout(60000); TransactionWatcher.DefaultPollingInterval = 5000; @@ -111,7 +110,7 @@ describe("test on local testnet", function () { // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); const callTxHash = await provider.sendTransaction(smartContractCallTransaction); - + console.log({ deployTxHash, callTxHash }); await watcher.awaitCompleted(deployTxHash); let transactionOnNetwork = await provider.getTransaction(deployTxHash); let response = parser.parseExecute({ transactionOnNetwork }); @@ -124,8 +123,8 @@ describe("test on local testnet", function () { assert.isTrue(response.returnCode == "ok"); // Simulate - Logger.trace(JSONbig.parse(await provider.simulateTransaction(simulateOne), null, 4)); - Logger.trace(JSONbig.parse(await provider.simulateTransaction(simulateTwo), null, 4)); + Logger.trace(parseBigIntJSON(await provider.simulateTransaction(simulateOne))); + Logger.trace(parseBigIntJSON(await provider.simulateTransaction(simulateTwo))); }); it("counter: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index 1ba118c9b..6e9cd823e 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -96,3 +96,15 @@ export function b64TopicsToBytes(topics: string[]): Uint8Array[] { export function b64ToHex(value: string): string { return Buffer.from(value, "base64").toString("hex"); } + +export function importJsonBig(value: string): string { + return Buffer.from(value, "base64").toString("hex"); +} +export const parseBigIntJSON = (jsonString: any): any => { + const JSONBig = require("json-bigint")({ constructorAction: "ignore" }); + try { + return JSONBig({ useNativeBigInt: true }).parse(jsonString); + } catch (error) { + throw new Error(`Failed to parse JSON: ${error.message}`); + } +}; diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 8babf176d..1ada1e29c 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -2,7 +2,7 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Logger } from "./logger"; import { INetworkProvider } from "./networkProviders/interface"; -import { loadTestWallets, TestWallet } from "./testutils"; +import { loadTestWallets, parseBigIntJSON, TestWallet } from "./testutils"; import { createLocalnetProvider } from "./testutils/networkProviders"; import { TokenTransfer } from "./tokens"; import { Transaction } from "./transaction"; @@ -114,7 +114,6 @@ describe("test transaction", function () { it("should simulate transactions", async function () { this.timeout(20000); - const JSONbig = require("json-bigint")({ constructorAction: "ignore" }); let provider = createLocalnetProvider(); let network = await provider.getNetworkConfig(); @@ -144,8 +143,8 @@ describe("test transaction", function () { await signTransaction({ transaction: transactionOne, wallet: alice }); await signTransaction({ transaction: transactionTwo, wallet: alice }); - Logger.trace(JSONbig.parse(await provider.simulateTransaction(transactionOne), null, 4)); - Logger.trace(JSONbig.parse(await provider.simulateTransaction(transactionTwo), null, 4)); + Logger.trace(parseBigIntJSON(await provider.simulateTransaction(transactionOne))); + Logger.trace(parseBigIntJSON(await provider.simulateTransaction(transactionTwo))); }); it("should create transaction using the TokenTransferFactory", async function () { From 2500ca970d389f3a2cc9a19a5b92615ac272be74 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 16:27:44 +0200 Subject: [PATCH 126/214] Remove only --- src/abi/smartContract.local.net.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 6bb6ed953..9b3bb01ef 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -41,7 +41,7 @@ describe("test on local testnet", function () { parser = new SmartContractTransactionsOutcomeParser(); }); - it.only("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { + it("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { this.timeout(60000); TransactionWatcher.DefaultPollingInterval = 5000; From 8438aa97ce9c04c8613a02f90f08b8a2b633f960 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 16:37:08 +0200 Subject: [PATCH 127/214] Update naming to keep naming convention --- src/abi/smartContract.local.net.spec.ts | 8 +-- src/networkProviders/networkConfig.ts | 60 +++++++++---------- src/networkProviders/networkStatus.ts | 30 +++++----- .../proxyNetworkProvider.dev.net.spec.ts | 20 +++---- src/networkProviders/proxyNetworkProvider.ts | 2 +- src/transaction.local.net.spec.ts | 18 +++--- 6 files changed, 69 insertions(+), 69 deletions(-) diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 9b3bb01ef..7f448f7c1 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -50,7 +50,7 @@ describe("test on local testnet", function () { let network = await provider.getNetworkConfig(); await alice.sync(provider); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); const bytecode = await promises.readFile("src/testdata/counter.wasm"); @@ -136,7 +136,7 @@ describe("test on local testnet", function () { let network = await provider.getNetworkConfig(); await alice.sync(provider); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); const bytecode = await promises.readFile("src/testdata/counter.wasm"); @@ -214,7 +214,7 @@ describe("test on local testnet", function () { let network = await provider.getNetworkConfig(); await alice.sync(provider); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); const bytecode = await promises.readFile("src/testdata/erc20.wasm"); @@ -317,7 +317,7 @@ describe("test on local testnet", function () { let network = await provider.getNetworkConfig(); await alice.sync(provider); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); const bytecode = await promises.readFile("src/testdata/lottery-esdt.wasm"); diff --git a/src/networkProviders/networkConfig.ts b/src/networkProviders/networkConfig.ts index 986826087..b33640e51 100644 --- a/src/networkProviders/networkConfig.ts +++ b/src/networkProviders/networkConfig.ts @@ -6,60 +6,60 @@ export class NetworkConfig { /** * The chain ID. E.g. "1" for the Mainnet. */ - public ChainID: string; + public chainID: string; /** * The gas required by the Network to process a byte of the transaction data. */ - public GasPerDataByte: bigint; + public gasPerDataByte: bigint; - public GasPriceModifier: number; + public gasPriceModifier: number; /** * The minimum gas limit required to be set when broadcasting a transaction. */ - public MinGasLimit: bigint; + public minGasLimit: bigint; /** * The minimum gas price required to be set when broadcasting a transaction. */ - public MinGasPrice: bigint; + public minGasPrice: bigint; /** * The extra gas needed for guarded transactions. */ - public ExtraGasLimitForGuardedTransactions: bigint; + public extraGasLimitForGuardedTransactions: bigint; /** * The number of rounds per epoch. */ - public NumberOfShards: number; + public numberOfShards: number; /** * The round duration. */ - public RoundDuration: number; + public roundDuration: number; /** * The number of rounds per epoch. */ - public RoundsPerEpoch: number; + public roundsPerEpoch: number; /** * The genesis timestamp */ - public GenesisTimestamp: number; + public genesisTimestamp: number; constructor() { - this.ChainID = "T"; - this.GasPerDataByte = 1500n; - this.GenesisTimestamp = 0; - this.RoundDuration = 0; - this.RoundsPerEpoch = 0; - this.MinGasLimit = 50000n; - this.MinGasPrice = 1000000000n; - this.ExtraGasLimitForGuardedTransactions = 0n; - this.GasPriceModifier = 1; - this.NumberOfShards = 0; + this.chainID = "T"; + this.gasPerDataByte = 1500n; + this.genesisTimestamp = 0; + this.roundDuration = 0; + this.roundsPerEpoch = 0; + this.minGasLimit = 50000n; + this.minGasPrice = 1000000000n; + this.extraGasLimitForGuardedTransactions = 0n; + this.gasPriceModifier = 1; + this.numberOfShards = 0; } /** @@ -69,16 +69,16 @@ export class NetworkConfig { let networkConfig = new NetworkConfig(); networkConfig.raw = payload; - networkConfig.ChainID = String(payload["erd_chain_id"]); - networkConfig.GasPerDataByte = BigInt(payload["erd_gas_per_data_byte"]); - networkConfig.GasPriceModifier = Number(payload["erd_top_up_factor"]); - networkConfig.MinGasLimit = BigInt(payload["erd_min_gas_limit"]); - networkConfig.MinGasPrice = BigInt(payload["erd_min_gas_price"]); - networkConfig.ExtraGasLimitForGuardedTransactions = BigInt(payload["erd_extra_gas_limit_guarded_tx"]); - networkConfig.NumberOfShards = Number(payload["erd_num_shards_without_meta"]); - networkConfig.RoundDuration = Number(payload["erd_round_duration"]); - networkConfig.RoundsPerEpoch = Number(payload["erd_rounds_per_epoch"]); - networkConfig.GenesisTimestamp = Number(payload["erd_start_time"]); + networkConfig.chainID = String(payload["erd_chain_id"]); + networkConfig.gasPerDataByte = BigInt(payload["erd_gas_per_data_byte"]); + networkConfig.gasPriceModifier = Number(payload["erd_top_up_factor"]); + networkConfig.minGasLimit = BigInt(payload["erd_min_gas_limit"]); + networkConfig.minGasPrice = BigInt(payload["erd_min_gas_price"]); + networkConfig.extraGasLimitForGuardedTransactions = BigInt(payload["erd_extra_gas_limit_guarded_tx"]); + networkConfig.numberOfShards = Number(payload["erd_num_shards_without_meta"]); + networkConfig.roundDuration = Number(payload["erd_round_duration"]); + networkConfig.roundsPerEpoch = Number(payload["erd_rounds_per_epoch"]); + networkConfig.genesisTimestamp = Number(payload["erd_start_time"]); return networkConfig; } diff --git a/src/networkProviders/networkStatus.ts b/src/networkProviders/networkStatus.ts index 5bac27028..d6d8a36cc 100644 --- a/src/networkProviders/networkStatus.ts +++ b/src/networkProviders/networkStatus.ts @@ -7,34 +7,34 @@ export class NetworkStatus { /** * The block nonce. */ - public BlockTimestamp: number; + public blockTimestamp: number; /** * The block nonce. */ - public BlockNonce: bigint; + public blockNonce: bigint; /** * The Highest final nonce. */ - public HighestFinalNonce: bigint; + public highestFinalNonce: bigint; /** * The current round. */ - public CurrentRound: bigint; + public currentRound: bigint; /** * The epoch number. */ - public CurrentEpoch: number; + public currentEpoch: number; constructor() { - this.CurrentRound = 0n; - this.CurrentEpoch = 0; - this.HighestFinalNonce = 0n; - this.BlockNonce = 0n; - this.BlockTimestamp = 0; + this.currentRound = 0n; + this.currentEpoch = 0; + this.highestFinalNonce = 0n; + this.blockNonce = 0n; + this.blockTimestamp = 0; } /** @@ -44,11 +44,11 @@ export class NetworkStatus { let networkStatus = new NetworkStatus(); networkStatus.raw = payload; - networkStatus.CurrentRound = BigInt(payload["erd_current_round"]); - networkStatus.CurrentEpoch = Number(payload["erd_epoch_number"]); - networkStatus.HighestFinalNonce = BigInt(payload["erd_highest_final_nonce"]); - networkStatus.BlockNonce = BigInt(payload["erd_nonce"]); - networkStatus.BlockTimestamp = Number(payload["erd_block_timestamp"]); + networkStatus.currentRound = BigInt(payload["erd_current_round"]); + networkStatus.currentEpoch = Number(payload["erd_epoch_number"]); + networkStatus.highestFinalNonce = BigInt(payload["erd_highest_final_nonce"]); + networkStatus.blockNonce = BigInt(payload["erd_nonce"]); + networkStatus.blockTimestamp = Number(payload["erd_block_timestamp"]); return networkStatus; } diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 055cc7f0c..dc298f16c 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -14,21 +14,21 @@ describe("ProxyNetworkProvider Tests", function () { it("should fetch network configuration", async () => { const result = await proxy.getNetworkConfig(); - assert.equal(result.ChainID, "D"); - assert.equal(result.GasPerDataByte, 1500n); - assert.equal(result.RoundDuration, 6000); - assert.equal(result.MinGasLimit, 50000n); - assert.equal(result.MinGasPrice, 1_000_000_000n); + assert.equal(result.chainID, "D"); + assert.equal(result.gasPerDataByte, 1500n); + assert.equal(result.roundDuration, 6000); + assert.equal(result.minGasLimit, 50000n); + assert.equal(result.minGasPrice, 1_000_000_000n); assert.exists(result.raw); }); it("should fetch network status", async () => { const result = await proxy.getNetworkStatus(); - assert.exists(result.BlockNonce); - assert.exists(result.CurrentRound); - assert.exists(result.BlockTimestamp); - assert.exists(result.CurrentEpoch); - assert.exists(result.HighestFinalNonce); + assert.exists(result.blockNonce); + assert.exists(result.currentRound); + assert.exists(result.blockTimestamp); + assert.exists(result.currentEpoch); + assert.exists(result.highestFinalNonce); assert.exists(result.raw); }); diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 217b34c84..0fea2c224 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -63,7 +63,7 @@ export class ProxyNetworkProvider implements INetworkProvider { } async getLatestBlock(shard: number = METACHAIN_ID): Promise { - const blockNonce = (await this.getNetworkStatus(shard)).BlockNonce; + const blockNonce = (await this.getNetworkStatus(shard)).blockNonce; const response = await this.doGetGeneric(`block/${shard}/by-nonce/${blockNonce}`); return BlockOnNetwork.fromHttpResponse(response); } diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 1ada1e29c..55e3ea99b 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -40,16 +40,16 @@ describe("test transaction", function () { sender: alice.address, receiver: bob.address, value: TokenTransfer.newFromNativeAmount(42000000000000000000n).amount, - gasLimit: BigInt(network.MinGasLimit), - chainID: network.ChainID, + gasLimit: BigInt(network.minGasLimit), + chainID: network.chainID, }); let transactionTwo = new Transaction({ sender: alice.address, receiver: bob.address, value: TokenTransfer.newFromNativeAmount(43000000000000000000n).amount, - gasLimit: BigInt(network.MinGasLimit), - chainID: network.ChainID, + gasLimit: BigInt(network.minGasLimit), + chainID: network.chainID, }); await alice.sync(provider); @@ -90,8 +90,8 @@ describe("test transaction", function () { sender: alice.address, receiver: bob.address, value: TokenTransfer.newFromNativeAmount(42n).amount, - gasLimit: BigInt(network.MinGasLimit), - chainID: network.ChainID, + gasLimit: BigInt(network.minGasLimit), + chainID: network.chainID, }); await alice.sync(provider); @@ -125,7 +125,7 @@ describe("test transaction", function () { gasLimit: 70000n, receiver: alice.address, value: TokenTransfer.newFromNativeAmount(1000n).amount, - chainID: network.ChainID, + chainID: network.chainID, }); let transactionTwo = new Transaction({ @@ -134,7 +134,7 @@ describe("test transaction", function () { gasLimit: 70000n, receiver: alice.address, value: TokenTransfer.newFromNativeAmount(1000000n).amount, - chainID: network.ChainID, + chainID: network.chainID, }); transactionOne.setNonce(alice.account.nonce); @@ -155,7 +155,7 @@ describe("test transaction", function () { const network = await provider.getNetworkConfig(); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new TransferTransactionsFactory({ config: config }); await alice.sync(provider); From 378e636147cd43dc29665ac776c9264f89e7f011 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 20 Jan 2025 16:44:43 +0200 Subject: [PATCH 128/214] Fix tests --- .../apiNetworkProvider.dev.net.spec.ts | 20 +++++++++---------- .../providers.dev.net.spec.ts | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index ed30b8882..817af7574 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -14,21 +14,21 @@ describe("ApiNetworkProvider Tests", function () { it("should fetch network configuration", async () => { const result = await apiProvider.getNetworkConfig(); - assert.equal(result.ChainID, "D"); - assert.equal(result.GasPerDataByte, 1500n); - assert.equal(result.RoundDuration, 6000); - assert.equal(result.MinGasLimit, 50000n); - assert.equal(result.MinGasPrice, 1_000_000_000n); + assert.equal(result.chainID, "D"); + assert.equal(result.gasPerDataByte, 1500n); + assert.equal(result.roundDuration, 6000); + assert.equal(result.minGasLimit, 50000n); + assert.equal(result.minGasPrice, 1_000_000_000n); assert.exists(result.raw); }); it("should fetch network status", async () => { const result = await apiProvider.getNetworkStatus(); - assert.exists(result.BlockNonce); - assert.exists(result.CurrentRound); - assert.exists(result.BlockTimestamp); - assert.exists(result.CurrentEpoch); - assert.exists(result.HighestFinalNonce); + assert.exists(result.blockNonce); + assert.exists(result.currentRound); + assert.exists(result.blockTimestamp); + assert.exists(result.currentEpoch); + assert.exists(result.highestFinalNonce); assert.exists(result.raw); }); diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 5bfd2e976..4685f1ca3 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -27,8 +27,8 @@ describe("test network providers on devnet: Proxy and API", function () { const apiResponse = await apiProviderWithoutConfig.getNetworkConfig(); const proxyResponse = await proxyProviderWithoutConfig.getNetworkConfig(); - assert.equal(apiResponse.ChainID, "D"); - assert.equal(proxyResponse.ChainID, "D"); + assert.equal(apiResponse.chainID, "D"); + assert.equal(proxyResponse.chainID, "D"); }); it("should have same response for getNetworkConfig()", async function () { From 7e5f1aaa8d6e701e20ade63b7506e53f14b4db0e Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 21 Jan 2025 10:45:55 +0200 Subject: [PATCH 129/214] Fix integration tests --- src/abi/interaction.local.net.spec.ts | 18 +++++++++--------- src/abi/smartContract.local.net.spec.ts | 7 +++---- src/abi/smartContractResults.local.net.spec.ts | 6 +++--- src/testutils/utils.ts | 4 ++-- src/transaction.local.net.spec.ts | 6 +++--- 5 files changed, 20 insertions(+), 21 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 42b76d821..cbe33c112 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -32,7 +32,7 @@ describe("test smart contract interactor", function () { let network = await provider.getNetworkConfig(); await alice.sync(provider); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config, abi: abiRegistry, @@ -141,7 +141,7 @@ describe("test smart contract interactor", function () { codePath: "src/testdata/basic-features.wasm", gasLimit: 600000000n, initArguments: [], - chainID: network.ChainID, + chainID: network.chainID, }); let deployTxHash = await provider.sendTransaction(deployTransaction); let deployResponse = await controller.awaitCompletedDeploy(deployTxHash); @@ -151,7 +151,7 @@ describe("test smart contract interactor", function () { contract.methods .returns_egld_decimal([]) .withGasLimit(10000000n) - .withChainID(network.ChainID) + .withChainID(network.chainID) .withSender(alice.address) .withValue(1n) ); @@ -165,7 +165,7 @@ describe("test smart contract interactor", function () { let additionInteraction = contract.methods .managed_decimal_addition([new ManagedDecimalValue("2.5", 2), new ManagedDecimalValue("2.7", 2)]) .withGasLimit(10000000n) - .withChainID(network.ChainID) + .withChainID(network.chainID) .withSender(alice.address) .withValue(0n); @@ -179,7 +179,7 @@ describe("test smart contract interactor", function () { let mdLnInteraction = contract.methods .managed_decimal_ln([new ManagedDecimalValue("23", 9)]) .withGasLimit(10000000n) - .withChainID(network.ChainID) + .withChainID(network.chainID) .withSender(alice.address) .withValue(0n); @@ -195,7 +195,7 @@ describe("test smart contract interactor", function () { new ManagedDecimalValue("5", 2, true), ]) .withGasLimit(50000000n) - .withChainID(network.ChainID) + .withChainID(network.chainID) .withSender(alice.address) .withValue(0n); @@ -208,7 +208,7 @@ describe("test smart contract interactor", function () { let lnVarInteraction = contract.methods .managed_decimal_ln_var([new ManagedDecimalValue("23", 9, true)]) .withGasLimit(50000000n) - .withChainID(network.ChainID) + .withChainID(network.chainID) .withSender(alice.address) .withValue(0n); @@ -268,7 +268,7 @@ describe("test smart contract interactor", function () { let network = await provider.getNetworkConfig(); await alice.sync(provider); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config, abi: abiRegistry, @@ -370,7 +370,7 @@ describe("test smart contract interactor", function () { let network = await provider.getNetworkConfig(); await alice.sync(provider); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config, abi: abiRegistry, diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 7f448f7c1..559108a85 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -6,7 +6,7 @@ import { SmartContractTransactionsFactory, SmartContractTransactionsOutcomeParser, } from "../smartContracts"; -import { parseBigIntJSON } from "../testutils"; +import { stringifyBigIntJSON } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { loadTestWallets, TestWallet } from "../testutils/wallets"; import { TransactionComputer } from "../transactionComputer"; @@ -110,7 +110,6 @@ describe("test on local testnet", function () { // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); const callTxHash = await provider.sendTransaction(smartContractCallTransaction); - console.log({ deployTxHash, callTxHash }); await watcher.awaitCompleted(deployTxHash); let transactionOnNetwork = await provider.getTransaction(deployTxHash); let response = parser.parseExecute({ transactionOnNetwork }); @@ -123,8 +122,8 @@ describe("test on local testnet", function () { assert.isTrue(response.returnCode == "ok"); // Simulate - Logger.trace(parseBigIntJSON(await provider.simulateTransaction(simulateOne))); - Logger.trace(parseBigIntJSON(await provider.simulateTransaction(simulateTwo))); + Logger.trace(stringifyBigIntJSON(await provider.simulateTransaction(simulateOne))); + Logger.trace(stringifyBigIntJSON(await provider.simulateTransaction(simulateTwo))); }); it("counter: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index a2f34ad0e..89ffcd141 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -44,14 +44,14 @@ describe("fetch transactions from local testnet", function () { codePath: "src/testdata/counter.wasm", gasLimit: 3000000n, initArguments: [], - chainID: network.ChainID, + chainID: network.chainID, }); // ++ let transactionIncrement = contract.call({ func: new ContractFunction("increment"), gasLimit: 3000000n, - chainID: network.ChainID, + chainID: network.chainID, caller: alice.address, }); @@ -86,7 +86,7 @@ describe("fetch transactions from local testnet", function () { let network = await provider.getNetworkConfig(); await alice.sync(provider); - const config = new TransactionsFactoryConfig({ chainID: network.ChainID }); + const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); const bytecode = await promises.readFile("src/testdata/counter.wasm"); diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index 6e9cd823e..ac6989816 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -100,10 +100,10 @@ export function b64ToHex(value: string): string { export function importJsonBig(value: string): string { return Buffer.from(value, "base64").toString("hex"); } -export const parseBigIntJSON = (jsonString: any): any => { +export const stringifyBigIntJSON = (jsonString: any): any => { const JSONBig = require("json-bigint")({ constructorAction: "ignore" }); try { - return JSONBig({ useNativeBigInt: true }).parse(jsonString); + return JSONBig.stringify(jsonString); } catch (error) { throw new Error(`Failed to parse JSON: ${error.message}`); } diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 55e3ea99b..702f9d7a7 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -2,7 +2,7 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { Logger } from "./logger"; import { INetworkProvider } from "./networkProviders/interface"; -import { loadTestWallets, parseBigIntJSON, TestWallet } from "./testutils"; +import { loadTestWallets, stringifyBigIntJSON, TestWallet } from "./testutils"; import { createLocalnetProvider } from "./testutils/networkProviders"; import { TokenTransfer } from "./tokens"; import { Transaction } from "./transaction"; @@ -143,8 +143,8 @@ describe("test transaction", function () { await signTransaction({ transaction: transactionOne, wallet: alice }); await signTransaction({ transaction: transactionTwo, wallet: alice }); - Logger.trace(parseBigIntJSON(await provider.simulateTransaction(transactionOne))); - Logger.trace(parseBigIntJSON(await provider.simulateTransaction(transactionTwo))); + Logger.trace(stringifyBigIntJSON(await provider.simulateTransaction(transactionOne))); + Logger.trace(stringifyBigIntJSON(await provider.simulateTransaction(transactionTwo))); }); it("should create transaction using the TokenTransferFactory", async function () { From 93600bbff205c298d2234800cbdd0202f0ec52e4 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 21 Jan 2025 12:11:04 +0200 Subject: [PATCH 130/214] Code review follow up --- .../apiNetworkProvider.dev.net.spec.ts | 4 +- src/networkProviders/apiNetworkProvider.ts | 39 ++++++++----------- src/networkProviders/interface.ts | 6 +-- src/networkProviders/networkConfig.ts | 22 +++++------ src/networkProviders/networkStatus.ts | 6 +-- .../providers.dev.net.spec.ts | 7 ++-- .../proxyNetworkProvider.dev.net.spec.ts | 4 +- src/networkProviders/proxyNetworkProvider.ts | 20 +++++----- src/networkProviders/resources.ts | 10 +++-- src/testutils/mockNetworkProvider.ts | 4 +- src/testutils/utils.ts | 1 + 11 files changed, 62 insertions(+), 61 deletions(-) diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index 817af7574..b63c5cfe9 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -275,8 +275,8 @@ describe("ApiNetworkProvider Tests", function () { null, "30274b60b5635f981fa89ccfe726a34ca7121caa5d34123021c77a5c64cc9163", ]; - const hashes = await apiProvider.sendTransactions(txs); - assert.equal(hashes.length, 3); + const [numOfSentTxs, hashes] = await apiProvider.sendTransactions(txs); + assert.equal(numOfSentTxs, 2); assert.deepEqual(hashes, expectedHashes); }); diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index c04121cdd..fff408c6b 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -8,7 +8,7 @@ import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../tran import { TransactionStatus } from "../transactionStatus"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; -import { AccountOnNetwork, GuardianData } from "./accounts"; +import { AccountOnNetwork } from "./accounts"; import { defaultAxiosConfig, defaultPagination } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; @@ -16,7 +16,6 @@ import { INetworkProvider, IPagination } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkProviderConfig } from "./networkProviderConfig"; import { NetworkStatus } from "./networkStatus"; -import { PairOnNetwork } from "./pairs"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; import { AccountStorage, @@ -24,7 +23,7 @@ import { AwaitingOptions, BlockOnNetwork, TokenAmountOnNetwork, - TransactionCostEstimationResponse, + TransactionCostResponse, } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { extendUserAgentIfBackend } from "./userAgent"; @@ -116,14 +115,24 @@ export class ApiNetworkProvider implements INetworkProvider { const data = response["data"] ?? {}; return TransactionOnNetwork.fromSimulateResponse(transaction, data["result"] ?? {}); } - async estimateTransactionCost(tx: Transaction): Promise { + + async estimateTransactionCost(tx: Transaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transaction/cost", transaction); - return TransactionCostEstimationResponse.fromHttpResponse(response.data); + return TransactionCostResponse.fromHttpResponse(response.data); } - async sendTransactions(txs: Transaction[]): Promise { - return await this.backingProxyNetworkProvider.sendTransactions(txs); + async sendTransactions(txs: Transaction[]): Promise<[number, string[]]> { + const data = txs.map((tx) => prepareTransactionForBroadcasting(tx)); + + const response = await this.doPostGeneric("transaction/send-multiple", data); + const numSent = Number(response.data["numOfSentTxs"] ?? 0); + const hashes = Array(txs.length).fill(null); + + for (let i = 0; i < txs.length; i++) { + hashes[i] = response.data.txsHashes[i.toString()] || null; + } + return [numSent, hashes]; } async getTransaction(txHash: string): Promise { @@ -154,6 +163,7 @@ export class ApiNetworkProvider implements INetworkProvider { }); return await awaiter.awaitOnCondition(transactionHash, condition); } + async awaitTransactionCompleted(transactionHash: string, options?: AwaitingOptions): Promise { if (!options) { options = new AwaitingOptions(); @@ -178,10 +188,6 @@ export class ApiNetworkProvider implements INetworkProvider { return TokenAmountOnNetwork.fromApiResponse(response); } - async getGuardianData(address: Address): Promise { - return await this.backingProxyNetworkProvider.getGuardianData(address); - } - async getFungibleTokensOfAccount(address: Address, pagination?: IPagination): Promise { pagination = pagination || defaultPagination; @@ -212,17 +218,6 @@ export class ApiNetworkProvider implements INetworkProvider { return definition; } - async getMexPairs(pagination?: IPagination): Promise { - let url = `mex/pairs`; - if (pagination) { - url = `${url}?from=${pagination.from}&size=${pagination.size}`; - } - - const response: any[] = await this.doGetGeneric(url); - - return response.map((item) => PairOnNetwork.fromApiHttpResponse(item)); - } - async queryContract(query: SmartContractQuery): Promise { try { const request = new ContractQueryRequest(query).toHttpRequest(); diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index f69c63df0..53de8f5d3 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -12,7 +12,7 @@ import { AccountStorageEntry, AwaitingOptions, TokenAmountOnNetwork, - TransactionCostEstimationResponse, + TransactionCostResponse, } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; @@ -71,12 +71,12 @@ export interface INetworkProvider { * Estimates the cost of a transaction. * */ - estimateTransactionCost(tx: Transaction): Promise; + estimateTransactionCost(tx: Transaction): Promise; /** * Broadcasts a list of already-signed transactions. */ - sendTransactions(txs: Transaction[]): Promise; + sendTransactions(txs: Transaction[]): Promise<[number, string[]]>; /** * Fetches the state of a transaction. diff --git a/src/networkProviders/networkConfig.ts b/src/networkProviders/networkConfig.ts index b33640e51..0efbff2c4 100644 --- a/src/networkProviders/networkConfig.ts +++ b/src/networkProviders/networkConfig.ts @@ -31,9 +31,9 @@ export class NetworkConfig { public extraGasLimitForGuardedTransactions: bigint; /** - * The number of rounds per epoch. + * The number of shards. */ - public numberOfShards: number; + public numShards: number; /** * The round duration. @@ -42,7 +42,7 @@ export class NetworkConfig { /** * The number of rounds per epoch. */ - public roundsPerEpoch: number; + public numRoundsPerEpoch: number; /** * The genesis timestamp @@ -50,16 +50,16 @@ export class NetworkConfig { public genesisTimestamp: number; constructor() { - this.chainID = "T"; - this.gasPerDataByte = 1500n; + this.chainID = ""; + this.gasPerDataByte = 0n; this.genesisTimestamp = 0; this.roundDuration = 0; - this.roundsPerEpoch = 0; - this.minGasLimit = 50000n; - this.minGasPrice = 1000000000n; + this.numRoundsPerEpoch = 0; + this.minGasLimit = 0n; + this.minGasPrice = 0n; this.extraGasLimitForGuardedTransactions = 0n; this.gasPriceModifier = 1; - this.numberOfShards = 0; + this.numShards = 0; } /** @@ -75,9 +75,9 @@ export class NetworkConfig { networkConfig.minGasLimit = BigInt(payload["erd_min_gas_limit"]); networkConfig.minGasPrice = BigInt(payload["erd_min_gas_price"]); networkConfig.extraGasLimitForGuardedTransactions = BigInt(payload["erd_extra_gas_limit_guarded_tx"]); - networkConfig.numberOfShards = Number(payload["erd_num_shards_without_meta"]); + networkConfig.numShards = Number(payload["erd_num_shards_without_meta"]); networkConfig.roundDuration = Number(payload["erd_round_duration"]); - networkConfig.roundsPerEpoch = Number(payload["erd_rounds_per_epoch"]); + networkConfig.numRoundsPerEpoch = Number(payload["erd_rounds_per_epoch"]); networkConfig.genesisTimestamp = Number(payload["erd_start_time"]); return networkConfig; diff --git a/src/networkProviders/networkStatus.ts b/src/networkProviders/networkStatus.ts index d6d8a36cc..0988a1707 100644 --- a/src/networkProviders/networkStatus.ts +++ b/src/networkProviders/networkStatus.ts @@ -5,7 +5,7 @@ export class NetworkStatus { raw: Record = {}; /** - * The block nonce. + * The block timestamp. */ public blockTimestamp: number; @@ -15,7 +15,7 @@ export class NetworkStatus { public blockNonce: bigint; /** - * The Highest final nonce. + * The highest final nonce. */ public highestFinalNonce: bigint; @@ -25,7 +25,7 @@ export class NetworkStatus { public currentRound: bigint; /** - * The epoch number. + * The current epoch. */ public currentEpoch: number; diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 4685f1ca3..c0a28820c 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -143,9 +143,10 @@ describe("test network providers on devnet: Proxy and API", function () { assert.equal(await apiProvider.sendTransaction(txs[0]), expectedHashes[0]); assert.equal(await proxyProvider.sendTransaction(txs[1]), expectedHashes[1]); - - assert.deepEqual(await apiProvider.sendTransactions(txs), expectedHashes); - assert.deepEqual(await proxyProvider.sendTransactions(txs), expectedHashes); + const [, apiHashes] = await apiProvider.sendTransactions(txs); + const [, proxyHashes] = await proxyProvider.sendTransactions(txs); + assert.deepEqual(apiHashes, expectedHashes); + assert.deepEqual(proxyHashes, expectedHashes); }); it("should have same response for getTransaction()", async function () { diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index dc298f16c..6333a757b 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -275,8 +275,8 @@ describe("ProxyNetworkProvider Tests", function () { null, "30274b60b5635f981fa89ccfe726a34ca7121caa5d34123021c77a5c64cc9163", ]; - const hashes = await proxy.sendTransactions(txs); - assert.equal(hashes.length, 3); + const [numOfSentTxs, hashes] = await proxy.sendTransactions(txs); + assert.equal(numOfSentTxs, 2); assert.deepEqual(hashes, expectedHashes); }); diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 0fea2c224..47657fe02 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -12,7 +12,7 @@ import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; -import { INetworkProvider, IPagination } from "./interface"; +import { INetworkProvider } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkProviderConfig } from "./networkProviderConfig"; import { NetworkStatus } from "./networkStatus"; @@ -22,7 +22,7 @@ import { AwaitingOptions, BlockOnNetwork, TokenAmountOnNetwork, - TransactionCostEstimationResponse, + TransactionCostResponse, } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; import { extendUserAgentIfBackend } from "./userAgent"; @@ -52,6 +52,7 @@ export class ProxyNetworkProvider implements INetworkProvider { const networkStatus = NetworkStatus.fromHttpResponse(response.status); return networkStatus; } + async getBlock(args: { shard: number; blockHash?: string; blockNonce?: bigint }): Promise { let response; if (args.blockHash) { @@ -120,25 +121,26 @@ export class ProxyNetworkProvider implements INetworkProvider { return TransactionOnNetwork.fromSimulateResponse(transaction, response["result"] ?? {}); } - async estimateTransactionCost(tx: Transaction): Promise { + async estimateTransactionCost(tx: Transaction): Promise { const transaction = prepareTransactionForBroadcasting(tx); const response = await this.doPostGeneric("transaction/cost", transaction); - return TransactionCostEstimationResponse.fromHttpResponse(response); + return TransactionCostResponse.fromHttpResponse(response); } - async sendTransactions(txs: Transaction[]): Promise { + async sendTransactions(txs: Transaction[]): Promise<[number, string[]]> { const data = txs.map((tx) => prepareTransactionForBroadcasting(tx)); const response = await this.doPostGeneric("transaction/send-multiple", data); + const numSent = Number(response["numOfSentTxs"] ?? 0); const hashes = Array(txs.length).fill(null); for (let i = 0; i < txs.length; i++) { hashes[i] = response.txsHashes[i.toString()] || null; } - return hashes; + return [numSent, hashes]; } - async getTransaction(txHash: string, _?: boolean): Promise { + async getTransaction(txHash: string): Promise { const url = this.buildUrlWithQueryParameters(`transaction/${txHash}`, { withResults: "true" }); const [data, status] = await Promise.all([this.doGetGeneric(url), this.getTransactionStatus(txHash)]); return TransactionOnNetwork.fromProxyHttpResponse(txHash, data.transaction, status); @@ -186,7 +188,7 @@ export class ProxyNetworkProvider implements INetworkProvider { return TokenAmountOnNetwork.fromProxyResponse(response["tokenData"]); } - async getFungibleTokensOfAccount(address: Address, _pagination?: IPagination): Promise { + async getFungibleTokensOfAccount(address: Address): Promise { const url = `address/${address.toBech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); @@ -197,7 +199,7 @@ export class ProxyNetworkProvider implements INetworkProvider { return tokens; } - async getNonFungibleTokensOfAccount(address: Address, _pagination?: IPagination): Promise { + async getNonFungibleTokensOfAccount(address: Address): Promise { const url = `address/${address.toBech32()}/esdt`; const response = await this.doGetGeneric(url); const responseItems: any[] = Object.values(response.esdts); diff --git a/src/networkProviders/resources.ts b/src/networkProviders/resources.ts index 5d1a82364..3a555857f 100644 --- a/src/networkProviders/resources.ts +++ b/src/networkProviders/resources.ts @@ -108,7 +108,7 @@ export class BlockOnNetwork { export class BlockCoordinates { nonce: bigint = 0n; hash: string = ""; - rootHash?: string; + rootHash: string = ""; constructor(init?: Partial) { Object.assign(this, init); } @@ -129,6 +129,7 @@ export class AccountStorageEntry { address: Address = Address.empty(); key: string = ""; value: string = ""; + constructor(init?: Partial) { Object.assign(this, init); } @@ -151,13 +152,13 @@ export class AwaitingOptions { patienceInMilliseconds: number = DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS; } -export class TransactionCostEstimationResponse { +export class TransactionCostResponse { raw: Record = {}; gasLimit: number = 0; status: TransactionStatus = TransactionStatus.createUnknown(); - static fromHttpResponse(payload: any): TransactionCostEstimationResponse { - const result = new TransactionCostEstimationResponse(); + static fromHttpResponse(payload: any): TransactionCostResponse { + const result = new TransactionCostResponse(); result.raw = payload; result.gasLimit = payload["txGasUnits"] ?? 0; result.status = new TransactionStatus(""); @@ -171,6 +172,7 @@ export class TokenAmountOnNetwork { token: Token = new Token({ identifier: "" }); amount: bigint = 0n; block_coordinates?: BlockCoordinates; + constructor(init?: Partial) { Object.assign(this, init); } diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 2bfdf9b1f..bd689424a 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -17,7 +17,7 @@ import { AwaitingOptions, BlockOnNetwork, TokenAmountOnNetwork, - TransactionCostEstimationResponse, + TransactionCostResponse, } from "../networkProviders/resources"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { Token } from "../tokens"; @@ -80,7 +80,7 @@ export class MockNetworkProvider implements INetworkProvider { ): AccountOnNetwork { throw new Error("Method not implemented."); } - estimateTransactionCost(_tx: Transaction): Promise { + estimateTransactionCost(_tx: Transaction): Promise { throw new Error("Method not implemented."); } awaitTransactionOnCondition( diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index ac6989816..96de9e707 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -100,6 +100,7 @@ export function b64ToHex(value: string): string { export function importJsonBig(value: string): string { return Buffer.from(value, "base64").toString("hex"); } + export const stringifyBigIntJSON = (jsonString: any): any => { const JSONBig = require("json-bigint")({ constructorAction: "ignore" }); try { From d2847bcd8a056a4c90ac0c2b238482ad37b8509b Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 21 Jan 2025 12:33:23 +0200 Subject: [PATCH 131/214] Fix compiling errors --- src/entrypoints/entrypoints.ts | 2 +- src/testutils/mockNetworkProvider.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 45b4a2cb2..6845346e4 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -68,7 +68,7 @@ class NetworkEntrypoint { return (await this.networkProvider.getAccount(address)).nonce; } - sendTransactions(transactions: Transaction[]): Promise { + sendTransactions(transactions: Transaction[]): Promise<[number, string[]]> { return this.networkProvider.sendTransactions(transactions); } diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index bd689424a..9b9aa819b 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -106,7 +106,7 @@ export class MockNetworkProvider implements INetworkProvider { getNonFungibleTokensOfAccount(_address: Address, _pagination?: IPagination): Promise { throw new Error("Method not implemented."); } - sendTransactions(_txs: Transaction[]): Promise { + sendTransactions(_txs: Transaction[]): Promise<[number, string[]]> { throw new Error("Method not implemented."); } getDefinitionOfFungibleToken(_tokenIdentifier: string): Promise { From bf102a7001517bfb19d654eda4f4b3d49f907e6a Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 21 Jan 2025 12:36:50 +0200 Subject: [PATCH 132/214] add back transaction Status tests --- src/networkProviders/providers.dev.net.spec.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index c0a28820c..2e0615cce 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -170,6 +170,22 @@ describe("test network providers on devnet: Proxy and API", function () { } }); + it("should have same response for getTransactionStatus()", async function () { + this.timeout(20000); + + let hashes = [ + "08acf8cbd71306a56eb58f9593cb2e23f109c94e27acdd906c82a5c3a5f84d9d", + "410efb1db2ab86678b8dbc503beb695b5b7d52754fb0de86c09cbb433de5f6a8", + ]; + + for (const hash of hashes) { + let apiResponse = await apiProvider.getTransactionStatus(hash); + let proxyResponse = await proxyProvider.getTransactionStatus(hash); + + assert.deepEqual(apiResponse, proxyResponse, `transaction: ${hash}`); + } + }); + // TODO: Strive to have as little differences as possible between Proxy and API. function ignoreKnownTransactionDifferencesBetweenProviders( apiResponse: TransactionOnNetwork, From 4ff440887a82ce10a7c66b7f4f877aeabcf62383 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 21 Jan 2025 14:27:49 +0200 Subject: [PATCH 133/214] Add account awaiter --- src/errors.ts | 9 ++ .../accountAwaiter..dev.net.spec.ts | 78 +++++++++++++ src/networkProviders/accountAwaiter.ts | 104 ++++++++++++++++++ src/networkProviders/apiNetworkProvider.ts | 17 ++- src/networkProviders/interface.ts | 2 +- src/networkProviders/proxyNetworkProvider.ts | 17 ++- src/testutils/mockNetworkProvider.ts | 27 ++++- 7 files changed, 242 insertions(+), 12 deletions(-) create mode 100644 src/networkProviders/accountAwaiter..dev.net.spec.ts create mode 100644 src/networkProviders/accountAwaiter.ts diff --git a/src/errors.ts b/src/errors.ts index 67878c12f..9eb4d610f 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -457,3 +457,12 @@ export class ErrInvalidNetworkProviderKind extends Err { super("Invalid network provider kind. Choose between `api` and `proxy`."); } } + +/** + * Signals that the account condition was not reached + */ +export class ExpectedAccountConditionNotReachedError extends Err { + public constructor() { + super("The expected account condition was not reached."); + } +} diff --git a/src/networkProviders/accountAwaiter..dev.net.spec.ts b/src/networkProviders/accountAwaiter..dev.net.spec.ts new file mode 100644 index 000000000..755c040a6 --- /dev/null +++ b/src/networkProviders/accountAwaiter..dev.net.spec.ts @@ -0,0 +1,78 @@ +import { assert } from "chai"; +import { Address } from "../address"; +import { MarkCompleted, MockNetworkProvider, Wait } from "../testutils/mockNetworkProvider"; +import { createAccountBalance } from "../testutils/utils"; +import { loadTestWallet } from "../testutils/wallets"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; +import { AccountAwaiter } from "./accountAwaiter"; +import { AccountOnNetwork } from "./accounts"; +import { ApiNetworkProvider } from "./apiNetworkProvider"; + +describe("AccountAwaiter Tests", () => { + const provider = new MockNetworkProvider(); + + const watcher = new AccountAwaiter({ + fetcher: provider, + pollingIntervalInMilliseconds: 42, + timeoutIntervalInMilliseconds: 42 * 42, + patienceTimeInMilliseconds: 0, + }); + + it("should await on balance increase", async () => { + const alice = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + // alice account is created with 1000 EGLD + const initialBalance = (await provider.getAccount(alice)).balance; + + // Mock balance timeline + provider.mockAccountBalanceTimelineByAddress(alice, [ + new Wait(40), + new Wait(40), + new Wait(45), + new MarkCompleted(), + ]); + + const condition = (account: AccountOnNetwork) => { + return account.balance === initialBalance + createAccountBalance(7); + }; + + const account = await watcher.awaitOnCondition(alice, condition); + + assert.equal(account.balance, createAccountBalance(1007)); + }); + + it("should await for account balance increase on the network", async function () { + this.timeout(10000); + const alice = await loadTestWallet("alice"); + const aliceAddress = alice.getAddress(); + const frank = Address.newFromBech32("erd1kdl46yctawygtwg2k462307dmz2v55c605737dp3zkxh04sct7asqylhyv"); + + const api = new ApiNetworkProvider("https://devnet-api.multiversx.com"); + const watcher = new AccountAwaiter({ fetcher: api }); + const txComputer = new TransactionComputer(); + const value = 100_000n; + + // Create and sign the transaction + const transaction = new Transaction({ + sender: aliceAddress, + receiver: frank, + gasLimit: 50000n, + chainID: "D", + value, + }); + transaction.nonce = (await api.getAccount(aliceAddress)).nonce; + transaction.signature = await alice.signer.sign(txComputer.computeBytesForSigning(transaction)); + + const initialBalance = (await api.getAccount(frank)).balance; + + const condition = (account: AccountOnNetwork) => { + return account.balance === initialBalance + value; + }; + + await api.sendTransaction(transaction); + + const accountOnNetwork = await watcher.awaitOnCondition(frank, condition); + + assert.equal(accountOnNetwork.balance, initialBalance + value); + }); +}); diff --git a/src/networkProviders/accountAwaiter.ts b/src/networkProviders/accountAwaiter.ts new file mode 100644 index 000000000..8f3ee8ced --- /dev/null +++ b/src/networkProviders/accountAwaiter.ts @@ -0,0 +1,104 @@ +import { Address } from "../address"; +import { ExpectedAccountConditionNotReachedError } from "../errors"; +import { AccountOnNetwork } from "./accounts"; +import { + DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS, + DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS, + DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS, +} from "./constants"; + +interface IAccountFetcher { + getAccount(address: Address): Promise; +} + +export class AccountAwaiter { + private fetcher: IAccountFetcher; + private pollingIntervalInMilliseconds: number; + private timeoutIntervalInMilliseconds: number; + private patienceTimeInMilliseconds: number; + + /** + * AccountAwaiter allows one to await until a specific event occurs on a given address. + * + * @param fetcher - Used to fetch the account of the network. + * @param pollingIntervalInMilliseconds - The polling interval, in milliseconds. + * @param timeoutIntervalInMilliseconds - The timeout, in milliseconds. + * @param patienceTimeInMilliseconds - The patience, an extra time (in milliseconds) to wait, after the account has reached its desired condition. + */ + constructor(options: { + fetcher: IAccountFetcher; + pollingIntervalInMilliseconds?: number; + timeoutIntervalInMilliseconds?: number; + patienceTimeInMilliseconds?: number; + }) { + this.fetcher = options.fetcher; + + this.pollingIntervalInMilliseconds = + options.pollingIntervalInMilliseconds ?? DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS; + + this.timeoutIntervalInMilliseconds = + options.timeoutIntervalInMilliseconds ?? DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS; + + this.patienceTimeInMilliseconds = + options.patienceTimeInMilliseconds ?? DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS; + } + + /** + * Waits until the condition is satisfied. + * + * @param address - The address to monitor. + * @param condition - A callable that evaluates the desired condition. + */ + async awaitOnCondition( + address: Address, + condition: (account: AccountOnNetwork) => boolean, + ): Promise { + const doFetch = async () => await this.fetcher.getAccount(address); + + return this.awaitConditionally(condition, doFetch, new ExpectedAccountConditionNotReachedError()); + } + + private async awaitConditionally( + isSatisfied: (account: AccountOnNetwork) => boolean, + doFetch: () => Promise, + error: Error, + ): Promise { + let isConditionSatisfied = false; + let fetchedData: AccountOnNetwork | null = null; + + const maxNumberOfRetries = Math.floor(this.timeoutIntervalInMilliseconds / this.pollingIntervalInMilliseconds); + + let numberOfRetries = 0; + + while (numberOfRetries < maxNumberOfRetries) { + try { + fetchedData = await doFetch(); + isConditionSatisfied = isSatisfied(fetchedData); + + if (isConditionSatisfied) { + break; + } + } catch (ex) { + throw ex; + } + + numberOfRetries += 1; + await this._sleep(this.pollingIntervalInMilliseconds); + } + + if (!fetchedData || !isConditionSatisfied) { + throw error; + } + + if (this.patienceTimeInMilliseconds) { + await this._sleep(this.patienceTimeInMilliseconds); + return doFetch(); + } + + return fetchedData; + } + + private async _sleep(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); + } +} diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index fff408c6b..e7030d8c2 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -8,6 +8,7 @@ import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../tran import { TransactionStatus } from "../transactionStatus"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; +import { AccountAwaiter } from "./accountAwaiter"; import { AccountOnNetwork } from "./accounts"; import { defaultAxiosConfig, defaultPagination } from "./config"; import { BaseUserAgent } from "./constants"; @@ -88,15 +89,21 @@ export class ApiNetworkProvider implements INetworkProvider { return account; } - awaitAccountOnCondition( - _address: Address, - _condition: (account: AccountOnNetwork) => boolean, + async awaitAccountOnCondition( + address: Address, + condition: (account: AccountOnNetwork) => boolean, options?: AwaitingOptions, - ): AccountOnNetwork { + ): Promise { if (!options) { options = new AwaitingOptions(); } - throw new Error("Method not implemented."); + const awaiter = new AccountAwaiter({ + fetcher: this, + patienceTimeInMilliseconds: options.patienceInMilliseconds, + pollingIntervalInMilliseconds: options.pollingIntervalInMilliseconds, + timeoutIntervalInMilliseconds: options.timeoutInMilliseconds, + }); + return await awaiter.awaitOnCondition(address, condition); } async sendTransaction(tx: Transaction): Promise { diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 53de8f5d3..8290c8bb3 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -54,7 +54,7 @@ export interface INetworkProvider { address: Address, condition: (account: AccountOnNetwork) => boolean, options?: AwaitingOptions, - ): AccountOnNetwork; + ): Promise; /** * Broadcasts an already-signed transaction. diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 47657fe02..ed454ca0a 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -8,6 +8,7 @@ import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../tran import { TransactionStatus } from "../transactionStatus"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; +import { AccountAwaiter } from "./accountAwaiter"; import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; import { BaseUserAgent } from "./constants"; @@ -94,15 +95,21 @@ export class ProxyNetworkProvider implements INetworkProvider { return account; } - awaitAccountOnCondition( - _address: Address, - _condition: (account: AccountOnNetwork) => boolean, + async awaitAccountOnCondition( + address: Address, + condition: (account: AccountOnNetwork) => boolean, options?: AwaitingOptions, - ): AccountOnNetwork { + ): Promise { if (!options) { options = new AwaitingOptions(); } - throw new Error("Method not implemented."); + const awaiter = new AccountAwaiter({ + fetcher: this, + patienceTimeInMilliseconds: options.patienceInMilliseconds, + pollingIntervalInMilliseconds: options.pollingIntervalInMilliseconds, + timeoutIntervalInMilliseconds: options.timeoutInMilliseconds, + }); + return await awaiter.awaitOnCondition(address, condition); } async sendTransaction(tx: Transaction): Promise { diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 9b9aa819b..badc181ab 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -77,7 +77,7 @@ export class MockNetworkProvider implements INetworkProvider { _address: Address, _condition: (account: AccountOnNetwork) => boolean, _options?: AwaitingOptions, - ): AccountOnNetwork { + ): Promise { throw new Error("Method not implemented."); } estimateTransactionCost(_tx: Transaction): Promise { @@ -159,6 +159,27 @@ export class MockNetworkProvider implements INetworkProvider { this.getTransactionResponders.unshift(new GetTransactionResponder(predicate, response)); } + mockAccountBalanceTimelineByAddress(address: Address, timelinePoints: Array): void { + const executeTimeline = async () => { + for (const point of timelinePoints) { + if (point instanceof MarkCompleted) { + // Mark account condition as reached + this.mockUpdateAccount(address, (account) => { + account.balance += createAccountBalance(7); + }); + } else if (point instanceof Wait) { + // Wait for the specified time + await this.sleep(point.milliseconds); + } + } + }; + + // Start the timeline execution in a separate async "thread" + executeTimeline().catch((err) => { + console.error("Error executing timeline:", err); + }); + } + async mockTransactionTimeline(transaction: Transaction, timelinePoints: any[]): Promise { return this.mockTransactionTimelineByHash(transaction.getHash(), timelinePoints); } @@ -187,6 +208,10 @@ export class MockNetworkProvider implements INetworkProvider { } } + private sleep(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); + } + async getAccount(address: Address): Promise { let account = this.accounts.get(address.toBech32()); if (account) { From 8e222fdc23a2694224b78ceecebe177dd0ecadb7 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 21 Jan 2025 15:25:44 +0200 Subject: [PATCH 134/214] Fix file name --- ...tAwaiter..dev.net.spec.ts => accountAwaiter.dev.net.spec.ts} | 2 +- src/networkProviders/proxyNetworkProvider.dev.net.spec.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename src/networkProviders/{accountAwaiter..dev.net.spec.ts => accountAwaiter.dev.net.spec.ts} (99%) diff --git a/src/networkProviders/accountAwaiter..dev.net.spec.ts b/src/networkProviders/accountAwaiter.dev.net.spec.ts similarity index 99% rename from src/networkProviders/accountAwaiter..dev.net.spec.ts rename to src/networkProviders/accountAwaiter.dev.net.spec.ts index 755c040a6..3322216ee 100644 --- a/src/networkProviders/accountAwaiter..dev.net.spec.ts +++ b/src/networkProviders/accountAwaiter.dev.net.spec.ts @@ -42,7 +42,7 @@ describe("AccountAwaiter Tests", () => { }); it("should await for account balance increase on the network", async function () { - this.timeout(10000); + this.timeout(20000); const alice = await loadTestWallet("alice"); const aliceAddress = alice.getAddress(); const frank = Address.newFromBech32("erd1kdl46yctawygtwg2k462307dmz2v55c605737dp3zkxh04sct7asqylhyv"); diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 6333a757b..07ac78785 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -349,7 +349,7 @@ describe("ProxyNetworkProvider Tests", function () { }); it("should send and await for completed transaction", async function () { - this.timeout(40000); + this.timeout(50000); const bob = await loadTestWallet("bob"); const transactionComputer = new TransactionComputer(); let transaction = new Transaction({ From e0a48890672c306a9037e139122b17a8793a1be1 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 21 Jan 2025 15:42:15 +0200 Subject: [PATCH 135/214] Add readonly to properties --- src/networkProviders/accountAwaiter.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/networkProviders/accountAwaiter.ts b/src/networkProviders/accountAwaiter.ts index 8f3ee8ced..72b27a98b 100644 --- a/src/networkProviders/accountAwaiter.ts +++ b/src/networkProviders/accountAwaiter.ts @@ -12,10 +12,10 @@ interface IAccountFetcher { } export class AccountAwaiter { - private fetcher: IAccountFetcher; - private pollingIntervalInMilliseconds: number; - private timeoutIntervalInMilliseconds: number; - private patienceTimeInMilliseconds: number; + private readonly fetcher: IAccountFetcher; + private readonly pollingIntervalInMilliseconds: number; + private readonly timeoutIntervalInMilliseconds: number; + private readonly patienceTimeInMilliseconds: number; /** * AccountAwaiter allows one to await until a specific event occurs on a given address. From 740ab32836ed25c2dd25a8cf6fd4970c764c8fee Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 22 Jan 2025 15:46:48 +0200 Subject: [PATCH 136/214] Add missing functions for controller --- src/tokenManagement/resources.ts | 11 + .../tokenManagementController.ts | 196 ++++++++++++++++++ ...okenManagementTransactionsOutcomeParser.ts | 149 ++++++++++++- 3 files changed, 355 insertions(+), 1 deletion(-) diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 90c38eb3d..2c0dd60cb 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -117,3 +117,14 @@ export type MintNftOutput = { }; export type EsdtOutput = { tokenIdentifier: string }; +export type ModifyingCreatorOutput = { tokenIdentifier: string; nonce: bigint; creator: Address }; +export type UpdateAttibutesOutput = { tokenIdentifier: string; nonce: bigint; caller: Address }; +export type ChangeToDynamicOutput = { tokenName: string; tokenTicker: string; tokenType: string }; +export type UpdateTokenIDOutput = { caller: Address; tokenIdentifier: string; token: string }; +export type RegisterDynamicOutput = { + tokenIdentifier: string; + tokenName: string; + tokenTicker: string; + tokenType: string; + numOfDecimals: number; +}; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index 45d99ed62..a00400d4e 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -491,4 +491,200 @@ export class TokenManagementController { parseBurnQuantity(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { return this.parser.parseBurnQuantity(transactionOnNetwork); } + + async createTransactionForModifyingRoyalties( + sender: IAccount, + nonce: bigint, + options: resources.ModifyRoyaltiesInput, + ): Promise { + const transaction = this.factory.createTransactionForModifyingRoyalties(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedModifyRoyalties(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseModifyRoyalties(transaction); + } + + parseModifyRoyalties(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { + return this.parser.parseModifyRoyalties(transactionOnNetwork); + } + + async createTransactionForSettingNewUris( + sender: IAccount, + nonce: bigint, + options: resources.SetNewUriInput, + ): Promise { + const transaction = this.factory.createTransactionForSettingNewUris(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedSetNewUris(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseSetNewUris(transaction); + } + + parseSetNewUris(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { + return this.parser.parseSetNewUris(transactionOnNetwork); + } + + async createTransactionForModifyingCreator( + sender: IAccount, + nonce: bigint, + options: resources.SetNewUriInput, + ): Promise { + const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedModifyCreator(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseModifyCreator(transaction); + } + + parseModifyCreator(transactionOnNetwork: TransactionOnNetwork): resources.ModifyingCreatorOutput[] { + return this.parser.parseModifyCreator(transactionOnNetwork); + } + + async createTransactionForUpdatingMetadata( + sender: IAccount, + nonce: bigint, + options: resources.SetNewUriInput, + ): Promise { + const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedUpdateMetadata(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseUpdateMetadata(transaction); + } + + parseUpdateMetadata(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { + return this.parser.parseUpdateMetadata(transactionOnNetwork); + } + + async createTransactionForMetadataRecreate( + sender: IAccount, + nonce: bigint, + options: resources.SetNewUriInput, + ): Promise { + const transaction = this.factory.createTransactionForMetadataRecreate(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedMetadataRecreate(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseMetadataRecreate(transaction); + } + + parseMetadataRecreate(transactionOnNetwork: TransactionOnNetwork): resources.EsdtOutput[] { + return this.parser.parseMetadataRecreate(transactionOnNetwork); + } + + async createTransactionForChangingTokenToDynamic( + sender: IAccount, + nonce: bigint, + options: resources.SetNewUriInput, + ): Promise { + const transaction = this.factory.createTransactionForChangingTokenToDynamic(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedChangeTokenToDynamic(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseChangeTokenToDynamic(transaction); + } + + parseChangeTokenToDynamic(transactionOnNetwork: TransactionOnNetwork): resources.ChangeToDynamicOutput[] { + return this.parser.parseChangeTokenToDynamic(transactionOnNetwork); + } + + async createTransactionForUpdatingTokenId( + sender: IAccount, + nonce: bigint, + options: resources.UpdateTokenIDInput, + ): Promise { + const transaction = this.factory.createTransactionForUpdatingTokenId(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedUpdateTokenId(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return transaction; + } + + async createTransactionForRegisteringDynamicToken( + sender: IAccount, + nonce: bigint, + options: resources.RegisteringDynamicTokenInput, + ): Promise { + const transaction = this.factory.createTransactionForRegisteringDynamicToken(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedRegisterDynamicToken(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseRegisterDynamicToken(transaction); + } + + parseRegisterDynamicToken(transactionOnNetwork: TransactionOnNetwork): resources.RegisterDynamicOutput[] { + return this.parser.parseRegisterDynamicToken(transactionOnNetwork); + } + + async createTransactionForRegisteringDynamicTokenAndSettingRoles( + sender: IAccount, + nonce: bigint, + options: resources.RegisteringDynamicTokenInput, + ): Promise { + const transaction = this.factory.createTransactionForRegisteringDynamicAndSettingRoles(sender.address, options); + + transaction.nonce = nonce; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedRegisterDynamicTokenAndSettingRoles(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseRegisterDynamicTokenAndSettingRoles(transaction); + } + + parseRegisterDynamicTokenAndSettingRoles( + transactionOnNetwork: TransactionOnNetwork, + ): resources.RegisterDynamicOutput[] { + return this.parser.parseRegisterDynamicTokenAndSettingRoles(transactionOnNetwork); + } } diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index 8f9770706..4fea39028 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -4,7 +4,14 @@ import { ErrParseTransactionOutcome } from "../errors"; import { TransactionEvent } from "../transactionEvents"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; -import { MintNftOutput, SpecialRoleOutput } from "./resources"; +import { + ChangeToDynamicOutput, + MintNftOutput, + ModifyingCreatorOutput, + RegisterDynamicOutput, + SpecialRoleOutput, + UpdateAttibutesOutput, +} from "./resources"; export class TokenManagementTransactionsOutcomeParser { constructor() {} @@ -349,6 +356,146 @@ export class TokenManagementTransactionsOutcomeParser { }; } + parseModifyRoyalties(transaction: TransactionOnNetwork): import("./resources").EsdtOutput[] { + this.ensureNoError(transaction.logs.events); + + const events = findEventsByIdentifier(transaction, "ESDTModifyRoyalties"); + return events.map((event) => this.getOutputForESDTModifyRoyaltiesEvent(event)); + } + + private getOutputForESDTModifyRoyaltiesEvent(event: TransactionEvent): { + tokenIdentifier: string; + nonce: bigint; + royalties: bigint; + } { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const royalties = this.extractAmount(event); + + return { + tokenIdentifier: tokenIdentifier, + nonce: nonce, + royalties: royalties, + }; + } + + parseSetNewUris(transaction: TransactionOnNetwork): import("./resources").EsdtOutput[] { + this.ensureNoError(transaction.logs.events); + + const events = findEventsByIdentifier(transaction, "ESDTSetNewURIs"); + return events.map((event) => this.getOutputForESDTSetNewURIsEvent(event)); + } + + private getOutputForESDTSetNewURIsEvent(event: TransactionEvent): { + tokenIdentifier: string; + nonce: bigint; + royalties: bigint; + } { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const royalties = this.extractAmount(event); + + return { + tokenIdentifier: tokenIdentifier, + nonce: nonce, + royalties: royalties, + }; + } + + parseModifyCreator(transaction: TransactionOnNetwork): ModifyingCreatorOutput[] { + this.ensureNoError(transaction.logs.events); + + const events = findEventsByIdentifier(transaction, "ESDTModifyCreator"); + return events.map((event) => this.getOutputForESDTModifyCreatorEvent(event)); + } + + private getOutputForESDTModifyCreatorEvent(event: TransactionEvent): ModifyingCreatorOutput { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const creator = Address.newFromBech32(this.extractAddress(event)); + + return { tokenIdentifier, nonce, creator }; + } + + parseUpdateMetadata(transaction: TransactionOnNetwork): UpdateAttibutesOutput[] { + this.ensureNoError(transaction.logs.events); + + const events = findEventsByIdentifier(transaction, "ESDTMetaDataUpdate"); + return events.map((event) => this.getOutputForESDTUpdateMetadataEvent(event)); + } + + private getOutputForESDTUpdateMetadataEvent(event: TransactionEvent): UpdateAttibutesOutput { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const caller = Address.newFromBech32(this.extractAddress(event)); + + return { tokenIdentifier, nonce, caller }; + } + + parseMetadataRecreate(transaction: TransactionOnNetwork): UpdateAttibutesOutput[] { + this.ensureNoError(transaction.logs.events); + + const events = findEventsByIdentifier(transaction, "ESDTMetaDataRecreate"); + return events.map((event) => this.getOutputForESDTMetadataRecreateEvent(event)); + } + + private getOutputForESDTMetadataRecreateEvent(event: TransactionEvent): UpdateAttibutesOutput { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const caller = this.extractAddress(event); + + return { tokenIdentifier, nonce, caller: Address.newFromBech32(caller) }; + } + + parseChangeTokenToDynamic(transaction: TransactionOnNetwork): ChangeToDynamicOutput[] { + this.ensureNoError(transaction.logs.events); + + const events = findEventsByIdentifier(transaction, "changeToDynamic"); + return events.map((event) => this.getOutputForChangeToDynamicEvent(event)); + } + + private getOutputForChangeToDynamicEvent(event: TransactionEvent): ChangeToDynamicOutput { + const tokenName = event.topics[1]?.length ? "" : event.topics[1].toString(); + const tokenTicker = event.topics[2]?.length ? "" : event.topics[2].toString(); + const tokenType = event.topics[3]?.length ? "" : event.topics[3].toString(); + + return { tokenName, tokenTicker, tokenType }; + } + + parseRegisterDynamicToken(transaction: TransactionOnNetwork): RegisterDynamicOutput[] { + this.ensureNoError(transaction.logs.events); + + const events = findEventsByIdentifier(transaction, "registerDynamic"); + return events.map((event) => this.getOutputForRegisterDynamicToken(event)); + } + + private getOutputForRegisterDynamicToken(event: TransactionEvent): RegisterDynamicOutput { + const tokenIdentifier = event.topics[0]?.length ? "" : event.topics[0].toString(); + const tokenName = event.topics[1]?.length ? "" : event.topics[1].toString(); + const tokenTicker = event.topics[2]?.length ? "" : event.topics[2].toString(); + const tokenType = event.topics[3]?.length ? "" : event.topics[3].toString(); + const numOfDecimals = event.topics[4]?.length ? 0 : Number(Buffer.from(event.topics[4]).toString()); + + return { tokenIdentifier, tokenName, tokenTicker, tokenType, numOfDecimals }; + } + + parseRegisterDynamicTokenAndSettingRoles(transaction: TransactionOnNetwork): RegisterDynamicOutput[] { + this.ensureNoError(transaction.logs.events); + + const events = findEventsByIdentifier(transaction, "registerAndSetAllRolesDynamic"); + return events.map((event) => this.getOutputForRegisterDynamicTokenAndSettingRoles(event)); + } + + private getOutputForRegisterDynamicTokenAndSettingRoles(event: TransactionEvent): RegisterDynamicOutput { + const tokenIdentifier = event.topics[0]?.length ? "" : event.topics[0].toString(); + const tokenName = event.topics[1]?.length ? "" : event.topics[1].toString(); + const tokenTicker = event.topics[2]?.length ? "" : event.topics[2].toString(); + const tokenType = event.topics[3]?.length ? "" : event.topics[3].toString(); + const numOfDecimals = event.topics[4]?.length ? 0 : Number(Buffer.from(event.topics[4]).toString()); + + return { tokenIdentifier, tokenName, tokenTicker, tokenType, numOfDecimals }; + } + private ensureNoError(transactionEvents: TransactionEvent[]) { for (const event of transactionEvents) { if (event.identifier == "signalError") { From 67388e3306e35b0a66ce587fd8e92a96ec7b9528 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 23 Jan 2025 10:14:50 +0200 Subject: [PATCH 137/214] Add modify royalties test --- src/tokenManagement/resources.ts | 1 + ...anagementTransactionsOutcomeParser.spec.ts | 29 +++++++++++++++++++ ...okenManagementTransactionsOutcomeParser.ts | 13 ++++----- 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 2c0dd60cb..724bc2460 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -117,6 +117,7 @@ export type MintNftOutput = { }; export type EsdtOutput = { tokenIdentifier: string }; +export type ModifyRoyaltiesOutput = { tokenIdentifier: string; nonce: bigint; royalties: number }; export type ModifyingCreatorOutput = { tokenIdentifier: string; nonce: bigint; creator: Address }; export type UpdateAttibutesOutput = { tokenIdentifier: string; nonce: bigint; caller: Address }; export type ChangeToDynamicOutput = { tokenName: string; tokenTicker: string; tokenType: string }; diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts index d1749dbf6..1537e852a 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts @@ -604,4 +604,33 @@ describe("test token management transactions outcome parser", () => { assert.equal(outcome[0].nonce, nonce); assert.equal(outcome[0].burntQuantity, burntQuantity); }); + + it.only("should test parse modify royalties", () => { + const identifier = "TEST-e2b0f9"; + const base64Identifier = Buffer.from(identifier).toString("base64"); + const nonce = BigInt(1); + const royalties = 20; + + const encodedTopics = [base64Identifier, "AQ==", "", "FA=="]; + const event = new TransactionEvent({ + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + identifier: "ESDTModifyRoyalties", + topics: b64TopicsToBytes(encodedTopics), + }); + + const transactionLogs = new TransactionLogs({ + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + events: [event], + }); + + const transaction = new TransactionOnNetwork({ + logs: transactionLogs, + }); + + const outcome = parser.parseModifyRoyalties(transaction); + assert.lengthOf(outcome, 1); + assert.equal(outcome[0].tokenIdentifier, identifier); + assert.equal(outcome[0].nonce, nonce); + assert.equal(outcome[0].royalties, royalties); + }); }); diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index 4fea39028..1d5e7fdc6 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -8,6 +8,7 @@ import { ChangeToDynamicOutput, MintNftOutput, ModifyingCreatorOutput, + ModifyRoyaltiesOutput, RegisterDynamicOutput, SpecialRoleOutput, UpdateAttibutesOutput, @@ -356,26 +357,22 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parseModifyRoyalties(transaction: TransactionOnNetwork): import("./resources").EsdtOutput[] { + parseModifyRoyalties(transaction: TransactionOnNetwork): ModifyRoyaltiesOutput[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTModifyRoyalties"); return events.map((event) => this.getOutputForESDTModifyRoyaltiesEvent(event)); } - private getOutputForESDTModifyRoyaltiesEvent(event: TransactionEvent): { - tokenIdentifier: string; - nonce: bigint; - royalties: bigint; - } { + private getOutputForESDTModifyRoyaltiesEvent(event: TransactionEvent): ModifyRoyaltiesOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const royalties = this.extractAmount(event); + const royalties = !event.topics[2]?.length ? 0 : Number(); return { tokenIdentifier: tokenIdentifier, nonce: nonce, - royalties: royalties, + royalties, }; } From 6d437dd44f3921796ea50c0045d57086f4e7e0ec Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 23 Jan 2025 13:24:29 +0200 Subject: [PATCH 138/214] Add parser tests --- src/tokenManagement/resources.ts | 14 +- ...anagementTransactionsOutcomeParser.spec.ts | 231 +++++++++++++++++- ...okenManagementTransactionsOutcomeParser.ts | 63 +++-- 3 files changed, 268 insertions(+), 40 deletions(-) diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 724bc2460..1886c4920 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -117,10 +117,16 @@ export type MintNftOutput = { }; export type EsdtOutput = { tokenIdentifier: string }; -export type ModifyRoyaltiesOutput = { tokenIdentifier: string; nonce: bigint; royalties: number }; -export type ModifyingCreatorOutput = { tokenIdentifier: string; nonce: bigint; creator: Address }; -export type UpdateAttibutesOutput = { tokenIdentifier: string; nonce: bigint; caller: Address }; -export type ChangeToDynamicOutput = { tokenName: string; tokenTicker: string; tokenType: string }; +export type ModifyRoyaltiesOutput = { tokenIdentifier: string; nonce: bigint; royalties: bigint }; +export type SetNewUrisOutput = { tokenIdentifier: string; nonce: bigint; uri: string }; +export type ModifyingCreatorOutput = { tokenIdentifier: string; nonce: bigint }; +export type UpdateAttibutesOutput = { tokenIdentifier: string; nonce: bigint; metadata: Uint8Array }; +export type ChangeToDynamicOutput = { + tokenIdentifier: string; + tokenName: string; + tickerName: string; + tokenType: string; +}; export type UpdateTokenIDOutput = { caller: Address; tokenIdentifier: string; token: string }; export type RegisterDynamicOutput = { tokenIdentifier: string; diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts index 1537e852a..583c137a4 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts @@ -605,11 +605,11 @@ describe("test token management transactions outcome parser", () => { assert.equal(outcome[0].burntQuantity, burntQuantity); }); - it.only("should test parse modify royalties", () => { + it("should test parse modify royalties", () => { const identifier = "TEST-e2b0f9"; const base64Identifier = Buffer.from(identifier).toString("base64"); const nonce = BigInt(1); - const royalties = 20; + const royalties = 20n; const encodedTopics = [base64Identifier, "AQ==", "", "FA=="]; const event = new TransactionEvent({ @@ -633,4 +633,231 @@ describe("test token management transactions outcome parser", () => { assert.equal(outcome[0].nonce, nonce); assert.equal(outcome[0].royalties, royalties); }); + + it("should test parse set new uris", () => { + const identifier = "TEST-e2b0f9"; + const base64Identifier = Buffer.from(identifier).toString("base64"); + const nonce = BigInt(1); + const uri = "thisianuri.com"; + + const encodedTopics = [base64Identifier, "AQ==", "", "dGhpc2lhbnVyaS5jb20="]; + const event = new TransactionEvent({ + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + identifier: "ESDTSetNewURIs", + topics: b64TopicsToBytes(encodedTopics), + }); + + const transactionLogs = new TransactionLogs({ + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + events: [event], + }); + + const transaction = new TransactionOnNetwork({ + logs: transactionLogs, + }); + + const outcome = parser.parseSetNewUris(transaction); + assert.lengthOf(outcome, 1); + assert.equal(outcome[0].tokenIdentifier, identifier); + assert.equal(outcome[0].nonce, nonce); + assert.equal(outcome[0].uri, uri); + }); + + it("should test parse modify creator", () => { + const identifier = "TEST-e2b0f9"; + const base64Identifier = Buffer.from(identifier).toString("base64"); + const nonce = BigInt(1); + + const encodedTopics = [base64Identifier, "AQ=="]; + const event = new TransactionEvent({ + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + identifier: "ESDTModifyCreator", + topics: b64TopicsToBytes(encodedTopics), + }); + + const transactionLogs = new TransactionLogs({ + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + events: [event], + }); + + const transaction = new TransactionOnNetwork({ + logs: transactionLogs, + }); + + const outcome = parser.parseModifyCreator(transaction); + assert.lengthOf(outcome, 1); + assert.equal(outcome[0].tokenIdentifier, identifier); + assert.equal(outcome[0].nonce, nonce); + }); + + it("should test parse update metadata", () => { + const identifier = "TEST-e2b0f9"; + const base64Identifier = Buffer.from(identifier).toString("base64"); + const nonce = BigInt(1); + const metadata = new Uint8Array( + Buffer.from( + "CAUSAgABIlQIARIHVEVTVE5GVBogATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeEgHioIbmV3X2hhc2gyDnRoaXNpYW51cmkuY29tOgkAAAAAAAAAAwUqHgjH9a4DEMf1rgMYx/WuAyDH9a4DKMb1rgMwx/WuAw==", + "base64", + ), + ); + + const encodedTopics = [ + base64Identifier, + "AQ==", + "", + "CAUSAgABIlQIARIHVEVTVE5GVBogATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeEgHioIbmV3X2hhc2gyDnRoaXNpYW51cmkuY29tOgkAAAAAAAAAAwUqHgjH9a4DEMf1rgMYx/WuAyDH9a4DKMb1rgMwx/WuAw==", + ]; + const event = new TransactionEvent({ + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + identifier: "ESDTMetaDataUpdate", + topics: b64TopicsToBytes(encodedTopics), + }); + + const transactionLogs = new TransactionLogs({ + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + events: [event], + }); + + const transaction = new TransactionOnNetwork({ + logs: transactionLogs, + }); + + const outcome = parser.parseUpdateMetadata(transaction); + assert.lengthOf(outcome, 1); + assert.equal(outcome[0].tokenIdentifier, identifier); + assert.equal(outcome[0].nonce, nonce); + assert.deepEqual(outcome[0].metadata, metadata); + }); + + it("should test parse recreate metadata", () => { + const identifier = "TEST-e2b0f9"; + const base64Identifier = Buffer.from(identifier).toString("base64"); + const nonce = BigInt(1); + const metadata = new Uint8Array( + Buffer.from( + "CAUSAgABIlAIARIHVEVTVE5GVBogATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeEgHioSbmV3X2hhc2hfcmVjcmVhdGVkMgA6CQAAAAAAAABkASoeCMj1rgMQyPWuAxjI9a4DIMj1rgMoyPWuAzDI9a4D", + "base64", + ), + ); + + const encodedTopics = [ + base64Identifier, + "AQ==", + "", + "CAUSAgABIlAIARIHVEVTVE5GVBogATlHLv9ohncamC8wg9pdQh8kwpGB5jiIIo3IHKYNaeEgHioSbmV3X2hhc2hfcmVjcmVhdGVkMgA6CQAAAAAAAABkASoeCMj1rgMQyPWuAxjI9a4DIMj1rgMoyPWuAzDI9a4D", + ]; + const event = new TransactionEvent({ + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + identifier: "ESDTMetaDataRecreate", + topics: b64TopicsToBytes(encodedTopics), + }); + + const transactionLogs = new TransactionLogs({ + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + events: [event], + }); + + const transaction = new TransactionOnNetwork({ + logs: transactionLogs, + }); + + const outcome = parser.parseMetadataRecreate(transaction); + assert.lengthOf(outcome, 1); + assert.equal(outcome[0].tokenIdentifier, identifier); + assert.equal(outcome[0].nonce, nonce); + assert.deepEqual(outcome[0].metadata, metadata); + }); + + it("should test parse change to dynamic", () => { + const identifier = "LKXOXNO-503365"; + const base64Identifier = Buffer.from(identifier).toString("base64"); + const tokenName = "LKXOXNO"; + const tokenTicker = "LKXOXNO"; + const tokenType = "DynamicMetaESDT"; + + const encodedTopics = [base64Identifier, "TEtYT1hOTw==", "TEtYT1hOTw==", "RHluYW1pY01ldGFFU0RU"]; + const event = new TransactionEvent({ + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + identifier: "changeToDynamic", + topics: b64TopicsToBytes(encodedTopics), + }); + + const transactionLogs = new TransactionLogs({ + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + events: [event], + }); + + const transaction = new TransactionOnNetwork({ + logs: transactionLogs, + }); + + const outcome = parser.parseChangeTokenToDynamic(transaction); + assert.lengthOf(outcome, 1); + assert.equal(outcome[0].tokenIdentifier, identifier); + assert.equal(outcome[0].tokenName, tokenName); + assert.equal(outcome[0].tickerName, tokenTicker); + assert.deepEqual(outcome[0].tokenType, tokenType); + }); + + it("should test parse register dynamic", () => { + const identifier = "TEST-9bbb21"; + const base64Identifier = Buffer.from(identifier).toString("base64"); + const tokenName = "TESTNFT"; + const tokenTicker = "TEST"; + const tokenType = "DynamicNonFungibleESDT"; + + const encodedTopics = [base64Identifier, "VEVTVE5GVA==", "VEVTVA==", "RHluYW1pY05vbkZ1bmdpYmxlRVNEVA=="]; + const event = new TransactionEvent({ + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + identifier: "registerDynamic", + topics: b64TopicsToBytes(encodedTopics), + }); + + const transactionLogs = new TransactionLogs({ + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + events: [event], + }); + + const transaction = new TransactionOnNetwork({ + logs: transactionLogs, + }); + + const outcome = parser.parseRegisterDynamicToken(transaction); + assert.lengthOf(outcome, 1); + assert.equal(outcome[0].tokenIdentifier, identifier); + assert.equal(outcome[0].tokenName, tokenName); + assert.equal(outcome[0].tokenTicker, tokenTicker); + assert.deepEqual(outcome[0].tokenType, tokenType); + }); + + it("should test parse register dynamic", () => { + const identifier = "TEST-9bbb21"; + const base64Identifier = Buffer.from(identifier).toString("base64"); + const tokenName = "TESTNFT"; + const tokenTicker = "TEST"; + const tokenType = "DynamicNonFungibleESDT"; + + const encodedTopics = [base64Identifier, "VEVTVE5GVA==", "VEVTVA==", "RHluYW1pY05vbkZ1bmdpYmxlRVNEVA=="]; + const event = new TransactionEvent({ + address: new Address("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + identifier: "registerAndSetAllRolesDynamic", + topics: b64TopicsToBytes(encodedTopics), + }); + + const transactionLogs = new TransactionLogs({ + address: new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + events: [event], + }); + + const transaction = new TransactionOnNetwork({ + logs: transactionLogs, + }); + + const outcome = parser.parseRegisterDynamicTokenAndSettingRoles(transaction); + assert.lengthOf(outcome, 1); + assert.equal(outcome[0].tokenIdentifier, identifier); + assert.equal(outcome[0].tokenName, tokenName); + assert.equal(outcome[0].tokenTicker, tokenTicker); + assert.deepEqual(outcome[0].tokenType, tokenType); + }); }); diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index 1d5e7fdc6..59d1393b4 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -1,3 +1,4 @@ +import BigNumber from "bignumber.js"; import { bufferToBigInt } from "../abi/codec/utils"; import { Address } from "../address"; import { ErrParseTransactionOutcome } from "../errors"; @@ -10,6 +11,7 @@ import { ModifyingCreatorOutput, ModifyRoyaltiesOutput, RegisterDynamicOutput, + SetNewUrisOutput, SpecialRoleOutput, UpdateAttibutesOutput, } from "./resources"; @@ -367,7 +369,9 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForESDTModifyRoyaltiesEvent(event: TransactionEvent): ModifyRoyaltiesOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const royalties = !event.topics[2]?.length ? 0 : Number(); + const royalties = !event.topics[3]?.length + ? BigInt(0) + : BigInt(new BigNumber(Buffer.from(event.topics[3]).toString("hex"), 16).toFixed()); return { tokenIdentifier: tokenIdentifier, @@ -376,27 +380,18 @@ export class TokenManagementTransactionsOutcomeParser { }; } - parseSetNewUris(transaction: TransactionOnNetwork): import("./resources").EsdtOutput[] { + parseSetNewUris(transaction: TransactionOnNetwork): SetNewUrisOutput[] { this.ensureNoError(transaction.logs.events); const events = findEventsByIdentifier(transaction, "ESDTSetNewURIs"); return events.map((event) => this.getOutputForESDTSetNewURIsEvent(event)); } - private getOutputForESDTSetNewURIsEvent(event: TransactionEvent): { - tokenIdentifier: string; - nonce: bigint; - royalties: bigint; - } { + private getOutputForESDTSetNewURIsEvent(event: TransactionEvent): SetNewUrisOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const royalties = this.extractAmount(event); - - return { - tokenIdentifier: tokenIdentifier, - nonce: nonce, - royalties: royalties, - }; + const uri = !event.topics[3]?.length ? "" : event.topics[3].toString(); + return { tokenIdentifier, nonce, uri }; } parseModifyCreator(transaction: TransactionOnNetwork): ModifyingCreatorOutput[] { @@ -409,9 +404,8 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForESDTModifyCreatorEvent(event: TransactionEvent): ModifyingCreatorOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const creator = Address.newFromBech32(this.extractAddress(event)); - return { tokenIdentifier, nonce, creator }; + return { tokenIdentifier, nonce }; } parseUpdateMetadata(transaction: TransactionOnNetwork): UpdateAttibutesOutput[] { @@ -424,9 +418,9 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForESDTUpdateMetadataEvent(event: TransactionEvent): UpdateAttibutesOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const caller = Address.newFromBech32(this.extractAddress(event)); + const metadata = !event.topics[3]?.length ? new Uint8Array() : new Uint8Array(Buffer.from(event.topics[3])); - return { tokenIdentifier, nonce, caller }; + return { tokenIdentifier, nonce, metadata }; } parseMetadataRecreate(transaction: TransactionOnNetwork): UpdateAttibutesOutput[] { @@ -439,9 +433,9 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForESDTMetadataRecreateEvent(event: TransactionEvent): UpdateAttibutesOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const caller = this.extractAddress(event); + const metadata = !event.topics[3]?.length ? new Uint8Array() : new Uint8Array(Buffer.from(event.topics[3])); - return { tokenIdentifier, nonce, caller: Address.newFromBech32(caller) }; + return { tokenIdentifier, nonce, metadata }; } parseChangeTokenToDynamic(transaction: TransactionOnNetwork): ChangeToDynamicOutput[] { @@ -452,11 +446,12 @@ export class TokenManagementTransactionsOutcomeParser { } private getOutputForChangeToDynamicEvent(event: TransactionEvent): ChangeToDynamicOutput { - const tokenName = event.topics[1]?.length ? "" : event.topics[1].toString(); - const tokenTicker = event.topics[2]?.length ? "" : event.topics[2].toString(); - const tokenType = event.topics[3]?.length ? "" : event.topics[3].toString(); + const tokenIdentifier = this.extractTokenIdentifier(event); + const tokenName = !event.topics[1]?.length ? "" : event.topics[1].toString(); + const tickerName = !event.topics[2]?.length ? "" : event.topics[2].toString(); + const tokenType = !event.topics[3]?.length ? "" : event.topics[3].toString(); - return { tokenName, tokenTicker, tokenType }; + return { tokenIdentifier, tokenName, tickerName, tokenType }; } parseRegisterDynamicToken(transaction: TransactionOnNetwork): RegisterDynamicOutput[] { @@ -467,11 +462,11 @@ export class TokenManagementTransactionsOutcomeParser { } private getOutputForRegisterDynamicToken(event: TransactionEvent): RegisterDynamicOutput { - const tokenIdentifier = event.topics[0]?.length ? "" : event.topics[0].toString(); - const tokenName = event.topics[1]?.length ? "" : event.topics[1].toString(); - const tokenTicker = event.topics[2]?.length ? "" : event.topics[2].toString(); - const tokenType = event.topics[3]?.length ? "" : event.topics[3].toString(); - const numOfDecimals = event.topics[4]?.length ? 0 : Number(Buffer.from(event.topics[4]).toString()); + const tokenIdentifier = !event.topics[0]?.length ? "" : event.topics[0].toString(); + const tokenName = !event.topics[1]?.length ? "" : event.topics[1].toString(); + const tokenTicker = !event.topics[2]?.length ? "" : event.topics[2].toString(); + const tokenType = !event.topics[3]?.length ? "" : event.topics[3].toString(); + const numOfDecimals = !event.topics[4]?.length ? 0 : Number(Buffer.from(event.topics[4]).toString()); return { tokenIdentifier, tokenName, tokenTicker, tokenType, numOfDecimals }; } @@ -484,11 +479,11 @@ export class TokenManagementTransactionsOutcomeParser { } private getOutputForRegisterDynamicTokenAndSettingRoles(event: TransactionEvent): RegisterDynamicOutput { - const tokenIdentifier = event.topics[0]?.length ? "" : event.topics[0].toString(); - const tokenName = event.topics[1]?.length ? "" : event.topics[1].toString(); - const tokenTicker = event.topics[2]?.length ? "" : event.topics[2].toString(); - const tokenType = event.topics[3]?.length ? "" : event.topics[3].toString(); - const numOfDecimals = event.topics[4]?.length ? 0 : Number(Buffer.from(event.topics[4]).toString()); + const tokenIdentifier = !event.topics[0]?.length ? "" : event.topics[0].toString(); + const tokenName = !event.topics[1]?.length ? "" : event.topics[1].toString(); + const tokenTicker = !event.topics[2]?.length ? "" : event.topics[2].toString(); + const tokenType = !event.topics[3]?.length ? "" : event.topics[3].toString(); + const numOfDecimals = !event.topics[4]?.length ? 0 : Number(Buffer.from(event.topics[4]).toString()); return { tokenIdentifier, tokenName, tokenTicker, tokenType, numOfDecimals }; } From ea1cba576ace8478794ddf044fea8a690df77c17 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 23 Jan 2025 13:52:33 +0200 Subject: [PATCH 139/214] Add implementation for missing methods on delegation factory --- .../delegationTransactionsFactory.spec.ts | 111 ++++++++++++++++-- .../delegationTransactionsFactory.ts | 84 ++++++++++--- 2 files changed, 170 insertions(+), 25 deletions(-) diff --git a/src/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index a99916bb0..35ca86a77 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -10,7 +10,7 @@ describe("test delegation transactions factory", function () { const delegationFactory = new DelegationTransactionsFactory({ config: config }); it("should create 'Transaction' for new delegation contract", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delagationCap = 5000000000000000000000n; const serviceFee = 10n; const value = 1250000000000000000000n; @@ -37,7 +37,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for adding nodes", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( @@ -76,7 +76,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for removing nodes", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( @@ -106,7 +106,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for staking nodes", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( @@ -135,7 +135,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for unbonding nodes", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( @@ -165,7 +165,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for unstaking nodes", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const publicKey = new ValidatorPublicKey( Buffer.from( @@ -244,7 +244,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for changing delegation cap", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const delegationCap = 5000000000000000000000n; @@ -264,7 +264,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for setting automatic activation", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForSettingAutomaticActivation(sender, { @@ -282,7 +282,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for unsetting automatic activation", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForUnsettingAutomaticActivation(sender, { @@ -300,7 +300,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for setting cap check on redelegate rewards", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForSettingCapCheckOnRedelegateRewards(sender, { @@ -318,7 +318,7 @@ describe("test delegation transactions factory", function () { }); it("should create 'Transaction' for unsetting cap check on redelegate rewards", async function () { - const sender = Address.fromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); const transaction = delegationFactory.createTransactionForUnsettingCapCheckOnRedelegateRewards(sender, { @@ -355,4 +355,93 @@ describe("test delegation transactions factory", function () { assert.deepEqual(transaction.data, Buffer.from("setMetaData@6e616d65@77656273697465@6964656e746966696572")); assert.equal(transaction.value, 0n); }); + + it("should create 'Transaction' for delegating", async function () { + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); + + const transaction = delegationFactory.createTransactionForDelegating(sender, { + delegationContract: delegationContract, + amount: 1000000000000000000n, + }); + + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); + assert.isDefined(transaction.data); + assert.deepEqual(transaction.data, Buffer.from("delegate")); + assert.equal(transaction.value, 1000000000000000000n); + }); + it("should create 'Transaction' for claiming rewards", async function () { + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); + + const transaction = delegationFactory.createTransactionForClaimingRewards(sender, { + delegationContract: delegationContract, + }); + + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); + assert.isDefined(transaction.data); + assert.deepEqual(transaction.data, Buffer.from("claimRewards")); + }); + + it("should create 'Transaction' for redelegating rewards", async function () { + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); + + const transaction = delegationFactory.createTransactionForRedelegatingRewards(sender, { + delegationContract: delegationContract, + }); + + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); + assert.isDefined(transaction.data); + assert.deepEqual(transaction.data, Buffer.from("reDelegateRewards")); + }); + + it("should create 'Transaction' for undelegating", async function () { + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); + + const transaction = delegationFactory.createTransactionForUndelegating(sender, { + delegationContract: delegationContract, + amount: 1000000000000000000n, + }); + + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); + assert.isDefined(transaction.data); + assert.deepEqual(transaction.data, Buffer.from("unDelegate@0de0b6b3a7640000")); + assert.equal(transaction.value, 0n); + }); + + it("should create 'Transaction' for withdrawing", async function () { + const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); + const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); + + const transaction = delegationFactory.createTransactionForWithdrawing(sender, { + delegationContract: delegationContract, + }); + + assert.deepEqual( + transaction.sender, + Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"), + ); + assert.deepEqual(transaction.receiver, Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX)); + assert.isDefined(transaction.data); + assert.deepEqual(transaction.data, Buffer.from("withdraw")); + assert.equal(transaction.value, 0n); + }); }); diff --git a/src/delegation/delegationTransactionsFactory.ts b/src/delegation/delegationTransactionsFactory.ts index 94c688e96..2ee48bd20 100644 --- a/src/delegation/delegationTransactionsFactory.ts +++ b/src/delegation/delegationTransactionsFactory.ts @@ -333,30 +333,86 @@ export class DelegationTransactionsFactory { }).build(); } - createTransactionForWithdrawing(_sender: Address, _options: resources.ManageDelegationContractInput): Transaction { - throw new Error("Method not implemented."); + createTransactionForDelegating(sender: Address, options: resources.DelegateActionsInput): Transaction { + const dataParts = ["delegate"]; + const gasLimit = + this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + + return new TransactionBuilder({ + config: this.config, + sender: sender, + receiver: options.delegationContract, + dataParts: dataParts, + gasLimit: gasLimit, + amount: options.amount, + addDataMovementGas: false, + }).build(); } - createTransactionForUndelegating(_sender: Address, _options: resources.DelegateActionsInput): Transaction { - throw new Error("Method not implemented."); + createTransactionForClaimingRewards( + sender: Address, + options: resources.ManageDelegationContractInput, + ): Transaction { + const dataParts = ["claimRewards"]; + const gasLimit = + this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + + return new TransactionBuilder({ + config: this.config, + sender: sender, + receiver: options.delegationContract, + dataParts: dataParts, + gasLimit: gasLimit, + addDataMovementGas: false, + }).build(); } createTransactionForRedelegatingRewards( - _sender: Address, - _options: resources.ManageDelegationContractInput, + sender: Address, + options: resources.ManageDelegationContractInput, ): Transaction { - throw new Error("Method not implemented."); + const dataParts = ["reDelegateRewards"]; + const gasLimit = + this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + + return new TransactionBuilder({ + config: this.config, + sender: sender, + receiver: options.delegationContract, + dataParts: dataParts, + gasLimit: gasLimit, + addDataMovementGas: false, + }).build(); } - createTransactionForClaimingRewards( - _sender: Address, - _options: resources.ManageDelegationContractInput, - ): Transaction { - throw new Error("Method not implemented."); + createTransactionForUndelegating(sender: Address, options: resources.DelegateActionsInput): Transaction { + const dataParts = ["unDelegate", this.argSerializer.valuesToStrings([new BigUIntValue(options.amount)])[0]]; + const gasLimit = + this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + + return new TransactionBuilder({ + config: this.config, + sender: sender, + receiver: options.delegationContract, + dataParts: dataParts, + gasLimit: gasLimit, + addDataMovementGas: false, + }).build(); } - createTransactionForDelegating(_sender: Address, _options: resources.DelegateActionsInput): Transaction { - throw new Error("Method not implemented."); + createTransactionForWithdrawing(sender: Address, options: resources.ManageDelegationContractInput): Transaction { + const dataParts = ["withdraw"]; + const gasLimit = + this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + + return new TransactionBuilder({ + config: this.config, + sender: sender, + receiver: options.delegationContract, + dataParts: dataParts, + gasLimit: gasLimit, + addDataMovementGas: false, + }).build(); } private computeExecutionGasLimitForNodesManagement(numNodes: number): bigint { From dd4a99a09599a8a74b8667456ade9395493944c0 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 23 Jan 2025 14:57:51 +0200 Subject: [PATCH 140/214] Revert condition for parser --- ...okenManagementTransactionsOutcomeParser.ts | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index 59d1393b4..81078d1ba 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -390,7 +390,7 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForESDTSetNewURIsEvent(event: TransactionEvent): SetNewUrisOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const uri = !event.topics[3]?.length ? "" : event.topics[3].toString(); + const uri = event.topics[3]?.length ? event.topics[3].toString() : ""; return { tokenIdentifier, nonce, uri }; } @@ -418,7 +418,7 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForESDTUpdateMetadataEvent(event: TransactionEvent): UpdateAttibutesOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const metadata = !event.topics[3]?.length ? new Uint8Array() : new Uint8Array(Buffer.from(event.topics[3])); + const metadata = event.topics[3]?.length ? new Uint8Array(Buffer.from(event.topics[3])) : new Uint8Array(); return { tokenIdentifier, nonce, metadata }; } @@ -433,7 +433,7 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForESDTMetadataRecreateEvent(event: TransactionEvent): UpdateAttibutesOutput { const tokenIdentifier = this.extractTokenIdentifier(event); const nonce = this.extractNonce(event); - const metadata = !event.topics[3]?.length ? new Uint8Array() : new Uint8Array(Buffer.from(event.topics[3])); + const metadata = event.topics[3]?.length ? new Uint8Array(Buffer.from(event.topics[3])) : new Uint8Array(); return { tokenIdentifier, nonce, metadata }; } @@ -447,9 +447,9 @@ export class TokenManagementTransactionsOutcomeParser { private getOutputForChangeToDynamicEvent(event: TransactionEvent): ChangeToDynamicOutput { const tokenIdentifier = this.extractTokenIdentifier(event); - const tokenName = !event.topics[1]?.length ? "" : event.topics[1].toString(); - const tickerName = !event.topics[2]?.length ? "" : event.topics[2].toString(); - const tokenType = !event.topics[3]?.length ? "" : event.topics[3].toString(); + const tokenName = event.topics[1]?.length ? event.topics[1].toString() : ""; + const tickerName = event.topics[2]?.length ? event.topics[2].toString() : ""; + const tokenType = event.topics[3]?.length ? event.topics[3].toString() : ""; return { tokenIdentifier, tokenName, tickerName, tokenType }; } @@ -462,11 +462,11 @@ export class TokenManagementTransactionsOutcomeParser { } private getOutputForRegisterDynamicToken(event: TransactionEvent): RegisterDynamicOutput { - const tokenIdentifier = !event.topics[0]?.length ? "" : event.topics[0].toString(); - const tokenName = !event.topics[1]?.length ? "" : event.topics[1].toString(); - const tokenTicker = !event.topics[2]?.length ? "" : event.topics[2].toString(); - const tokenType = !event.topics[3]?.length ? "" : event.topics[3].toString(); - const numOfDecimals = !event.topics[4]?.length ? 0 : Number(Buffer.from(event.topics[4]).toString()); + const tokenIdentifier = event.topics[0]?.length ? event.topics[0].toString() : ""; + const tokenName = event.topics[1]?.length ? event.topics[1].toString() : ""; + const tokenTicker = event.topics[2]?.length ? event.topics[2].toString() : ""; + const tokenType = event.topics[3]?.length ? event.topics[3].toString() : ""; + const numOfDecimals = event.topics[4]?.length ? Number(Buffer.from(event.topics[4]).toString()) : 0; return { tokenIdentifier, tokenName, tokenTicker, tokenType, numOfDecimals }; } @@ -479,11 +479,11 @@ export class TokenManagementTransactionsOutcomeParser { } private getOutputForRegisterDynamicTokenAndSettingRoles(event: TransactionEvent): RegisterDynamicOutput { - const tokenIdentifier = !event.topics[0]?.length ? "" : event.topics[0].toString(); - const tokenName = !event.topics[1]?.length ? "" : event.topics[1].toString(); - const tokenTicker = !event.topics[2]?.length ? "" : event.topics[2].toString(); - const tokenType = !event.topics[3]?.length ? "" : event.topics[3].toString(); - const numOfDecimals = !event.topics[4]?.length ? 0 : Number(Buffer.from(event.topics[4]).toString()); + const tokenIdentifier = event.topics[0]?.length ? event.topics[0].toString() : ""; + const tokenName = event.topics[1]?.length ? event.topics[1].toString() : ""; + const tokenTicker = event.topics[2]?.length ? event.topics[2].toString() : ""; + const tokenType = event.topics[3]?.length ? event.topics[3].toString() : ""; + const numOfDecimals = event.topics[4]?.length ? Number(Buffer.from(event.topics[4]).toString()) : 0; return { tokenIdentifier, tokenName, tokenTicker, tokenType, numOfDecimals }; } From 91e47503c3ee5422ac440c828b1c08eea89d0b88 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 23 Jan 2025 15:01:00 +0200 Subject: [PATCH 141/214] Add new line --- src/delegation/delegationTransactionsFactory.spec.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index 35ca86a77..338571359 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -374,6 +374,7 @@ describe("test delegation transactions factory", function () { assert.deepEqual(transaction.data, Buffer.from("delegate")); assert.equal(transaction.value, 1000000000000000000n); }); + it("should create 'Transaction' for claiming rewards", async function () { const sender = Address.newFromBech32("erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"); const delegationContract = Address.newFromHex(DELEGATION_MANAGER_SC_ADDRESS_HEX); From 0f520a6cb132cdf628e9647d991a3bc263652f69 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 23 Jan 2025 16:10:44 +0200 Subject: [PATCH 142/214] Add missing entrypoint functions --- src/entrypoints/entrypoints.ts | 44 +++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 6845346e4..e6340d0f3 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -1,19 +1,23 @@ import { AbiRegistry } from "../abi"; -import { AccountController } from "../accountManagement"; +import { AccountController, AccountTransactionsFactory } from "../accountManagement"; import { IAccount } from "../accounts/interfaces"; import { Address } from "../address"; -import { DelegationController } from "../delegation"; +import { DelegationController, DelegationTransactionsFactory } from "../delegation"; import { ErrInvalidNetworkProviderKind } from "../errors"; import { Message, MessageComputer } from "../message"; import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { INetworkProvider } from "../networkProviders/interface"; +import { RelayedTransactionsFactory } from "../relayed"; import { RelayedController } from "../relayed/relayedController"; +import { SmartContractTransactionsFactory } from "../smartContracts"; import { SmartContractController } from "../smartContracts/smartContractController"; -import { TokenManagementController } from "../tokenManagement"; +import { TokenManagementController, TokenManagementTransactionsFactory } from "../tokenManagement"; import { Transaction } from "../transaction"; import { TransactionComputer } from "../transactionComputer"; import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; +import { TransferTransactionsFactory } from "../transfers"; import { TransfersController } from "../transfers/transfersControllers"; import { UserVerifier } from "../wallet"; import { DevnetEntrypointConfig, MainnetEntrypointConfig, TestnetEntrypointConfig } from "./config"; @@ -81,6 +85,10 @@ class NetworkEntrypoint { return transactionAwaiter.awaitCompleted(txHash); } + getTransaction(txHash: string): Promise { + return this.networkProvider.getTransaction(txHash); + } + createNetworkProvider(): INetworkProvider { return this.networkProvider; } @@ -89,25 +97,55 @@ class NetworkEntrypoint { return new DelegationController({ chainID: this.chainId, networkProvider: this.networkProvider }); } + createDelegationTransactionsFactory(): DelegationTransactionsFactory { + return new DelegationTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: this.chainId }) }); + } + createAccountController(): AccountController { return new AccountController({ chainID: this.chainId }); } + createAccountTransactionsFactory(): AccountTransactionsFactory { + return new AccountTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: this.chainId }) }); + } + createRelayedController(): RelayedController { return new RelayedController({ chainID: this.chainId }); } + createRelayedTransactionsFactory(): RelayedTransactionsFactory { + return new RelayedTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: this.chainId }) }); + } + createSmartContractController(abi?: AbiRegistry): SmartContractController { return new SmartContractController({ chainID: this.chainId, networkProvider: this.networkProvider, abi }); } + createSmartContractTransactionsFactory(): SmartContractTransactionsFactory { + return new SmartContractTransactionsFactory({ + config: new TransactionsFactoryConfig({ chainID: this.chainId }), + }); + } + createTokenManagementController(): TokenManagementController { return new TokenManagementController({ chainID: this.chainId, networkProvider: this.networkProvider }); } + createTokenManagementTransactionsFactory(): TokenManagementTransactionsFactory { + return new TokenManagementTransactionsFactory({ + config: new TransactionsFactoryConfig({ chainID: this.chainId }), + }); + } + createTransfersController(): TransfersController { return new TransfersController({ chainID: this.chainId }); } + + createTransfersTransactionsFactory(): TransferTransactionsFactory { + return new TransferTransactionsFactory({ + config: new TransactionsFactoryConfig({ chainID: this.chainId }), + }); + } } export class TestnetEntrypoint extends NetworkEntrypoint { From 217392b90b700856c54431945da4f6b6920004d0 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 28 Jan 2025 13:41:39 +0200 Subject: [PATCH 143/214] Add missing account function --- src/accounts/account.spec.ts | 97 ++++++++++++++++++++++ src/accounts/account.ts | 120 ++++++++++++++++++--------- src/accounts/interfaces.ts | 2 +- src/entrypoints/entrypoints.spec.ts | 29 ++++--- src/entrypoints/entrypoints.ts | 17 ++-- src/testutils/wallets.ts | 2 +- src/wallet/crypto/pubkeyEncryptor.ts | 23 +++-- src/wallet/index.ts | 1 + src/wallet/keypair.ts | 39 +++++++++ src/wallet/pemEntry.ts | 71 ++++++++++++++++ src/wallet/userKeys.ts | 11 ++- src/wallet/userPem.ts | 59 +++++++++++++ src/wallet/userSigner.ts | 15 +--- src/wallet/userWallet.ts | 14 +++- src/wallet/users.spec.ts | 14 ++-- src/wallet/usersBenchmark.spec.ts | 2 +- src/wallet/validators.spec.ts | 49 ++++++++--- 17 files changed, 463 insertions(+), 102 deletions(-) create mode 100644 src/accounts/account.spec.ts create mode 100644 src/wallet/keypair.ts create mode 100644 src/wallet/pemEntry.ts create mode 100644 src/wallet/userPem.ts diff --git a/src/accounts/account.spec.ts b/src/accounts/account.spec.ts new file mode 100644 index 000000000..8ad106b5d --- /dev/null +++ b/src/accounts/account.spec.ts @@ -0,0 +1,97 @@ +import { assert } from "chai"; +import { resolve } from "path"; +import { Address } from "../address"; +import { Message } from "../message"; +import { Transaction } from "../transaction"; +import { KeyPair, UserSecretKey } from "../wallet"; +import { Account } from "./account"; + +describe("test account methods", function () { + const testWallets = resolve(__dirname, "..", "testdata", "testwallets"); + const DUMMY_MNEMONIC = + "moral volcano peasant pass circle pen over picture flat shop clap goat never lyrics gather prepare woman film husband gravity behind test tiger improve"; + const alice = `${testWallets}/alice.pem`; + it("should create account from pem file", async function () { + const account = await Account.newFromPem(alice); + + assert.equal( + account.secretKey.valueOf().toString("hex"), + "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9", + ); + assert.equal(account.address.toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + }); + + it("should create account from keystore", async function () { + const account = Account.newFromKeystore(`${testWallets}/withDummyMnemonic.json`, "password"); + + assert.equal( + account.secretKey.valueOf().toString("hex"), + "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9", + ); + assert.equal(account.address.toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + }); + + it("should create account from mnemonic", async function () { + const account = Account.newFromMnemonic(DUMMY_MNEMONIC); + + assert.equal( + account.secretKey.valueOf().toString("hex"), + "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9", + ); + assert.equal(account.address.toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + }); + + it("should create account from keypair", async function () { + const secretKey = UserSecretKey.fromString("413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9"); + const keypair = new KeyPair(secretKey); + const account = Account.newFromKeypair(keypair); + + assert.deepEqual(account.secretKey, secretKey); + assert.equal(account.address.toBech32(), "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + }); + + it("should increase nonce on account", async function () { + const account = Account.newFromMnemonic(DUMMY_MNEMONIC); + account.nonce = 42n; + + assert.equal(account.getNonceThenIncrement(), 42n); + assert.equal(account.getNonceThenIncrement(), 43n); + }); + + it("should sign transaction", async function () { + const transaction = new Transaction({ + nonce: 89n, + value: 0n, + receiver: Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), + sender: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + gasPrice: 1000000000n, + gasLimit: 50000n, + data: new Uint8Array(), + chainID: "local-testnet", + version: 1, + options: 0, + }); + + const account = Account.newFromMnemonic(DUMMY_MNEMONIC); + transaction.signature = account.signTransaction(transaction); + + assert.equal( + Buffer.from(transaction.signature).toString("hex"), + "b56769014f2bdc5cf9fc4a05356807d71fcf8775c819b0f1b0964625b679c918ffa64862313bfef86f99b38cb84fcdb16fa33ad6eb565276616723405cd8f109", + ); + }); + + it("should sign message", async function () { + const message = new Message({ + data: new Uint8Array(Buffer.from("hello")), + }); + + const account = Account.newFromMnemonic(DUMMY_MNEMONIC); + message.signature = account.signMessage(message); + + assert.equal( + Buffer.from(message.signature).toString("hex"), + "561bc58f1dc6b10de208b2d2c22c9a474ea5e8cabb59c3d3ce06bbda21cc46454aa71a85d5a60442bd7784effa2e062fcb8fb421c521f898abf7f5ec165e5d0f", + ); + }); +}); diff --git a/src/accounts/account.ts b/src/accounts/account.ts index 5eea33794..a52258765 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -1,6 +1,11 @@ +import * as fs from "fs"; +import { PathLike } from "fs"; +import { Message, MessageComputer, TransactionComputer } from ".."; import { Address } from "../address"; import { LibraryConfig } from "../config"; -import { Mnemonic, UserSigner, UserWallet } from "../wallet"; +import { Transaction } from "../transaction"; +import { KeyPair, Mnemonic, UserPublicKey, UserSecretKey, UserSigner, UserWallet } from "../wallet"; +import { UserPem } from "../wallet/userPem"; import { IAccount } from "./interfaces"; /** @@ -18,32 +23,63 @@ export class Account implements IAccount { nonce: bigint = 0n; /** - * The signer of the account. + * The secret key of the account. */ - private signer?: UserSigner; + readonly secretKey: UserSecretKey; /** - * Creates an account object from an address + * The public key of the account. */ - constructor(address: Address, signer?: UserSigner) { - this.address = address; - this.signer = signer; - } + readonly publicKey: UserPublicKey; /** - * Increments (locally) the nonce (the account sequence number). + * Creates an account object from an address */ - incrementNonce() { - this.nonce = this.nonce + 1n; + constructor(secretKey: UserSecretKey, hrp: string = LibraryConfig.DefaultAddressHrp) { + this.secretKey = secretKey; + this.publicKey = secretKey.generatePublicKey(); + this.address = this.publicKey.toAddress(hrp); + } + + static async newFromPem( + path: PathLike, + index: number = 0, + hrp: string = LibraryConfig.DefaultAddressHrp, + ): Promise { + const text = await fs.promises.readFile(path, { encoding: "utf8" }); + const userSigner = UserSigner.fromPem(text, index); + return new Account(userSigner.secretKey, hrp); + } + + static newFromKeystore( + filePath: string, + password: string, + addressIndex?: number, + hrp: string = LibraryConfig.DefaultAddressHrp, + ): Account { + const secretKey = UserWallet.loadSecretKey(filePath, password, addressIndex); + return new Account(secretKey, hrp); + } + + static newFromMnemonic( + mnemonic: string, + addressIndex: number = 0, + hrp: string = LibraryConfig.DefaultAddressHrp, + ): Account { + const mnemonicHandler = Mnemonic.fromString(mnemonic); + const secretKey = mnemonicHandler.deriveKey(addressIndex); + return new Account(secretKey, hrp); + } + + static newFromKeypair(keypair: KeyPair, hrp: string = LibraryConfig.DefaultAddressHrp): Account { + return new Account(keypair.secretKey, hrp); } /** - * Gets then increments (locally) the nonce (the account sequence number). + * Increments (locally) the nonce (the account sequence number). */ - getNonceThenIncrement(): bigint { - let nonce = this.nonce; + incrementNonce() { this.nonce = this.nonce + 1n; - return nonce; } /** @@ -56,37 +92,39 @@ export class Account implements IAccount { }; } - sign(data: Uint8Array): Promise { - if (!this.signer) { - throw new Error("Signer not initialiezed, please provide the signer when account is instantiated"); - } - return this.signer.sign(data); + sign(data: Uint8Array): Uint8Array { + return this.secretKey.sign(data); } - static newFromPem(path: string, index: number = 0, hrp: string = LibraryConfig.DefaultAddressHrp): Account { - const userSigner = UserSigner.fromPem(path, index); - return new Account(userSigner.getAddress(hrp), userSigner); + verify(data: Uint8Array, signature: Uint8Array): boolean { + return this.publicKey.verify(data, signature); } - static newFromMnemonic( - mnemonic: string, - addressIndex: number = 0, - hrp: string = LibraryConfig.DefaultAddressHrp, - ): Account { - const mnemonicHandler = Mnemonic.fromString(mnemonic); - const secretKey = mnemonicHandler.deriveKey(addressIndex); - const userSigner = new UserSigner(secretKey); - return new Account(userSigner.getAddress(hrp), userSigner); + signTransaction(transaction: Transaction): Uint8Array { + const transactionComputer = new TransactionComputer(); + const serializedTransaction = transactionComputer.computeBytesForSigning(transaction); + return this.secretKey.sign(serializedTransaction); } - static newFromKeystore( - filePath: string, - password: string, - addressIndex?: number, - hrp: string = LibraryConfig.DefaultAddressHrp, - ): Account { - const secretKey = UserWallet.loadSecretKey(filePath, password, addressIndex); - const userSigner = new UserSigner(secretKey); - return new Account(userSigner.getAddress(hrp), userSigner); + signMessage(message: Message): Uint8Array { + const messageComputer = new MessageComputer(); + const serializedMessage = messageComputer.computeBytesForSigning(message); + return this.secretKey.sign(serializedMessage); + } + + getNonceThenIncrement(): bigint { + let nonce = this.nonce; + this.nonce = this.nonce + 1n; + return nonce; + } + + saveToPem(path: string): void { + const pem = new UserPem(this.address.toBech32(), this.secretKey); + pem.save(path); + } + + saveToKeystore(path: PathLike, password: string): void { + const wallet = UserWallet.fromSecretKey({ secretKey: this.secretKey, password }); + wallet.save(path, this.address.getHrp()); } } diff --git a/src/accounts/interfaces.ts b/src/accounts/interfaces.ts index 482b99900..72001424d 100644 --- a/src/accounts/interfaces.ts +++ b/src/accounts/interfaces.ts @@ -3,5 +3,5 @@ import { Address } from "../address"; export interface IAccount { readonly address: Address; - sign(data: Uint8Array): Promise; + sign(data: Uint8Array): Uint8Array; } diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 782437606..d86816cc6 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -1,26 +1,24 @@ import { assert } from "chai"; import { readFileSync } from "fs"; +import path from "path"; import { Account } from "../accounts/account"; import { Address } from "../address"; -import { loadAbiRegistry, loadTestWallet, TestWallet } from "../testutils"; +import { loadAbiRegistry } from "../testutils"; import { TransactionComputer } from "../transactionComputer"; import { DevnetEntrypoint } from "./entrypoints"; describe("TestEntrypoint", () => { const entrypoint = new DevnetEntrypoint(); - let alicePem: TestWallet; - let bobPem: TestWallet; let txComputer: TransactionComputer; before(async function () { - alicePem = await loadTestWallet("alice"); - bobPem = await loadTestWallet("bob"); txComputer = new TransactionComputer(); }); it("native transfer", async () => { const controller = entrypoint.createTransfersController(); - const sender = Account.newFromPem(alicePem.pemFileText); + const filePath = path.join("src", "testdata", "testwallets", "alice.pem"); + const sender = await Account.newFromPem(filePath); sender.nonce = 77777n; const transaction = await controller.createTransactionForTransfer( @@ -41,7 +39,8 @@ describe("TestEntrypoint", () => { it("contract flow", async function () { this.timeout(30000); const abi = await loadAbiRegistry("src/testdata/adder.abi.json"); - const sender = Account.newFromPem(alicePem.pemFileText); + const filePath = path.join("src", "testdata", "testwallets", "alice.pem"); + const sender = await Account.newFromPem(filePath); sender.nonce = await entrypoint.recallAccountNonce(sender.address); const controller = entrypoint.createSmartContractController(abi); @@ -85,10 +84,12 @@ describe("TestEntrypoint", () => { it("create relayed transaction", async function () { const transferController = entrypoint.createTransfersController(); - const sender = Account.newFromPem(alicePem.pemFileText); + const filePath = path.join("src", "testdata", "testwallets", "alice.pem"); + const sender = await Account.newFromPem(filePath); sender.nonce = 77777n; - const relayer = Account.newFromPem(bobPem.pemFileText); + const bobPath = path.join("src", "testdata", "testwallets", "alice.pem"); + const relayer = await Account.newFromPem(bobPath); relayer.nonce = 7n; const transaction = await transferController.createTransactionForTransfer( @@ -101,7 +102,7 @@ describe("TestEntrypoint", () => { ); const innerTransactionGasLimit = transaction.gasLimit; transaction.gasLimit = BigInt(0); - transaction.signature = await sender.sign(txComputer.computeBytesForSigning(transaction)); + transaction.signature = sender.sign(txComputer.computeBytesForSigning(transaction)); const relayedController = entrypoint.createRelayedController(); const relayedTransaction = await relayedController.createRelayedV2Transaction( @@ -121,4 +122,12 @@ describe("TestEntrypoint", () => { ); assert.equal(relayedTransaction.gasLimit, 442000n); }); + + it("create account", async () => { + const account = await entrypoint.createAccount(); + assert.isNotNull(account); + assert.isNotNull(account.address); + assert.equal(account.secretKey.valueOf().length, 32); + assert.equal(account.publicKey.valueOf().length, 32); + }); }); diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index e6340d0f3..750b9c660 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -1,5 +1,6 @@ import { AbiRegistry } from "../abi"; import { AccountController, AccountTransactionsFactory } from "../accountManagement"; +import { Account } from "../accounts"; import { IAccount } from "../accounts/interfaces"; import { Address } from "../address"; import { DelegationController, DelegationTransactionsFactory } from "../delegation"; @@ -19,7 +20,7 @@ import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TransactionWatcher } from "../transactionWatcher"; import { TransferTransactionsFactory } from "../transfers"; import { TransfersController } from "../transfers/transfersControllers"; -import { UserVerifier } from "../wallet"; +import { UserSecretKey, UserVerifier } from "../wallet"; import { DevnetEntrypointConfig, MainnetEntrypointConfig, TestnetEntrypointConfig } from "./config"; class NetworkEntrypoint { @@ -38,6 +39,15 @@ class NetworkEntrypoint { this.chainId = options.chainId; } + async createAccount(): Promise { + const secretKey = UserSecretKey.generate(); + return new Account(secretKey); + } + + async getAirdrop(_address: Address): Promise { + throw new Error("Not implemented"); + } + async signTransaction(transaction: Transaction, account: IAccount): Promise { const txComputer = new TransactionComputer(); transaction.signature = await account.sign(txComputer.computeBytesForSigning(transaction)); @@ -49,11 +59,6 @@ class NetworkEntrypoint { return verifier.verify(txComputer.computeBytesForVerifying(transaction), transaction.signature); } - async signMessage(message: Message, account: IAccount): Promise { - const messageComputer = new MessageComputer(); - message.signature = await account.sign(messageComputer.computeBytesForSigning(message)); - } - verifyMessageSignature(message: Message): boolean { if (!message.address) { throw new Error("`address` property of Message is not set"); diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index 628e53d1e..ab0c9a740 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -103,7 +103,7 @@ export class TestWallet { this.signer = new UserSigner(UserSecretKey.fromString(secretKeyHex)); this.keyFileObject = keyFileObject; this.pemFileText = pemFileText; - this.account = new Account(this.address); + this.account = new Account(new UserSecretKey(this.secretKey)); } getAddress(): Address { diff --git a/src/wallet/crypto/pubkeyEncryptor.ts b/src/wallet/crypto/pubkeyEncryptor.ts index 0c89bf16c..3210c8dc8 100644 --- a/src/wallet/crypto/pubkeyEncryptor.ts +++ b/src/wallet/crypto/pubkeyEncryptor.ts @@ -17,7 +17,11 @@ export class PubkeyEncryptor { // For the nonce we use a random component and a deterministic one based on the message // - this is so we won't completely rely on the random number generator - const nonceDeterministic = crypto.createHash('sha256').update(data).digest().slice(0, PubKeyEncNonceLength / 2); + const nonceDeterministic = crypto + .createHash("sha256") + .update(data) + .digest() + .slice(0, PubKeyEncNonceLength / 2); const nonceRandom = nacl.randomBytes(PubKeyEncNonceLength / 2); const nonce = Buffer.concat([nonceDeterministic, nonceRandom]); const encryptedMessage = nacl.box(data, nonce, recipientDHPubKey, edhConvertedSecretKey); @@ -25,23 +29,24 @@ export class PubkeyEncryptor { // Note that the ciphertext is already authenticated for the ephemeral key - but we want it authenticated by // the ed25519 key which the user interacts with. A signature over H(ciphertext | edhPubKey) // would be enough - const authMessage = crypto.createHash('sha256').update( - Buffer.concat([encryptedMessage, edhPair.publicKey]) - ).digest(); + const authMessage = crypto + .createHash("sha256") + .update(Buffer.concat([encryptedMessage, edhPair.publicKey])) + .digest(); const signature = authSecretKey.sign(authMessage); return new X25519EncryptedData({ version: PubKeyEncVersion, - nonce: Buffer.from(nonce).toString('hex'), + nonce: Buffer.from(nonce).toString("hex"), cipher: PubKeyEncCipher, - ciphertext: Buffer.from(encryptedMessage).toString('hex'), - mac: signature.toString('hex'), + ciphertext: Buffer.from(encryptedMessage).toString("hex"), + mac: Buffer.from(signature).toString("hex"), identities: { recipient: recipientPubKey.hex(), - ephemeralPubKey: Buffer.from(edhPair.publicKey).toString('hex'), + ephemeralPubKey: Buffer.from(edhPair.publicKey).toString("hex"), originatorPubKey: authSecretKey.generatePublicKey().hex(), - } + }, }); } } diff --git a/src/wallet/index.ts b/src/wallet/index.ts index 7207e0c14..ebcbb8db3 100644 --- a/src/wallet/index.ts +++ b/src/wallet/index.ts @@ -1,4 +1,5 @@ export * from "./crypto"; +export * from "./keypair"; export * from "./mnemonic"; export * from "./pem"; export * from "./userKeys"; diff --git a/src/wallet/keypair.ts b/src/wallet/keypair.ts new file mode 100644 index 000000000..61368a109 --- /dev/null +++ b/src/wallet/keypair.ts @@ -0,0 +1,39 @@ +import { UserPublicKey, UserSecretKey } from "./userKeys"; + +export class KeyPair { + readonly secretKey: UserSecretKey; + readonly publicKey: UserPublicKey; + + constructor(secretKey: UserSecretKey) { + this.secretKey = secretKey; + this.publicKey = this.secretKey.generatePublicKey(); + } + + static generate(): KeyPair { + const secretKey = UserSecretKey.generate(); + return new KeyPair(secretKey); + } + + static newFromBytes(data: Uint8Array): KeyPair { + const secretKey = new UserSecretKey(data); + return new KeyPair(secretKey); + } + + sign(data: Uint8Array): Uint8Array { + // Signs the data using the secret key of the keypair + return this.secretKey.sign(data); + } + + verify(data: Uint8Array, signature: Uint8Array): boolean { + // Verifies the data using the public key of the keypair + return this.publicKey.verify(data, signature); + } + + getSecretKey(): UserSecretKey { + return this.secretKey; + } + + getPublicKey(): UserPublicKey { + return this.publicKey; + } +} diff --git a/src/wallet/pemEntry.ts b/src/wallet/pemEntry.ts new file mode 100644 index 000000000..bc463d40a --- /dev/null +++ b/src/wallet/pemEntry.ts @@ -0,0 +1,71 @@ +import * as base64 from "base64-js"; // For Base64 encoding and decoding + +export class PemEntry { + label: string; + message: Uint8Array; + + constructor(label: string, message: Uint8Array) { + this.label = label; + this.message = message; + } + + static fromTextAll(pemText: string): PemEntry[] { + const lines = PemEntry.cleanLines(pemText.split("\n")); + // Group lines based on whether they include "-----" + const groupedLines: { [key: string]: string[] } = PemEntry.groupLines(lines); + const messageLinesGroups = Object.values(groupedLines).filter((_, idx) => idx % 2 === 1) as string[][]; + const messageBase64s = messageLinesGroups.map((lines) => lines.join("")); + const labels = PemEntry.parseLabels(lines); + + return messageBase64s.map((messageBase64, index) => { + const messageHex = new TextDecoder().decode(base64.toByteArray(messageBase64)); + const messageBytes = Uint8Array.from(Buffer.from(messageHex, "hex")); + return new PemEntry(labels[index], messageBytes); + }); + } + + private static groupLines(lines: string[]): { [key: string]: string[] } { + return lines.reduce( + (acc, line) => { + const isHeaderOrFooter = line.includes("-----"); + const key = isHeaderOrFooter ? "headers" : "messages"; + + if (!acc[key]) { + acc[key] = []; + } + acc[key].push(line); + + return acc; + }, + { headers: [], messages: [] } as { [key: string]: string[] }, + ); + } + + toText(): string { + const header = `-----BEGIN PRIVATE KEY for ${this.label}-----`; + const footer = `-----END PRIVATE KEY for ${this.label}-----`; + + const messageHex = Buffer.from(this.message).toString("hex"); + const messageBase64 = base64.fromByteArray(Buffer.from(messageHex, "utf-8")); + const payloadLines = PemEntry.wrapText(messageBase64, 64); + const payload = payloadLines.join("\n"); + + return [header, payload, footer].join("\n"); + } + + private static cleanLines(lines: string[]): string[] { + return lines.map((line) => line.trim()).filter((line) => line.length > 0); + } + + private static parseLabels(headers: string[]): string[] { + const marker = "-----BEGIN PRIVATE KEY for"; + return headers + .filter((line) => line.startsWith(marker)) + .map((line) => line.replace(marker, "").replace(/-/g, "").trim()); + } + + private static wrapText(text: string, width: number): string[] { + const regex = new RegExp(`.{1,${width}}`, "g"); // Match chunks of up to `width` characters + return text.match(regex) || []; + } +} diff --git a/src/wallet/userKeys.ts b/src/wallet/userKeys.ts index eaee0e10a..31bcb8133 100644 --- a/src/wallet/userKeys.ts +++ b/src/wallet/userKeys.ts @@ -1,5 +1,6 @@ import * as ed from "@noble/ed25519"; import { sha512 } from "@noble/hashes/sha512"; +import nacl from "tweetnacl"; import { Address } from "../address"; import { guardLength } from "./assertions"; import { parseUserKey } from "./pem"; @@ -36,9 +37,15 @@ export class UserSecretKey { return new UserPublicKey(buffer); } - sign(message: Buffer | Uint8Array): Buffer { + static generate(): UserSecretKey { + const keyPair = nacl.sign.keyPair(); // Generates a new signing keypair + const secretKey = keyPair.secretKey.subarray(0, 32); // Extract only the private key part + return new UserSecretKey(secretKey); + } + + sign(message: Buffer | Uint8Array): Uint8Array { const signature = ed.sync.sign(new Uint8Array(message), new Uint8Array(this.buffer)); - return Buffer.from(signature); + return signature; } hex(): string { diff --git a/src/wallet/userPem.ts b/src/wallet/userPem.ts new file mode 100644 index 000000000..5aafddade --- /dev/null +++ b/src/wallet/userPem.ts @@ -0,0 +1,59 @@ +import { PathLike, readFileSync, writeFileSync } from "fs"; +import { isAbsolute, join, resolve } from "path"; +import { PemEntry } from "./pemEntry"; +import { USER_SEED_LENGTH, UserPublicKey, UserSecretKey } from "./userKeys"; + +export class UserPem { + label: string; + secretKey: UserSecretKey; + publicKey: UserPublicKey; + + constructor(label: string, secretKey: UserSecretKey) { + this.label = label; + this.secretKey = secretKey; + this.publicKey = secretKey.generatePublicKey(); + } + + static fromFile(path: PathLike, index: number = 0): UserPem { + return this.fromFileAll(path)[index]; + } + + static fromFileAll(path: PathLike): UserPem[] { + const resolvedPath = isAbsolute(path.toString()) + ? resolve(path.toString()) + : resolve(join(process.cwd(), path.toString())); + const text = readFileSync(resolvedPath, "utf-8"); + return this.fromTextAll(text); + } + + static fromText(text: string, index: number = 0): UserPem { + const items = this.fromTextAll(text); + return items[index]; + } + + static fromTextAll(text: string): UserPem[] { + const entries = PemEntry.fromTextAll(text); + const resultItems: UserPem[] = []; + + for (const entry of entries) { + const secretKey = new UserSecretKey(entry.message.slice(0, USER_SEED_LENGTH)); + const item = new UserPem(entry.label, secretKey); + resultItems.push(item); + } + + return resultItems; + } + + save(path: PathLike): void { + const resolvedPath = isAbsolute(path.toString()) + ? resolve(path.toString()) + : resolve(join(process.cwd(), path.toString())); + writeFileSync(resolvedPath, this.toText(), { encoding: "utf-8" }); + } + + toText(): string { + const message = new Uint8Array([...this.secretKey.valueOf(), ...this.publicKey.valueOf()]); + const pemEntry = new PemEntry(this.label, message); + return pemEntry.toText(); + } +} diff --git a/src/wallet/userSigner.ts b/src/wallet/userSigner.ts index acc8f6f09..a74518ffd 100644 --- a/src/wallet/userSigner.ts +++ b/src/wallet/userSigner.ts @@ -3,22 +3,13 @@ import { ErrSignerCannotSign } from "../errors"; import { UserSecretKey } from "./userKeys"; import { UserWallet } from "./userWallet"; -interface IUserSecretKey { - sign(message: Buffer | Uint8Array): Buffer; - generatePublicKey(): IUserPublicKey; -} - -interface IUserPublicKey { - toAddress(hrp?: string): { bech32(): string }; -} - /** * ed25519 signer */ export class UserSigner { - protected readonly secretKey: IUserSecretKey; + readonly secretKey: UserSecretKey; - constructor(secretKey: IUserSecretKey) { + constructor(secretKey: UserSecretKey) { this.secretKey = secretKey; } @@ -32,7 +23,7 @@ export class UserSigner { return new UserSigner(secretKey); } - async sign(data: Buffer | Uint8Array): Promise { + async sign(data: Buffer | Uint8Array): Promise { try { const signature = this.secretKey.sign(data); return signature; diff --git a/src/wallet/userWallet.ts b/src/wallet/userWallet.ts index 3d505ff60..974cf2be0 100644 --- a/src/wallet/userWallet.ts +++ b/src/wallet/userWallet.ts @@ -1,5 +1,6 @@ -import { readFileSync } from "fs"; -import path from "path"; +import { PathLike, readFileSync, writeFileSync } from "fs"; +import path, { isAbsolute, join, resolve } from "path"; +import { LibraryConfig } from "../config"; import { Err } from "../errors"; import { Logger } from "../logger"; import { CipherAlgorithm, Decryptor, EncryptedData, Encryptor, KeyDerivationFunction, Randomness } from "./crypto"; @@ -242,4 +243,13 @@ export class UserWallet { crypto: cryptoSection, }; } + + save(path: PathLike, addressHrp: string = LibraryConfig.DefaultAddressHrp): void { + const resolvedPath = isAbsolute(path.toString()) + ? resolve(path.toString()) + : resolve(join(process.cwd(), path.toString())); + + const jsonContent = this.toJSON(addressHrp); + writeFileSync(resolvedPath, jsonContent, { encoding: "utf-8" }); + } } diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index 35f0b7632..0cc2408f0 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -321,7 +321,7 @@ describe("test user wallets", () => { `{"nonce":0,"value":"0","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"","gasPrice":1000000000,"gasLimit":50000,"data":"Zm9v","chainID":"1","version":1}`, ); assert.equal( - signature.toString("hex"), + Buffer.from(signature).toString("hex"), "a3b61a2fe461f3393c42e6cb0477a6b52ffd92168f10c111f6aa8d0a310ee0c314fae0670f8313f1ad992933ac637c61a8ff20cc20b6a8b2260a4af1a120a70d", ); assert.isTrue(verifier.verify(serialized, signature)); @@ -345,7 +345,7 @@ describe("test user wallets", () => { `{"nonce":8,"value":"10000000000000000000","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"","gasPrice":1000000000,"gasLimit":50000,"chainID":"1","version":1}`, ); assert.equal( - signature.toString("hex"), + Buffer.from(signature).toString("hex"), "f136c901d37349a7da8cfe3ab5ec8ef333b0bc351517c0e9bef9eb9704aed3077bf222769cade5ff29dffe5f42e4f0c5e0b068bdba90cd2cb41da51fd45d5a03", ); }); @@ -386,11 +386,11 @@ describe("test user wallets", () => { `{"nonce":0,"value":"0","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz","guardian":"erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx","gasPrice":1000000000,"gasLimit":50000,"data":"Zm9v","chainID":"1","options":2,"version":2}`, ); assert.equal( - signature.toString("hex"), + Buffer.from(signature).toString("hex"), "00b867ae749616954711ef227c0a3f5c6556246f26dbde12ad929a099094065341a0fae7c5ced98e6bdd100ce922c975667444ea859dce9597b46e63cade2a03", ); assert.equal( - guardianSignature.toString("hex"), + Buffer.from(guardianSignature).toString("hex"), "1326e44941ef7bfbad3edf346e72abe23704ee32b4b6a6a6a9b793bd7c62b6d4a69d3c6ea2dddf7eabc8df8fe291cd24822409ab9194b6a0f3bbbf1c59b0a10f", ); assert.isTrue(verifier.verify(serialized, signature)); @@ -418,11 +418,11 @@ describe("test user wallets", () => { `{"nonce":8,"value":"10000000000000000000","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz","guardian":"erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx","gasPrice":1000000000,"gasLimit":50000,"chainID":"1","options":2,"version":2}`, ); assert.equal( - signature.toString("hex"), + Buffer.from(signature).toString("hex"), "49a63fa0e3cfb81a2b6d926c741328fb270ea4f58fa32585fe8aa3cde191245e5a13c5c059d5576f4c05fc24d2534a2124ff79c98d067ce8412c806779066b03", ); assert.equal( - guardianSignature.toString("hex"), + Buffer.from(guardianSignature).toString("hex"), "4c25a54381bf66576d05f32659d30672b5b0bfbfb6b6aee52290d28cfbc87860637f095f83663a1893d12d0d5a27b2ab3325829ff1f1215b81a7ced8ee5d7203", ); assert.isTrue(verifier.verify(serialized, signature)); @@ -446,7 +446,7 @@ describe("test user wallets", () => { assert.deepEqual(await signer.sign(serialized), await signer.sign(Uint8Array.from(serialized))); assert.equal( - signature.toString("hex"), + Buffer.from(signature).toString("hex"), "ba4fa95fea1402e4876abf1d5a510615aab374ee48bb76f5230798a7d3f2fcae6ba91ba56c6d62e6e7003ce531ff02f219cb7218dd00dd2ca650ba747f19640a", ); }); diff --git a/src/wallet/usersBenchmark.spec.ts b/src/wallet/usersBenchmark.spec.ts index eeb318e0a..38459ed25 100644 --- a/src/wallet/usersBenchmark.spec.ts +++ b/src/wallet/usersBenchmark.spec.ts @@ -28,7 +28,7 @@ describe("behchmark sign and verify", () => { for (let i = 0; i < n; i++) { const signature = secretKeys[i].sign(messages[i]); - goodSignatures.push(signature); + goodSignatures.push(Buffer.from(signature)); } console.timeEnd("sign"); diff --git a/src/wallet/validators.spec.ts b/src/wallet/validators.spec.ts index 5a01b7a45..c3a93bae5 100644 --- a/src/wallet/validators.spec.ts +++ b/src/wallet/validators.spec.ts @@ -2,31 +2,54 @@ import { assert } from "chai"; import { BLS, ValidatorSecretKey } from "./validatorKeys"; describe("test validator keys", () => { - it("should create secret key and sign a message", async () => { await BLS.initIfNecessary(); - let secretKey = Buffer.from(Buffer.from("N2NmZjk5YmQ2NzE1MDJkYjdkMTViYzhhYmMwYzlhODA0ZmI5MjU0MDZmYmRkNTBmMWU0YzE3YTRjZDc3NDI0Nw==", "base64").toString(), "hex"); + let secretKey = Buffer.from( + Buffer.from( + "N2NmZjk5YmQ2NzE1MDJkYjdkMTViYzhhYmMwYzlhODA0ZmI5MjU0MDZmYmRkNTBmMWU0YzE3YTRjZDc3NDI0Nw==", + "base64", + ).toString(), + "hex", + ); let key = new ValidatorSecretKey(secretKey); - + assert.deepEqual(new ValidatorSecretKey(secretKey), new ValidatorSecretKey(Uint8Array.from(secretKey))); - assert.equal(key.generatePublicKey().hex(), "e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208"); + assert.equal( + key.generatePublicKey().hex(), + "e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208", + ); const data = Buffer.from("hello"); let signature = key.sign(data); assert.deepEqual(key.sign(data), key.sign(Uint8Array.from(data))); - assert.equal(signature.toString("hex"), "84fd0a3a9d4f1ea2d4b40c6da67f9b786284a1c3895b7253fec7311597cda3f757862bb0690a92a13ce612c33889fd86"); + assert.equal( + Buffer.from(signature).toString("hex"), + "84fd0a3a9d4f1ea2d4b40c6da67f9b786284a1c3895b7253fec7311597cda3f757862bb0690a92a13ce612c33889fd86", + ); - secretKey = Buffer.from(Buffer.from("ODA4NWJhMWQ3ZjdjM2RiOTM4YWQ3MDU5NWEyYmRhYjA5NjQ0ZjFlYzM4MDNiZTE3MWMzM2YxNGJjODBkNGUzYg==", "base64").toString(), "hex"); + secretKey = Buffer.from( + Buffer.from( + "ODA4NWJhMWQ3ZjdjM2RiOTM4YWQ3MDU5NWEyYmRhYjA5NjQ0ZjFlYzM4MDNiZTE3MWMzM2YxNGJjODBkNGUzYg==", + "base64", + ).toString(), + "hex", + ); key = new ValidatorSecretKey(secretKey); - assert.equal(key.generatePublicKey().hex(), "78689fd4b1e2e434d567fe01e61598a42717d83124308266bd09ccc15d2339dd318c019914b86ac29adbae5dd8a02d0307425e9bd85a296e94943708c72f8c670f0b7c50a890a5719088dbd9f1d062cad9acffa06df834106eebe1a4257ef00d"); + assert.equal( + key.generatePublicKey().hex(), + "78689fd4b1e2e434d567fe01e61598a42717d83124308266bd09ccc15d2339dd318c019914b86ac29adbae5dd8a02d0307425e9bd85a296e94943708c72f8c670f0b7c50a890a5719088dbd9f1d062cad9acffa06df834106eebe1a4257ef00d", + ); signature = key.sign(data); assert.deepEqual(key.sign(data), key.sign(Uint8Array.from(data))); - assert.equal(signature.toString("hex"), "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98"); + assert.equal( + Buffer.from(signature).toString("hex"), + "be2e593ff10899a2ee8e1d5c8094e36c9f48e04b87e129991ff09475808743e07bb41bf6e7bc1463fa554c4b46594b98", + ); }); it("should handle PEM files", async () => { @@ -35,7 +58,13 @@ describe("test validator keys", () => { let text = `-----BEGIN foobar N2NmZjk5YmQ2NzE1MDJkYjdkMTViYzhhYmMwYzlhODA0ZmI5MjU0MDZmYmRkNTBmMWU0YzE3YTRjZDc3NDI0Nw== -----END foobar`; - assert.equal(ValidatorSecretKey.fromPem(text).hex(), "7cff99bd671502db7d15bc8abc0c9a804fb925406fbdd50f1e4c17a4cd774247"); - assert.equal(ValidatorSecretKey.fromPem(text).generatePublicKey().hex(), "e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208"); + assert.equal( + ValidatorSecretKey.fromPem(text).hex(), + "7cff99bd671502db7d15bc8abc0c9a804fb925406fbdd50f1e4c17a4cd774247", + ); + assert.equal( + ValidatorSecretKey.fromPem(text).generatePublicKey().hex(), + "e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208", + ); }); }); From 7777d398a6a8ceadf56691d0c36b45cfe9a63a3a Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 28 Jan 2025 15:55:17 +0200 Subject: [PATCH 144/214] Add pem entry tests --- src/testdata/testwallets/multipleUserKeys.pem | 15 +++ .../testwallets/multipleValidatorKeys.pem | 16 +++ src/testdata/testwallets/validatorKey00.pem | 4 + src/wallet/pemEntry.spec.ts | 122 ++++++++++++++++++ src/wallet/pemEntry.ts | 77 ++++++----- 5 files changed, 204 insertions(+), 30 deletions(-) create mode 100644 src/testdata/testwallets/multipleUserKeys.pem create mode 100644 src/testdata/testwallets/multipleValidatorKeys.pem create mode 100644 src/testdata/testwallets/validatorKey00.pem create mode 100644 src/wallet/pemEntry.spec.ts diff --git a/src/testdata/testwallets/multipleUserKeys.pem b/src/testdata/testwallets/multipleUserKeys.pem new file mode 100644 index 000000000..c8e708eff --- /dev/null +++ b/src/testdata/testwallets/multipleUserKeys.pem @@ -0,0 +1,15 @@ +-----BEGIN PRIVATE KEY for erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th----- +NDEzZjQyNTc1ZjdmMjZmYWQzMzE3YTc3ODc3MTIxMmZkYjgwMjQ1ODUwOTgxZTQ4 +YjU4YTRmMjVlMzQ0ZThmOTAxMzk0NzJlZmY2ODg2NzcxYTk4MmYzMDgzZGE1ZDQy +MWYyNGMyOTE4MWU2Mzg4ODIyOGRjODFjYTYwZDY5ZTE= +-----END PRIVATE KEY for erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th----- +-----BEGIN PRIVATE KEY for erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx----- +YjhjYTZmODIwM2ZiNGI1NDVhOGU4M2M1Mzg0ZGEwMzNjNDE1ZGIxNTViNTNmYjVi +OGViYTdmZjVhMDM5ZDYzOTgwNDlkNjM5ZTVhNjk4MGQxY2QyMzkyYWJjY2U0MTAy +OWNkYTc0YTE1NjM1MjNhMjAyZjA5NjQxY2MyNjE4Zjg= +-----END PRIVATE KEY for erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx----- +-----BEGIN PRIVATE KEY for erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8----- +ZTI1M2E1NzFjYTE1M2RjMmFlZTg0NTgxOWY3NGJjYzk3NzNiMDU4NmVkZWFkMTVh +OTRjYjcyMzVhNTAyNzQzNmIyYTExNTU1Y2U1MjFlNDk0NGUwOWFiMTc1NDlkODVi +NDg3ZGNkMjZjODRiNTAxN2EzOWUzMWEzNjcwODg5YmE= +-----END PRIVATE KEY for erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8----- diff --git a/src/testdata/testwallets/multipleValidatorKeys.pem b/src/testdata/testwallets/multipleValidatorKeys.pem new file mode 100644 index 000000000..073fdbcc0 --- /dev/null +++ b/src/testdata/testwallets/multipleValidatorKeys.pem @@ -0,0 +1,16 @@ +-----BEGIN PRIVATE KEY for f8910e47cf9464777c912e6390758bb39715fffcb861b184017920e4a807b42553f2f21e7f3914b81bcf58b66a72ab16d97013ae1cff807cefc977ef8cbf116258534b9e46d19528042d16ef8374404a89b184e0a4ee18c77c49e454d04eae8d----- +N2MxOWJmM2EwYzU3Y2RkMWZiMDhlNDYwN2NlYmFhMzY0N2Q2YjkyNjFiNDY5M2Y2 +MWU5NmU1NGIyMThkNDQyYQ== +-----END PRIVATE KEY for f8910e47cf9464777c912e6390758bb39715fffcb861b184017920e4a807b42553f2f21e7f3914b81bcf58b66a72ab16d97013ae1cff807cefc977ef8cbf116258534b9e46d19528042d16ef8374404a89b184e0a4ee18c77c49e454d04eae8d----- +-----BEGIN PRIVATE KEY for 1b4e60e6d100cdf234d3427494dac55fbac49856cadc86bcb13a01b9bb05a0d9143e86c186c948e7ae9e52427c9523102efe9019a2a9c06db02993f2e3e6756576ae5a3ec7c235d548bc79de1a6990e1120ae435cb48f7fc436c9f9098b92a0d----- +MzAzNGIxZDU4NjI4YTg0Mjk4NGRhMGM3MGRhMGI1YTI1MWViYjJhZWJmNTFhZmM1 +YjU4NmUyODM5YjVlNTI2Mw== +-----END PRIVATE KEY for 1b4e60e6d100cdf234d3427494dac55fbac49856cadc86bcb13a01b9bb05a0d9143e86c186c948e7ae9e52427c9523102efe9019a2a9c06db02993f2e3e6756576ae5a3ec7c235d548bc79de1a6990e1120ae435cb48f7fc436c9f9098b92a0d----- +-----BEGIN PRIVATE KEY for e5dc552b4b170cdec4405ff8f9af20313bf0e2756d06c35877b6fbcfa6b354a7b3e2d439ea87999befb09a8fa1b3f014e57ec747bf738c4199338fcd4a87b373dd62f5c8329f1f5f245956bbb06685596a2e83dc38befa63e4a2b5c4ce408506----- +ZGU3ZTFiMzg1ZWRiYjBlMWU4ZjlmYzI1ZDkxYmQ4ZWVkNzFhMWRhN2NhYWI3MzJl +NmI0N2E0ODA0MmQ4NTIzZA== +-----END PRIVATE KEY for e5dc552b4b170cdec4405ff8f9af20313bf0e2756d06c35877b6fbcfa6b354a7b3e2d439ea87999befb09a8fa1b3f014e57ec747bf738c4199338fcd4a87b373dd62f5c8329f1f5f245956bbb06685596a2e83dc38befa63e4a2b5c4ce408506----- +-----BEGIN PRIVATE KEY for 12773304cb718250edd89770cedcbf675ccdb7fe2b30bd3185ca65ffa0d516879768ed03f92e41a6e5bc5340b78a9d02655e3b727c79730ead791fb68eaa02b84e1be92a816a9604a1ab9a6d3874b638487e2145239438a4bafac3889348d405----- +OGViZWIwN2QyOTZhZDI1Mjk0MDBiNDA2ODdhNzQxYTEzNWY4MzU3Zjc5ZjM5ZmNi +Mjg5NGE2Zjk3MDNhNTgxNg== +-----END PRIVATE KEY for 12773304cb718250edd89770cedcbf675ccdb7fe2b30bd3185ca65ffa0d516879768ed03f92e41a6e5bc5340b78a9d02655e3b727c79730ead791fb68eaa02b84e1be92a816a9604a1ab9a6d3874b638487e2145239438a4bafac3889348d405----- diff --git a/src/testdata/testwallets/validatorKey00.pem b/src/testdata/testwallets/validatorKey00.pem new file mode 100644 index 000000000..50a57c40b --- /dev/null +++ b/src/testdata/testwallets/validatorKey00.pem @@ -0,0 +1,4 @@ +-----BEGIN PRIVATE KEY for e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208----- +N2NmZjk5YmQ2NzE1MDJkYjdkMTViYzhhYmMwYzlhODA0ZmI5MjU0MDZmYmRkNTBm +MWU0YzE3YTRjZDc3NDI0Nw== +-----END PRIVATE KEY for e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208----- diff --git a/src/wallet/pemEntry.spec.ts b/src/wallet/pemEntry.spec.ts new file mode 100644 index 000000000..628472d8c --- /dev/null +++ b/src/wallet/pemEntry.spec.ts @@ -0,0 +1,122 @@ +import { assert } from "chai"; +import { readFileSync } from "fs"; +import path from "path"; +import { PemEntry } from "./pemEntry"; +import { USER_SEED_LENGTH } from "./userKeys"; + +describe("test pem entry", () => { + const walletsPath = path.join("src", "testdata", "testwallets"); + + it("should test from text all", () => { + let text = readFileSync(path.join(walletsPath, "alice.pem"), "utf-8"); + let entries = PemEntry.fromTextAll(text); + let entry = entries[0]; + + assert.lengthOf(entries, 1); + assert.equal(entry.label, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.equal( + Buffer.from(entry.message.slice(0, USER_SEED_LENGTH)).toString("hex"), + "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9", + ); + + text = readFileSync(path.join(walletsPath, "multipleUserKeys.pem"), "utf-8"); + entries = PemEntry.fromTextAll(text); + entry = entries[0]; + + assert.lengthOf(entries, 3); + assert.equal(entry.label, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.equal( + Buffer.from(entry.message.slice(0, USER_SEED_LENGTH)).toString("hex"), + "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9", + ); + + entry = entries[1]; + assert.equal(entry.label, "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); + assert.equal( + Buffer.from(entry.message.slice(0, USER_SEED_LENGTH)).toString("hex"), + "b8ca6f8203fb4b545a8e83c5384da033c415db155b53fb5b8eba7ff5a039d639", + ); + + entry = entries[2]; + assert.equal(entry.label, "erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"); + assert.equal( + Buffer.from(entry.message.slice(0, USER_SEED_LENGTH)).toString("hex"), + "e253a571ca153dc2aee845819f74bcc9773b0586edead15a94cb7235a5027436", + ); + }); + + it("should test from text all for validatiors", () => { + let text = readFileSync(path.join(walletsPath, "alice.pem"), "utf-8"); + let entries = PemEntry.fromTextAll(text); + let entry = entries[0]; + + assert.lengthOf(entries, 1); + assert.equal(entry.label, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.equal( + Buffer.from(entry.message.slice(0, USER_SEED_LENGTH)).toString("hex"), + "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9", + ); + + text = readFileSync(path.join(walletsPath, "multipleValidatorKeys.pem"), "utf-8"); + entries = PemEntry.fromTextAll(text); + entry = entries[0]; + + assert.lengthOf(entries, 4); + assert.equal( + entry.label, + "f8910e47cf9464777c912e6390758bb39715fffcb861b184017920e4a807b42553f2f21e7f3914b81bcf58b66a72ab16d97013ae1cff807cefc977ef8cbf116258534b9e46d19528042d16ef8374404a89b184e0a4ee18c77c49e454d04eae8d", + ); + assert.equal( + Buffer.from(entry.message).toString("hex"), + "7c19bf3a0c57cdd1fb08e4607cebaa3647d6b9261b4693f61e96e54b218d442a", + ); + + entry = entries[1]; + assert.equal( + entry.label, + "1b4e60e6d100cdf234d3427494dac55fbac49856cadc86bcb13a01b9bb05a0d9143e86c186c948e7ae9e52427c9523102efe9019a2a9c06db02993f2e3e6756576ae5a3ec7c235d548bc79de1a6990e1120ae435cb48f7fc436c9f9098b92a0d", + ); + assert.equal( + Buffer.from(entry.message).toString("hex"), + "3034b1d58628a842984da0c70da0b5a251ebb2aebf51afc5b586e2839b5e5263", + ); + + entry = entries[2]; + assert.equal( + entry.label, + "e5dc552b4b170cdec4405ff8f9af20313bf0e2756d06c35877b6fbcfa6b354a7b3e2d439ea87999befb09a8fa1b3f014e57ec747bf738c4199338fcd4a87b373dd62f5c8329f1f5f245956bbb06685596a2e83dc38befa63e4a2b5c4ce408506", + ); + assert.equal( + Buffer.from(entry.message).toString("hex"), + "de7e1b385edbb0e1e8f9fc25d91bd8eed71a1da7caab732e6b47a48042d8523d", + ); + + entry = entries[3]; + assert.equal( + entry.label, + "12773304cb718250edd89770cedcbf675ccdb7fe2b30bd3185ca65ffa0d516879768ed03f92e41a6e5bc5340b78a9d02655e3b727c79730ead791fb68eaa02b84e1be92a816a9604a1ab9a6d3874b638487e2145239438a4bafac3889348d405", + ); + assert.equal( + Buffer.from(entry.message).toString("hex"), + "8ebeb07d296ad2529400b40687a741a135f8357f79f39fcb2894a6f9703a5816", + ); + }); + + it("should test to text", () => { + let text = readFileSync(path.join(walletsPath, "alice.pem"), "utf-8").trim(); + assert.deepEqual(PemEntry.fromTextAll(text)[0].toText(), text); + + text = readFileSync(path.join(walletsPath, "validatorKey00.pem"), "utf-8").trim(); + assert.deepEqual(PemEntry.fromTextAll(text)[0].toText(), text); + + text = readFileSync(path.join(walletsPath, "multipleUserKeys.pem"), "utf-8").trim(); + let entries = PemEntry.fromTextAll(text); + let actualText = entries.map((entry) => entry.toText()).join("\n"); + assert.deepEqual(actualText, text); + + text = readFileSync(path.join(walletsPath, "multipleValidatorKeys.pem"), "utf-8").trim(); + entries = PemEntry.fromTextAll(text); + actualText = entries.map((entry) => entry.toText()).join("\n"); + assert.deepEqual(actualText, text); + }); +}); diff --git a/src/wallet/pemEntry.ts b/src/wallet/pemEntry.ts index bc463d40a..4cdfca3f1 100644 --- a/src/wallet/pemEntry.ts +++ b/src/wallet/pemEntry.ts @@ -11,34 +11,55 @@ export class PemEntry { static fromTextAll(pemText: string): PemEntry[] { const lines = PemEntry.cleanLines(pemText.split("\n")); - // Group lines based on whether they include "-----" - const groupedLines: { [key: string]: string[] } = PemEntry.groupLines(lines); - const messageLinesGroups = Object.values(groupedLines).filter((_, idx) => idx % 2 === 1) as string[][]; - const messageBase64s = messageLinesGroups.map((lines) => lines.join("")); - const labels = PemEntry.parseLabels(lines); - - return messageBase64s.map((messageBase64, index) => { - const messageHex = new TextDecoder().decode(base64.toByteArray(messageBase64)); + + // Group PEM entries into blocks of header, content, and footer + const blocks: string[][] = PemEntry.groupBlocks(lines); + + return blocks.map((block) => { + // Extract label from the header line + const header = block[0]; + const footer = block[block.length - 1]; + if (!header.startsWith("-----BEGIN PRIVATE KEY for") || !footer.startsWith("-----END PRIVATE KEY for")) { + throw new Error("Invalid PEM format"); + } + + const label = header.replace("-----BEGIN PRIVATE KEY for", "").replace("-----", "").trim(); + + // Join all content lines between header and footer + const base64Message = block.slice(1, block.length - 1).join(""); + + // Decode Base64 to Uint8Array + const messageHex = new TextDecoder().decode(base64.toByteArray(base64Message)); const messageBytes = Uint8Array.from(Buffer.from(messageHex, "hex")); - return new PemEntry(labels[index], messageBytes); + + return new PemEntry(label, messageBytes); }); } - private static groupLines(lines: string[]): { [key: string]: string[] } { - return lines.reduce( - (acc, line) => { - const isHeaderOrFooter = line.includes("-----"); - const key = isHeaderOrFooter ? "headers" : "messages"; + private static groupBlocks(lines: string[]): string[][] { + const blocks: string[][] = []; + let currentBlock: string[] = []; - if (!acc[key]) { - acc[key] = []; + for (const line of lines) { + if (line.startsWith("-----BEGIN PRIVATE KEY for")) { + if (currentBlock.length > 0) { + blocks.push(currentBlock); } - acc[key].push(line); + currentBlock = [line]; // Start a new block + } else if (line.startsWith("-----END PRIVATE KEY for")) { + currentBlock.push(line); + blocks.push(currentBlock); // Finalize the current block + currentBlock = []; + } else { + currentBlock.push(line); // Add content to the current block + } + } + + if (currentBlock.length > 0) { + throw new Error("Invalid PEM format: Missing END line for a block"); + } - return acc; - }, - { headers: [], messages: [] } as { [key: string]: string[] }, - ); + return blocks; } toText(): string { @@ -57,15 +78,11 @@ export class PemEntry { return lines.map((line) => line.trim()).filter((line) => line.length > 0); } - private static parseLabels(headers: string[]): string[] { - const marker = "-----BEGIN PRIVATE KEY for"; - return headers - .filter((line) => line.startsWith(marker)) - .map((line) => line.replace(marker, "").replace(/-/g, "").trim()); - } - private static wrapText(text: string, width: number): string[] { - const regex = new RegExp(`.{1,${width}}`, "g"); // Match chunks of up to `width` characters - return text.match(regex) || []; + const lines: string[] = []; + for (let i = 0; i < text.length; i += width) { + lines.push(text.slice(i, i + width)); + } + return lines; } } From f6929f1c6b655433e7ddf80aeb9b465710177ae9 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 28 Jan 2025 16:09:43 +0200 Subject: [PATCH 145/214] Add keypair tests --- src/wallet/keypair.spec.ts | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/wallet/keypair.spec.ts diff --git a/src/wallet/keypair.spec.ts b/src/wallet/keypair.spec.ts new file mode 100644 index 000000000..971423b83 --- /dev/null +++ b/src/wallet/keypair.spec.ts @@ -0,0 +1,54 @@ +import { assert } from "chai"; +import { Address, Transaction, TransactionComputer } from ".."; +import { KeyPair } from "./keypair"; +import { UserSecretKey } from "./userKeys"; + +describe("test keypair", () => { + it("should create keypair", () => { + const buffer_hex = "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9"; + const buffer = Uint8Array.from(Buffer.from(buffer_hex, "hex")); + const userSecretKey = UserSecretKey.fromString(buffer_hex); + let keypair = KeyPair.newFromBytes(buffer); + let secretKey = keypair.getSecretKey(); + assert.equal(secretKey.hex(), buffer_hex); + assert.equal(keypair.secretKey.hex(), buffer_hex); + assert.deepEqual(secretKey, userSecretKey); + + keypair = new KeyPair(secretKey); + assert.deepEqual(keypair.getSecretKey(), userSecretKey); + assert.deepEqual(keypair.getPublicKey(), userSecretKey.generatePublicKey()); + + keypair = KeyPair.generate(); + const pubkey = keypair.getPublicKey(); + secretKey = keypair.getSecretKey(); + assert.lengthOf(pubkey.valueOf(), 32); + assert.lengthOf(secretKey.valueOf(), 32); + }); + + it("should sign and verify transaction", () => { + const transaction = new Transaction({ + nonce: 89n, + value: 0n, + receiver: Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), + sender: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + gasPrice: 1000000000n, + gasLimit: 50000n, + chainID: "local-testnet", + version: 1, + options: 0, + }); + const bufferHex = "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9"; + const buffer = Uint8Array.from(Buffer.from(bufferHex, "hex")); + const keypair = KeyPair.newFromBytes(buffer); + + const transactionComputer = new TransactionComputer(); + const serializedTx = transactionComputer.computeBytesForSigning(transaction); + transaction.signature = keypair.sign(serializedTx); + assert.equal( + Buffer.from(transaction.signature).toString("hex"), + "b56769014f2bdc5cf9fc4a05356807d71fcf8775c819b0f1b0964625b679c918ffa64862313bfef86f99b38cb84fcdb16fa33ad6eb565276616723405cd8f109", + ); + assert.isTrue(keypair.verify(serializedTx, transaction.signature)); + assert.isTrue(keypair.verify(serializedTx, transaction.signature)); + }); +}); From 0bfabf3e202f6c18f0609e7f2971811768243c74 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 11:24:10 +0200 Subject: [PATCH 146/214] Code review follow up --- src/accounts/account.ts | 6 +- src/accounts/interfaces.ts | 2 +- src/entrypoints/entrypoints.spec.ts | 8 +- .../validatorKey00WithExtraLines.pem | 9 +++ src/wallet/keypair.spec.ts | 7 +- src/wallet/keypair.ts | 6 +- src/wallet/pemEntry.spec.ts | 74 +++++++++++++++++-- src/wallet/pemEntry.ts | 6 +- src/wallet/userKeys.ts | 6 +- src/wallet/userSigner.ts | 2 +- src/wallet/usersBenchmark.spec.ts | 4 +- 11 files changed, 97 insertions(+), 33 deletions(-) create mode 100644 src/testdata/testwallets/validatorKey00WithExtraLines.pem diff --git a/src/accounts/account.ts b/src/accounts/account.ts index a52258765..cfc108835 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -15,7 +15,7 @@ export class Account implements IAccount { /** * The address of the account. */ - readonly address: Address = Address.empty(); + readonly address: Address; /** * The nonce of the account (the account sequence number). @@ -33,7 +33,7 @@ export class Account implements IAccount { readonly publicKey: UserPublicKey; /** - * Creates an account object from an address + * Creates an account object from a secret key */ constructor(secretKey: UserSecretKey, hrp: string = LibraryConfig.DefaultAddressHrp) { this.secretKey = secretKey; @@ -92,7 +92,7 @@ export class Account implements IAccount { }; } - sign(data: Uint8Array): Uint8Array { + async sign(data: Uint8Array): Promise { return this.secretKey.sign(data); } diff --git a/src/accounts/interfaces.ts b/src/accounts/interfaces.ts index 72001424d..482b99900 100644 --- a/src/accounts/interfaces.ts +++ b/src/accounts/interfaces.ts @@ -3,5 +3,5 @@ import { Address } from "../address"; export interface IAccount { readonly address: Address; - sign(data: Uint8Array): Uint8Array; + sign(data: Uint8Array): Promise; } diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index d86816cc6..8abbc4fe5 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -4,16 +4,12 @@ import path from "path"; import { Account } from "../accounts/account"; import { Address } from "../address"; import { loadAbiRegistry } from "../testutils"; -import { TransactionComputer } from "../transactionComputer"; import { DevnetEntrypoint } from "./entrypoints"; describe("TestEntrypoint", () => { const entrypoint = new DevnetEntrypoint(); - let txComputer: TransactionComputer; - before(async function () { - txComputer = new TransactionComputer(); - }); + before(async function () {}); it("native transfer", async () => { const controller = entrypoint.createTransfersController(); @@ -102,7 +98,7 @@ describe("TestEntrypoint", () => { ); const innerTransactionGasLimit = transaction.gasLimit; transaction.gasLimit = BigInt(0); - transaction.signature = sender.sign(txComputer.computeBytesForSigning(transaction)); + transaction.signature = sender.signTransaction(transaction); const relayedController = entrypoint.createRelayedController(); const relayedTransaction = await relayedController.createRelayedV2Transaction( diff --git a/src/testdata/testwallets/validatorKey00WithExtraLines.pem b/src/testdata/testwallets/validatorKey00WithExtraLines.pem new file mode 100644 index 000000000..138f171e2 --- /dev/null +++ b/src/testdata/testwallets/validatorKey00WithExtraLines.pem @@ -0,0 +1,9 @@ +-----BEGIN PRIVATE KEY for e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208----- +N2NmZjk5YmQ2NzE1MDJkYjdkMTViYzhhYmMwYzlhODA0ZmI5MjU0MDZmYmRkNTBm + +MWU0YzE3YTRjZDc3NDI0Nw== + +-----END PRIVATE KEY for e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208----- + + + diff --git a/src/wallet/keypair.spec.ts b/src/wallet/keypair.spec.ts index 971423b83..b46d14e2d 100644 --- a/src/wallet/keypair.spec.ts +++ b/src/wallet/keypair.spec.ts @@ -25,7 +25,7 @@ describe("test keypair", () => { assert.lengthOf(secretKey.valueOf(), 32); }); - it("should sign and verify transaction", () => { + it("should sign and verify transaction", async () => { const transaction = new Transaction({ nonce: 89n, value: 0n, @@ -43,12 +43,11 @@ describe("test keypair", () => { const transactionComputer = new TransactionComputer(); const serializedTx = transactionComputer.computeBytesForSigning(transaction); - transaction.signature = keypair.sign(serializedTx); + transaction.signature = await keypair.sign(serializedTx); assert.equal( Buffer.from(transaction.signature).toString("hex"), "b56769014f2bdc5cf9fc4a05356807d71fcf8775c819b0f1b0964625b679c918ffa64862313bfef86f99b38cb84fcdb16fa33ad6eb565276616723405cd8f109", ); - assert.isTrue(keypair.verify(serializedTx, transaction.signature)); - assert.isTrue(keypair.verify(serializedTx, transaction.signature)); + assert.isTrue(await keypair.verify(serializedTx, transaction.signature)); }); }); diff --git a/src/wallet/keypair.ts b/src/wallet/keypair.ts index 61368a109..3d1d545f5 100644 --- a/src/wallet/keypair.ts +++ b/src/wallet/keypair.ts @@ -19,13 +19,11 @@ export class KeyPair { return new KeyPair(secretKey); } - sign(data: Uint8Array): Uint8Array { - // Signs the data using the secret key of the keypair + async sign(data: Uint8Array): Promise { return this.secretKey.sign(data); } - verify(data: Uint8Array, signature: Uint8Array): boolean { - // Verifies the data using the public key of the keypair + async verify(data: Uint8Array, signature: Uint8Array): Promise { return this.publicKey.verify(data, signature); } diff --git a/src/wallet/pemEntry.spec.ts b/src/wallet/pemEntry.spec.ts index 628472d8c..3ab50d5b1 100644 --- a/src/wallet/pemEntry.spec.ts +++ b/src/wallet/pemEntry.spec.ts @@ -7,7 +7,7 @@ import { USER_SEED_LENGTH } from "./userKeys"; describe("test pem entry", () => { const walletsPath = path.join("src", "testdata", "testwallets"); - it("should test from text all", () => { + it("should create from text all", () => { let text = readFileSync(path.join(walletsPath, "alice.pem"), "utf-8"); let entries = PemEntry.fromTextAll(text); let entry = entries[0]; @@ -45,16 +45,19 @@ describe("test pem entry", () => { ); }); - it("should test from text all for validatiors", () => { - let text = readFileSync(path.join(walletsPath, "alice.pem"), "utf-8"); + it("should create from text all for validators", () => { + let text = readFileSync(path.join(walletsPath, "validatorKey00.pem"), "utf-8"); let entries = PemEntry.fromTextAll(text); let entry = entries[0]; assert.lengthOf(entries, 1); - assert.equal(entry.label, "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + assert.equal( + entry.label, + "e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208", + ); assert.equal( Buffer.from(entry.message.slice(0, USER_SEED_LENGTH)).toString("hex"), - "413f42575f7f26fad3317a778771212fdb80245850981e48b58a4f25e344e8f9", + "7cff99bd671502db7d15bc8abc0c9a804fb925406fbdd50f1e4c17a4cd774247", ); text = readFileSync(path.join(walletsPath, "multipleValidatorKeys.pem"), "utf-8"); @@ -102,7 +105,66 @@ describe("test pem entry", () => { ); }); - it("should test to text", () => { + it("should create from text all for validators with extra lines in pem file", () => { + let text = readFileSync(path.join(walletsPath, "validatorKey00WithExtraLines.pem"), "utf-8"); + let entries = PemEntry.fromTextAll(text); + let entry = entries[0]; + + assert.lengthOf(entries, 1); + assert.equal( + entry.label, + "e7beaa95b3877f47348df4dd1cb578a4f7cabf7a20bfeefe5cdd263878ff132b765e04fef6f40c93512b666c47ed7719b8902f6c922c04247989b7137e837cc81a62e54712471c97a2ddab75aa9c2f58f813ed4c0fa722bde0ab718bff382208", + ); + assert.equal( + Buffer.from(entry.message.slice(0, USER_SEED_LENGTH)).toString("hex"), + "7cff99bd671502db7d15bc8abc0c9a804fb925406fbdd50f1e4c17a4cd774247", + ); + + text = readFileSync(path.join(walletsPath, "multipleValidatorKeys.pem"), "utf-8"); + entries = PemEntry.fromTextAll(text); + entry = entries[0]; + + assert.lengthOf(entries, 4); + assert.equal( + entry.label, + "f8910e47cf9464777c912e6390758bb39715fffcb861b184017920e4a807b42553f2f21e7f3914b81bcf58b66a72ab16d97013ae1cff807cefc977ef8cbf116258534b9e46d19528042d16ef8374404a89b184e0a4ee18c77c49e454d04eae8d", + ); + assert.equal( + Buffer.from(entry.message).toString("hex"), + "7c19bf3a0c57cdd1fb08e4607cebaa3647d6b9261b4693f61e96e54b218d442a", + ); + + entry = entries[1]; + assert.equal( + entry.label, + "1b4e60e6d100cdf234d3427494dac55fbac49856cadc86bcb13a01b9bb05a0d9143e86c186c948e7ae9e52427c9523102efe9019a2a9c06db02993f2e3e6756576ae5a3ec7c235d548bc79de1a6990e1120ae435cb48f7fc436c9f9098b92a0d", + ); + assert.equal( + Buffer.from(entry.message).toString("hex"), + "3034b1d58628a842984da0c70da0b5a251ebb2aebf51afc5b586e2839b5e5263", + ); + + entry = entries[2]; + assert.equal( + entry.label, + "e5dc552b4b170cdec4405ff8f9af20313bf0e2756d06c35877b6fbcfa6b354a7b3e2d439ea87999befb09a8fa1b3f014e57ec747bf738c4199338fcd4a87b373dd62f5c8329f1f5f245956bbb06685596a2e83dc38befa63e4a2b5c4ce408506", + ); + assert.equal( + Buffer.from(entry.message).toString("hex"), + "de7e1b385edbb0e1e8f9fc25d91bd8eed71a1da7caab732e6b47a48042d8523d", + ); + + entry = entries[3]; + assert.equal( + entry.label, + "12773304cb718250edd89770cedcbf675ccdb7fe2b30bd3185ca65ffa0d516879768ed03f92e41a6e5bc5340b78a9d02655e3b727c79730ead791fb68eaa02b84e1be92a816a9604a1ab9a6d3874b638487e2145239438a4bafac3889348d405", + ); + assert.equal( + Buffer.from(entry.message).toString("hex"), + "8ebeb07d296ad2529400b40687a741a135f8357f79f39fcb2894a6f9703a5816", + ); + }); + it("should convert to text", () => { let text = readFileSync(path.join(walletsPath, "alice.pem"), "utf-8").trim(); assert.deepEqual(PemEntry.fromTextAll(text)[0].toText(), text); diff --git a/src/wallet/pemEntry.ts b/src/wallet/pemEntry.ts index 4cdfca3f1..c8c14829e 100644 --- a/src/wallet/pemEntry.ts +++ b/src/wallet/pemEntry.ts @@ -1,5 +1,3 @@ -import * as base64 from "base64-js"; // For Base64 encoding and decoding - export class PemEntry { label: string; message: Uint8Array; @@ -29,7 +27,7 @@ export class PemEntry { const base64Message = block.slice(1, block.length - 1).join(""); // Decode Base64 to Uint8Array - const messageHex = new TextDecoder().decode(base64.toByteArray(base64Message)); + const messageHex = new TextDecoder().decode(Buffer.from(base64Message, "base64")); const messageBytes = Uint8Array.from(Buffer.from(messageHex, "hex")); return new PemEntry(label, messageBytes); @@ -67,7 +65,7 @@ export class PemEntry { const footer = `-----END PRIVATE KEY for ${this.label}-----`; const messageHex = Buffer.from(this.message).toString("hex"); - const messageBase64 = base64.fromByteArray(Buffer.from(messageHex, "utf-8")); + const messageBase64 = Buffer.from(messageHex, "utf-8").toString("base64"); const payloadLines = PemEntry.wrapText(messageBase64, 64); const payload = payloadLines.join("\n"); diff --git a/src/wallet/userKeys.ts b/src/wallet/userKeys.ts index 31bcb8133..8b0fe324d 100644 --- a/src/wallet/userKeys.ts +++ b/src/wallet/userKeys.ts @@ -38,8 +38,10 @@ export class UserSecretKey { } static generate(): UserSecretKey { - const keyPair = nacl.sign.keyPair(); // Generates a new signing keypair - const secretKey = keyPair.secretKey.subarray(0, 32); // Extract only the private key part + // Generates a new signing keypair + const keyPair = nacl.sign.keyPair(); + // Extract only the private key part + const secretKey = keyPair.secretKey.subarray(0, USER_SEED_LENGTH); return new UserSecretKey(secretKey); } diff --git a/src/wallet/userSigner.ts b/src/wallet/userSigner.ts index a74518ffd..dc6a872bd 100644 --- a/src/wallet/userSigner.ts +++ b/src/wallet/userSigner.ts @@ -23,7 +23,7 @@ export class UserSigner { return new UserSigner(secretKey); } - async sign(data: Buffer | Uint8Array): Promise { + async sign(data: Uint8Array): Promise { try { const signature = this.secretKey.sign(data); return signature; diff --git a/src/wallet/usersBenchmark.spec.ts b/src/wallet/usersBenchmark.spec.ts index 38459ed25..5eafc86f1 100644 --- a/src/wallet/usersBenchmark.spec.ts +++ b/src/wallet/usersBenchmark.spec.ts @@ -10,7 +10,7 @@ describe("behchmark sign and verify", () => { const secretKeys: UserSecretKey[] = []; const publicKeys: UserPublicKey[] = []; const messages: Buffer[] = []; - const goodSignatures: Buffer[] = []; + const goodSignatures: Uint8Array[] = []; for (let i = 0; i < n; i++) { const secretKey = new UserSecretKey(Buffer.from(utils.randomBytes(32))); @@ -28,7 +28,7 @@ describe("behchmark sign and verify", () => { for (let i = 0; i < n; i++) { const signature = secretKeys[i].sign(messages[i]); - goodSignatures.push(Buffer.from(signature)); + goodSignatures.push(signature); } console.timeEnd("sign"); From 8025400053dbf5612468f56406a96f92eba1be79 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 11:34:29 +0200 Subject: [PATCH 147/214] Remove testDecoder as is not needed --- src/wallet/pemEntry.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/wallet/pemEntry.ts b/src/wallet/pemEntry.ts index c8c14829e..ef2a5c9e2 100644 --- a/src/wallet/pemEntry.ts +++ b/src/wallet/pemEntry.ts @@ -27,8 +27,7 @@ export class PemEntry { const base64Message = block.slice(1, block.length - 1).join(""); // Decode Base64 to Uint8Array - const messageHex = new TextDecoder().decode(Buffer.from(base64Message, "base64")); - const messageBytes = Uint8Array.from(Buffer.from(messageHex, "hex")); + const messageBytes = Buffer.from(Buffer.from(base64Message, "base64").toString(), "hex"); return new PemEntry(label, messageBytes); }); From 5eeedd8608545da8b6c58cce742da53b95b90944 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 11:46:33 +0200 Subject: [PATCH 148/214] Remove testTransaction and TestMessage and update tests --- src/testutils/message.ts | 21 ------ src/testutils/transaction.ts | 43 ------------- src/wallet/users.spec.ts | 120 +++++++++++++++++------------------ 3 files changed, 60 insertions(+), 124 deletions(-) delete mode 100644 src/testutils/message.ts delete mode 100644 src/testutils/transaction.ts diff --git a/src/testutils/message.ts b/src/testutils/message.ts deleted file mode 100644 index c115d20dc..000000000 --- a/src/testutils/message.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * A dummy message used in tests. - */ -export class TestMessage { - foo: string = ""; - bar: string = ""; - - constructor(init?: Partial) { - Object.assign(this, init); - } - - serializeForSigning(): Buffer { - let plainObject = { - foo: this.foo, - bar: this.bar - }; - - let serialized = JSON.stringify(plainObject); - return Buffer.from(serialized); - } -} diff --git a/src/testutils/transaction.ts b/src/testutils/transaction.ts deleted file mode 100644 index 318b9a8b6..000000000 --- a/src/testutils/transaction.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * A dummy transaction used in tests. - */ -export class TestTransaction { - nonce: number = 0; - value: string = ""; - receiver: string = ""; - sender: string = ""; - guardian: string = ""; - gasPrice: number = 0; - gasLimit: number = 0; - data: string = ""; - chainID: string = ""; - version: number = 1; - options: number = 0; - - constructor(init?: Partial) { - Object.assign(this, init); - } - - serializeForSigning(): Buffer { - const dataEncoded = this.data ? Buffer.from(this.data).toString("base64") : undefined; - const guardian = this.guardian ? this.guardian : undefined; - const options = this.options ? this.options : undefined; - - const plainObject = { - nonce: this.nonce, - value: this.value, - receiver: this.receiver, - sender: this.sender, - guardian: guardian, - gasPrice: this.gasPrice, - gasLimit: this.gasLimit, - data: dataEncoded, - chainID: this.chainID, - options: options, - version: this.version - }; - - const serialized = JSON.stringify(plainObject); - return Buffer.from(serialized); - } -} diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index 0cc2408f0..2e329f905 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -1,8 +1,7 @@ import { assert } from "chai"; import path from "path"; +import { Address, Message, Transaction } from ".."; import { ErrBadMnemonicEntropy, ErrInvariantFailed } from "../errors"; -import { TestMessage } from "./../testutils/message"; -import { TestTransaction } from "./../testutils/transaction"; import { DummyMnemonicOf12Words, loadMnemonic, @@ -302,13 +301,14 @@ describe("test user wallets", () => { ); // With data field - let transaction = new TestTransaction({ - nonce: 0, - value: "0", - receiver: "erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r", - gasPrice: 1000000000, - gasLimit: 50000, - data: "foo", + let transaction = new Transaction({ + nonce: 0n, + value: 0n, + sender: Address.newFromBech32("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz"), + receiver: Address.newFromBech32("erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r"), + gasPrice: 1000000000n, + gasLimit: 50000n, + data: new TextEncoder().encode("foo"), chainID: "1", }); @@ -316,23 +316,24 @@ describe("test user wallets", () => { let signature = await signer.sign(serialized); assert.deepEqual(await signer.sign(serialized), await signer.sign(Uint8Array.from(serialized))); - assert.equal( + assert.deepEqual( serialized.toString(), - `{"nonce":0,"value":"0","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"","gasPrice":1000000000,"gasLimit":50000,"data":"Zm9v","chainID":"1","version":1}`, + `{"nonce":0,"value":"0","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz","gasPrice":1000000000,"gasLimit":50000,"data":"Zm9v","chainID":"1","version":2}`, ); assert.equal( Buffer.from(signature).toString("hex"), - "a3b61a2fe461f3393c42e6cb0477a6b52ffd92168f10c111f6aa8d0a310ee0c314fae0670f8313f1ad992933ac637c61a8ff20cc20b6a8b2260a4af1a120a70d", + "a5db62c6186612d44094f83576aa6a664299315fb6e42d0c17a40e9cd33efa9a9df8b76943aeac7dceaff3d78a16a7414c914f03f7a88e786c2cf939eb111c06", ); assert.isTrue(verifier.verify(serialized, signature)); // Without data field - transaction = new TestTransaction({ - nonce: 8, - value: "10000000000000000000", - receiver: "erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r", - gasPrice: 1000000000, - gasLimit: 50000, + transaction = new Transaction({ + nonce: 8n, + value: 10000000000000000000n, + sender: Address.newFromBech32("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz"), + receiver: Address.newFromBech32("erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r"), + gasPrice: 1000000000n, + gasLimit: 50000n, chainID: "1", }); @@ -342,11 +343,11 @@ describe("test user wallets", () => { assert.deepEqual(await signer.sign(serialized), await signer.sign(Uint8Array.from(serialized))); assert.equal( serialized.toString(), - `{"nonce":8,"value":"10000000000000000000","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"","gasPrice":1000000000,"gasLimit":50000,"chainID":"1","version":1}`, + `{"nonce":8,"value":"10000000000000000000","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz","gasPrice":1000000000,"gasLimit":50000,"chainID":"1","version":2}`, ); assert.equal( Buffer.from(signature).toString("hex"), - "f136c901d37349a7da8cfe3ab5ec8ef333b0bc351517c0e9bef9eb9704aed3077bf222769cade5ff29dffe5f42e4f0c5e0b068bdba90cd2cb41da51fd45d5a03", + "024f007f7eae87141b34708e33afd66c85a49ea8c8422e55292832ee870f879cdc033d2511c174d0f2ed62799b9f597c4a8399309578a258f558131d74374f0d", ); }); @@ -363,16 +364,16 @@ describe("test user wallets", () => { let guardianSigner = new UserSigner(UserSecretKey.fromPem(bob.pemFileText)); // With data field - let transaction = new TestTransaction({ - nonce: 0, - value: "0", - receiver: "erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r", - sender: "erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz", - gasPrice: 1000000000, - gasLimit: 50000, - data: "foo", + let transaction = new Transaction({ + nonce: 0n, + value: 0n, + receiver: Address.newFromBech32("erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r"), + sender: Address.newFromBech32("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz"), + gasPrice: 1000000000n, + gasLimit: 50000n, + data: new TextEncoder().encode("foo"), chainID: "1", - guardian: "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", + guardian: Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), options: 2, version: 2, }); @@ -381,30 +382,30 @@ describe("test user wallets", () => { let signature = await signer.sign(serialized); let guardianSignature = await guardianSigner.sign(serialized); - assert.equal( + assert.deepEqual( serialized.toString(), - `{"nonce":0,"value":"0","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz","guardian":"erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx","gasPrice":1000000000,"gasLimit":50000,"data":"Zm9v","chainID":"1","options":2,"version":2}`, + `{"nonce":0,"value":"0","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz","gasPrice":1000000000,"gasLimit":50000,"data":"Zm9v","chainID":"1","version":2,"options":2,"guardian":"erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"}`, ); assert.equal( Buffer.from(signature).toString("hex"), - "00b867ae749616954711ef227c0a3f5c6556246f26dbde12ad929a099094065341a0fae7c5ced98e6bdd100ce922c975667444ea859dce9597b46e63cade2a03", + "fa067dc9508ec9df04896665fc9c9e3e7e9cbdc6577c10d56128e3c891ea502572be637bd7cdfb466779cee3e208a2be1f32b0267af1710a6532848e5e5e6f0d", ); assert.equal( Buffer.from(guardianSignature).toString("hex"), - "1326e44941ef7bfbad3edf346e72abe23704ee32b4b6a6a6a9b793bd7c62b6d4a69d3c6ea2dddf7eabc8df8fe291cd24822409ab9194b6a0f3bbbf1c59b0a10f", + "5695fde5d9c77a94bb320438fbebe3bbd60b7cc4d633fb38e42bb65f83d253cbb82cc5ae40d701a7f0b839a5231320ca356018ced949885baae473e469ec770e", ); assert.isTrue(verifier.verify(serialized, signature)); // Without data field - transaction = new TestTransaction({ - nonce: 8, - value: "10000000000000000000", - receiver: "erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r", - sender: "erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz", - gasPrice: 1000000000, - gasLimit: 50000, + transaction = new Transaction({ + nonce: 8n, + value: 10000000000000000000n, + receiver: Address.newFromBech32("erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r"), + sender: Address.newFromBech32("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz"), + gasPrice: 1000000000n, + gasLimit: 50000n, chainID: "1", - guardian: "erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx", + guardian: Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), options: 2, version: 2, }); @@ -415,15 +416,15 @@ describe("test user wallets", () => { assert.equal( serialized.toString(), - `{"nonce":8,"value":"10000000000000000000","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz","guardian":"erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx","gasPrice":1000000000,"gasLimit":50000,"chainID":"1","options":2,"version":2}`, + `{"nonce":8,"value":"10000000000000000000","receiver":"erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r","sender":"erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz","gasPrice":1000000000,"gasLimit":50000,"chainID":"1","version":2,"options":2,"guardian":"erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"}`, ); assert.equal( Buffer.from(signature).toString("hex"), - "49a63fa0e3cfb81a2b6d926c741328fb270ea4f58fa32585fe8aa3cde191245e5a13c5c059d5576f4c05fc24d2534a2124ff79c98d067ce8412c806779066b03", + "50d61a408cf032b3e70b15ecc313dbea43e35a1b33ea89aadb42b25a672d3427147bcda0d911be539629fcd3183c22b30f8ac30023abb230b13abf2cd1befd04", ); assert.equal( Buffer.from(guardianSignature).toString("hex"), - "4c25a54381bf66576d05f32659d30672b5b0bfbfb6b6aee52290d28cfbc87860637f095f83663a1893d12d0d5a27b2ab3325829ff1f1215b81a7ced8ee5d7203", + "ea3b83adcc468b0c7d3613fca5f429a9764d5710137c34c27e15d06e625326724ccfa758968507acadb14345d19389ba6004a4f0a6c527799c01713e10cf650b", ); assert.isTrue(verifier.verify(serialized, signature)); }); @@ -431,13 +432,14 @@ describe("test user wallets", () => { it("should sign transactions using PEM files", async () => { const signer = UserSigner.fromPem(alice.pemFileText); - const transaction = new TestTransaction({ - nonce: 0, - value: "0", - receiver: "erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r", - gasPrice: 1000000000, - gasLimit: 50000, - data: "foo", + const transaction = new Transaction({ + nonce: 0n, + value: 0n, + sender: signer.getAddress(), + receiver: Address.newFromBech32("erd1cux02zersde0l7hhklzhywcxk4u9n4py5tdxyx7vrvhnza2r4gmq4vw35r"), + gasPrice: 1000000000n, + gasLimit: 50000n, + data: new TextEncoder().encode("foo"), chainID: "1", }); @@ -447,7 +449,7 @@ describe("test user wallets", () => { assert.deepEqual(await signer.sign(serialized), await signer.sign(Uint8Array.from(serialized))); assert.equal( Buffer.from(signature).toString("hex"), - "ba4fa95fea1402e4876abf1d5a510615aab374ee48bb76f5230798a7d3f2fcae6ba91ba56c6d62e6e7003ce531ff02f219cb7218dd00dd2ca650ba747f19640a", + "b6feb8b50711cc8436040de561355e94585b2cf9e33e9e887125ad9c6877829dbc75afaf878c690e249455b738e89f63067930bc8c46fcf0779ac0bd3590a206", ); }); @@ -461,17 +463,15 @@ describe("test user wallets", () => { ).generatePublicKey(), ); - const message = new TestMessage({ - foo: "hello", - bar: "world", + const message = new Message({ + data: new TextEncoder().encode(JSON.stringify({ foo: "hello", bar: "world" })), }); - const data = message.serializeForSigning(); - const signature = await signer.sign(data); + const signature = await signer.sign(message.data); - assert.deepEqual(await signer.sign(data), await signer.sign(Uint8Array.from(data))); - assert.isTrue(verifier.verify(data, signature)); - assert.isTrue(verifier.verify(Uint8Array.from(data), Uint8Array.from(signature))); + assert.deepEqual(await signer.sign(message.data), await signer.sign(Uint8Array.from(message.data))); + assert.isTrue(verifier.verify(message.data, signature)); + assert.isTrue(verifier.verify(Uint8Array.from(message.data), Uint8Array.from(signature))); assert.isFalse(verifier.verify(Buffer.from("hello"), signature)); assert.isFalse(verifier.verify(new TextEncoder().encode("hello"), signature)); }); From efc0fd9dd0be059a845bcf68f24f48e4f9409c02 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 12:25:02 +0200 Subject: [PATCH 149/214] Remove dummy query --- src/testutils/dummyQuery.ts | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 src/testutils/dummyQuery.ts diff --git a/src/testutils/dummyQuery.ts b/src/testutils/dummyQuery.ts deleted file mode 100644 index 5be41fe69..000000000 --- a/src/testutils/dummyQuery.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Address } from "../address"; -import { IContractQuery } from "../networkProviders/interface"; - -export class MockQuery implements IContractQuery { - caller = Address.empty(); - address = Address.empty(); - func: string = ""; - args: string[] = []; - value: string = ""; - - constructor(init?: Partial) { - Object.assign(this, init); - } - - getEncodedArguments(): string[] { - return this.args; - } -} From 5f45564f0e7e5433f97a28ac514ef22c0da930ab Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 13:09:42 +0200 Subject: [PATCH 150/214] Remove TransactionHash and hash and update to use TransactionComputer.computeTransactionHash --- src/abi/interaction.spec.ts | 14 ++++---- src/abi/smartContract.spec.ts | 13 +++++--- src/hash.ts | 48 ---------------------------- src/testutils/mockNetworkProvider.ts | 21 ++++++------ src/transaction.spec.ts | 33 +++++++------------ src/transaction.ts | 28 ---------------- src/transactionComputer.ts | 4 +-- src/transactionWatcher.spec.ts | 19 ++++------- 8 files changed, 47 insertions(+), 133 deletions(-) delete mode 100644 src/hash.ts diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index c24450dc0..aa7dfdbe6 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -12,6 +12,7 @@ import { } from "../testutils"; import { Token, TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; @@ -251,20 +252,17 @@ describe("test smart contract interactor", function () { await provider.sendTransaction(transaction); assert.equal(transaction.getNonce().valueOf(), 0n); assert.equal(transaction.getData().toString(), "getUltimateAnswer"); - assert.equal( - transaction.getHash().toString(), - "3579ad09099feb9755c860ddd225251170806d833342e912fccdfe2ed5c3a364", - ); + const computer = new TransactionComputer(); + let hashString = computer.computeTransactionHash(transaction); + assert.equal(hashString, "3579ad09099feb9755c860ddd225251170806d833342e912fccdfe2ed5c3a364"); transaction = interaction.withNonce(1n).buildTransaction(); transaction.setSender(alice.address); transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); await provider.sendTransaction(transaction); assert.equal(transaction.getNonce(), 1n); - assert.equal( - transaction.getHash().toString(), - "ad513ce7c5d371d30e48f073326899766736eac1ac231d847d45bc3facbcb496", - ); + hashString = computer.computeTransactionHash(transaction); + assert.equal(hashString, "ad513ce7c5d371d30e48f073326899766736eac1ac231d847d45bc3facbcb496"); // Execute, and wait for execution transaction = interaction.withNonce(2n).buildTransaction(); diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index 7658b7c50..54a4ccff2 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -8,6 +8,7 @@ import { TestWallet, Wait, } from "../testutils"; +import { TransactionComputer } from "../transactionComputer"; import { TransactionStatus } from "../transactionStatus"; import { TransactionWatcher } from "../transactionWatcher"; import { Code } from "./code"; @@ -73,6 +74,8 @@ describe("test contract", () => { // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); + const computer = new TransactionComputer(); + const hashString = computer.computeTransactionHash(deployTransaction); await Promise.all([ provider.mockTransactionTimeline(deployTransaction, [ @@ -82,7 +85,7 @@ describe("test contract", () => { new TransactionStatus("executed"), new MarkCompleted(), ]), - watcher.awaitCompleted(deployTransaction.getHash().hex()), + watcher.awaitCompleted(hashString), ]); assert.isTrue((await provider.getTransaction(hash)).status.isCompleted()); @@ -150,8 +153,8 @@ describe("test contract", () => { new TransactionStatus("executed"), new MarkCompleted(), ]), - watcher.awaitCompleted(callTransactionOne.getHash().hex()), - watcher.awaitCompleted(callTransactionTwo.getHash().hex()), + watcher.awaitCompleted(hashOne), + watcher.awaitCompleted(hashTwo), ]); assert.isTrue((await provider.getTransaction(hashOne)).status.isCompleted()); @@ -188,6 +191,8 @@ describe("test contract", () => { // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); + const computer = new TransactionComputer(); + const hashString = computer.computeTransactionHash(deployTransaction); await Promise.all([ provider.mockTransactionTimeline(deployTransaction, [ @@ -197,7 +202,7 @@ describe("test contract", () => { new TransactionStatus("executed"), new MarkCompleted(), ]), - watcher.awaitCompleted(deployTransaction.getHash().hex()), + watcher.awaitCompleted(hashString), ]); assert.isTrue((await provider.getTransaction(hash)).status.isCompleted()); diff --git a/src/hash.ts b/src/hash.ts deleted file mode 100644 index 40efda328..000000000 --- a/src/hash.ts +++ /dev/null @@ -1,48 +0,0 @@ -import * as errors from "./errors"; - -export class Hash { - /** - * The hash, as a hex-encoded string. - */ - readonly hash: Buffer; - - /** - * Creates a new Hash object. - * - * @param hash The hash, as a Buffer or a hex-encoded string. - */ - constructor(hash: Buffer | string) { - if (!hash) { - this.hash = Buffer.from([]); - } else if (hash instanceof Buffer) { - this.hash = hash; - } else if (typeof hash === "string") { - this.hash = Buffer.from(hash, "hex"); - } else { - throw new errors.ErrBadType("hash", "buffer | string", hash); - } - } - - static empty(): Hash { - return new Hash(Buffer.from([])); - } - - /** - * Returns whether the hash is empty (not computed). - */ - isEmpty(): boolean { - return this.hash.length == 0; - } - - toString(): string { - return this.hex(); - } - - hex(): string { - return this.hash.toString("hex"); - } - - valueOf(): Buffer { - return this.hash; - } -} diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index badc181ab..5dfd1333b 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -21,7 +21,8 @@ import { } from "../networkProviders/resources"; import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; import { Token } from "../tokens"; -import { Transaction, TransactionHash } from "../transaction"; +import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { TransactionStatus } from "../transactionStatus"; @@ -129,16 +130,16 @@ export class MockNetworkProvider implements INetworkProvider { } } - mockUpdateTransaction(hash: TransactionHash, mutate: (item: TransactionOnNetwork) => void) { - let transaction = this.transactions.get(hash.toString()); + mockUpdateTransaction(hash: string, mutate: (item: TransactionOnNetwork) => void) { + let transaction = this.transactions.get(hash); if (transaction) { mutate(transaction); } } - mockPutTransaction(hash: TransactionHash, item: TransactionOnNetwork) { + mockPutTransaction(hash: string, item: TransactionOnNetwork) { item.status = TransactionStatus.createUnknown(); - this.transactions.set(hash.toString(), item); + this.transactions.set(hash, item); } mockQueryContractOnFunction(functionName: string, response: SmartContractQueryResponse) { @@ -181,14 +182,15 @@ export class MockNetworkProvider implements INetworkProvider { } async mockTransactionTimeline(transaction: Transaction, timelinePoints: any[]): Promise { - return this.mockTransactionTimelineByHash(transaction.getHash(), timelinePoints); + const computer = new TransactionComputer(); + return this.mockTransactionTimelineByHash(computer.computeTransactionHash(transaction), timelinePoints); } async mockNextTransactionTimeline(timelinePoints: any[]): Promise { this.nextTransactionTimelinePoints = timelinePoints; } - async mockTransactionTimelineByHash(hash: TransactionHash, timelinePoints: any[]): Promise { + async mockTransactionTimelineByHash(hash: string, timelinePoints: any[]): Promise { let timeline = new AsyncTimer(`mock timeline of ${hash}`); await timeline.start(0); @@ -222,8 +224,9 @@ export class MockNetworkProvider implements INetworkProvider { } async sendTransaction(transaction: Transaction): Promise { + const computer = new TransactionComputer(); this.mockPutTransaction( - transaction.getHash(), + computer.computeTransactionHash(transaction), new TransactionOnNetwork({ sender: transaction.getSender(), receiver: transaction.getReceiver(), @@ -233,7 +236,7 @@ export class MockNetworkProvider implements INetworkProvider { ); this.mockTransactionTimeline(transaction, this.nextTransactionTimelinePoints); - return transaction.getHash().hex(); + return computer.computeTransactionHash(transaction); } async simulateTransaction(_transaction: Transaction): Promise { diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index 745ed11ac..6640aef79 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -85,7 +85,7 @@ describe("test transaction", async () => { "3f08a1dd64fbb627d10b048e0b45b1390f29bb0e457762a2ccb710b029f299022a67a4b8e45cf62f4314afec2e56b5574c71e38df96cc41fae757b7ee5062503", ); assert.equal( - transaction.getHash().toString(), + transactionComputer.computeTransactionHash(transaction), "1359fb9d5b0b47ca9f3b4adce6e4a524fa74099dd4732743b9226774a4cb0ad8", ); }); @@ -109,7 +109,7 @@ describe("test transaction", async () => { "f9e8c1caf7f36b99e7e76ee1118bf71b55cde11a2356e2b3adf15f4ad711d2e1982469cbba7eb0afbf74e8a8f78e549b9410cd86eeaa88fcba62611ac9f6e30e", ); assert.equal( - transaction.getHash().toString(), + transactionComputer.computeTransactionHash(transaction), "10a2bd6f9c358d2c9645368081999efd2a4cc7f24bdfdd75e8f57485fd702001", ); }); @@ -156,10 +156,7 @@ describe("test transaction", async () => { const hash = transactionComputer.computeTransactionHash(transaction); - assert.equal( - Buffer.from(hash).toString("hex"), - "169b76b752b220a76a93aeebc462a1192db1dc2ec9d17e6b4d7b0dcc91792f03", - ); + assert.equal(hash, "169b76b752b220a76a93aeebc462a1192db1dc2ec9d17e6b4d7b0dcc91792f03"); }); it("should compute hash (with usernames)", async () => { @@ -183,10 +180,7 @@ describe("test transaction", async () => { const hash = transactionComputer.computeTransactionHash(transaction); - assert.equal( - Buffer.from(hash).toString("hex"), - "41b5acf7ebaf4a9165a64206b6ebc02021b3adda55ffb2a2698aac2e7004dc29", - ); + assert.equal(hash, "41b5acf7ebaf4a9165a64206b6ebc02021b3adda55ffb2a2698aac2e7004dc29"); }); it("should sign & compute hash (with data, with opaque, unused options) (legacy)", async () => { @@ -227,7 +221,7 @@ describe("test transaction", async () => { "b45f22e9f57a6df22670fcc3566723a0711a05ac2547456de59fd222a54940e4a1d99bd414897ccbf5c02a842ad86e638989b7f4d30edd26c99a8cd1eb092304", ); assert.equal( - transaction.getHash().toString(), + transactionComputer.computeTransactionHash(transaction).toString(), "84125d7154d81a723642100bdf74e6df99f7c069c016d1e6bbeb408fd4e961bf", ); }); @@ -251,7 +245,7 @@ describe("test transaction", async () => { "01f05aa8cb0614e12a94ab9dcbde5e78370a4e05d23ef25a1fb9d5fcf1cb3b1f33b919cd8dafb1704efb18fa233a8aa0d3344fb6ee9b613a7d7a403786ffbd0a", ); assert.equal( - transaction.getHash().toString(), + transactionComputer.computeTransactionHash(transaction), "321e1f1a0e3d06edade34fd0fdf3b4859e4328a73706a442c2439968a074113c", ); }); @@ -276,7 +270,7 @@ describe("test transaction", async () => { "dfa3e9f2fdec60dcb353bac3b3435b4a2ff251e7e98eaf8620f46c731fc70c8ba5615fd4e208b05e75fe0f7dc44b7a99567e29f94fcd91efac7e67b182cd2a04", ); assert.equal( - transaction.getHash().toString(), + transactionComputer.computeTransactionHash(transaction), "6ffa1a75f98aaf336bfb87ef13b9b5a477a017158285d34ee2a503668767e69e", ); }); @@ -299,7 +293,7 @@ describe("test transaction", async () => { "3f08a1dd64fbb627d10b048e0b45b1390f29bb0e457762a2ccb710b029f299022a67a4b8e45cf62f4314afec2e56b5574c71e38df96cc41fae757b7ee5062503", ); assert.equal( - transaction.getHash().toString(), + transactionComputer.computeTransactionHash(transaction), "1359fb9d5b0b47ca9f3b4adce6e4a524fa74099dd4732743b9226774a4cb0ad8", ); @@ -325,7 +319,7 @@ describe("test transaction", async () => { "3f08a1dd64fbb627d10b048e0b45b1390f29bb0e457762a2ccb710b029f299022a67a4b8e45cf62f4314afec2e56b5574c71e38df96cc41fae757b7ee5062503", ); assert.equal( - transaction.getHash().toString(), + transactionComputer.computeTransactionHash(transaction), "1359fb9d5b0b47ca9f3b4adce6e4a524fa74099dd4732743b9226774a4cb0ad8", ); @@ -352,7 +346,7 @@ describe("test transaction", async () => { "51e6cd78fb3ab4b53ff7ad6864df27cb4a56d70603332869d47a5cf6ea977c30e696103e41e8dddf2582996ad335229fdf4acb726564dbc1a0bc9e705b511f06", ); assert.equal( - transaction.getHash().toString(), + transactionComputer.computeTransactionHash(transaction), "edc84d776bfd655ddbd6fce24a83e379496ac47890d00be9c8bb2c6666fa3fd8", ); }); @@ -371,7 +365,7 @@ describe("test transaction", async () => { options: 2, nonce: 92n, value: 123456789000000000000000000000n, - guardian: Address.fromBech32("erd1x23lzn8483xs2su4fak0r0dqx6w38enpmmqf2yrkylwq7mfnvyhsxqw57y"), + guardian: Address.newFromBech32("erd1x23lzn8483xs2su4fak0r0dqx6w38enpmmqf2yrkylwq7mfnvyhsxqw57y"), }); transaction.guardianSignature = new Uint8Array(64); transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); @@ -385,10 +379,7 @@ describe("test transaction", async () => { ); const txHash = transactionComputer.computeTransactionHash(transaction); - assert.equal( - Buffer.from(txHash).toString("hex"), - "242022e9dcfa0ee1d8199b0043314dbda8601619f70069ebc441b9f03349a35c", - ); + assert.equal(txHash, "242022e9dcfa0ee1d8199b0043314dbda8601619f70069ebc441b9f03349a35c"); }); it("computes fee (legacy)", () => { diff --git a/src/transaction.ts b/src/transaction.ts index 53ca342fe..110ca9816 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,7 +1,6 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; -import { Hash } from "./hash"; import { IPlainTransactionObject } from "./interface"; import { INetworkConfig } from "./interfaceOfNetwork"; import { interpretSignatureAsBuffer } from "./signature"; @@ -324,13 +323,6 @@ export class Transaction { this.guardian = guardian; } - /** - * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. - */ - getHash(): TransactionHash { - return TransactionHash.compute(this); - } - /** * Legacy method, use "TransactionComputer.computeBytesForSigning()" instead. * Serializes a transaction to a sequence of bytes, ready to be signed. @@ -467,23 +459,3 @@ export class Transaction { return value && value.length ? Buffer.from(value).toString("hex") : undefined; } } - -/** - * Legacy class, use "TransactionComputer.computeTransactionHash()" instead. - * An abstraction for handling and computing transaction hashes. - */ -export class TransactionHash extends Hash { - constructor(hash: string) { - super(hash); - } - - /** - * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. - * Computes the hash of a transaction. - */ - static compute(transaction: Transaction): TransactionHash { - const computer = new TransactionComputer(); - const hash = computer.computeTransactionHash(transaction); - return new TransactionHash(Buffer.from(hash).toString("hex")); - } -} diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index dfc827541..4384c621b 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -69,12 +69,12 @@ export class TransactionComputer { return createKeccakHash("keccak256").update(signable).digest(); } - computeTransactionHash(transaction: Transaction): Uint8Array { + computeTransactionHash(transaction: Transaction): string { const serializer = new ProtoSerializer(); const buffer = serializer.serializeTransaction(transaction); const hash = createTransactionHasher(TRANSACTION_HASH_LENGTH).update(buffer).digest("hex"); - return Buffer.from(hash, "hex"); + return Buffer.from(hash, "hex").toString("hex"); } hasOptionsSetForGuardedTransaction(transaction: Transaction): boolean { diff --git a/src/transactionWatcher.spec.ts b/src/transactionWatcher.spec.ts index 2629ced71..c9189ceec 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/transactionWatcher.spec.ts @@ -1,21 +1,17 @@ import { assert } from "chai"; import { MarkCompleted, MockNetworkProvider, Wait } from "./testutils"; -import { TransactionHash } from "./transaction"; import { TransactionOnNetwork } from "./transactionOnNetwork"; import { TransactionStatus } from "./transactionStatus"; import { TransactionWatcher } from "./transactionWatcher"; describe("test transactionWatcher", () => { it("should await status == executed using hash", async () => { - let hash = new TransactionHash("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba"); + let hash = "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba"; let provider = new MockNetworkProvider(); let watcher = new TransactionWatcher(provider, { pollingIntervalMilliseconds: 42, timeoutMilliseconds: 42 * 42, }); - let dummyTransaction = { - getHash: () => hash, - }; provider.mockPutTransaction( hash, @@ -32,22 +28,19 @@ describe("test transactionWatcher", () => { new TransactionStatus("executed"), new MarkCompleted(), ]), - watcher.awaitCompleted(dummyTransaction.getHash().hex()), + watcher.awaitCompleted(hash), ]); - assert.isTrue((await provider.getTransactionStatus(hash.hex())).isCompleted()); + assert.isTrue((await provider.getTransactionStatus(hash)).isCompleted()); }); it("should await status == executed using transaction", async () => { - let hash = new TransactionHash("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba"); + let hash = "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba"; let provider = new MockNetworkProvider(); let watcher = new TransactionWatcher(provider, { pollingIntervalMilliseconds: 42, timeoutMilliseconds: 42 * 42, }); - let dummyTransaction = { - getHash: () => hash, - }; provider.mockPutTransaction( hash, @@ -64,9 +57,9 @@ describe("test transactionWatcher", () => { new TransactionStatus("executed"), new MarkCompleted(), ]), - watcher.awaitCompleted(dummyTransaction), + watcher.awaitCompleted(hash), ]); - assert.isTrue((await provider.getTransactionStatus(hash.hex())).isCompleted()); + assert.isTrue((await provider.getTransactionStatus(hash)).isCompleted()); }); }); From 2af7f14cdb9b7fcfc8b3bafe88e40b7d151aac6a Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 13:25:20 +0200 Subject: [PATCH 151/214] Fix tests --- src/abi/interaction.spec.ts | 14 +++++--------- src/abi/smartContract.spec.ts | 4 +--- src/transaction.local.net.spec.ts | 12 ++++++------ 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index aa7dfdbe6..af32410b1 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -12,7 +12,6 @@ import { } from "../testutils"; import { Token, TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; @@ -249,27 +248,24 @@ describe("test smart contract interactor", function () { let transaction = interaction.withSender(alice.address).withNonce(0n).buildTransaction(); transaction.setSender(alice.address); transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); - await provider.sendTransaction(transaction); + let hash = await provider.sendTransaction(transaction); assert.equal(transaction.getNonce().valueOf(), 0n); assert.equal(transaction.getData().toString(), "getUltimateAnswer"); - const computer = new TransactionComputer(); - let hashString = computer.computeTransactionHash(transaction); - assert.equal(hashString, "3579ad09099feb9755c860ddd225251170806d833342e912fccdfe2ed5c3a364"); + assert.equal(hash, "3579ad09099feb9755c860ddd225251170806d833342e912fccdfe2ed5c3a364"); transaction = interaction.withNonce(1n).buildTransaction(); transaction.setSender(alice.address); transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); - await provider.sendTransaction(transaction); + hash = await provider.sendTransaction(transaction); assert.equal(transaction.getNonce(), 1n); - hashString = computer.computeTransactionHash(transaction); - assert.equal(hashString, "ad513ce7c5d371d30e48f073326899766736eac1ac231d847d45bc3facbcb496"); + assert.equal(hash, "ad513ce7c5d371d30e48f073326899766736eac1ac231d847d45bc3facbcb496"); // Execute, and wait for execution transaction = interaction.withNonce(2n).buildTransaction(); transaction.setSender(alice.address); transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs", "getUltimateAnswer"); - let hash = await provider.sendTransaction(transaction); + hash = await provider.sendTransaction(transaction); let responseExecute = await controller.awaitCompletedExecute(hash); assert.isTrue(responseExecute.values.length == 1); diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index 54a4ccff2..d197518ef 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -191,8 +191,6 @@ describe("test contract", () => { // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); - const computer = new TransactionComputer(); - const hashString = computer.computeTransactionHash(deployTransaction); await Promise.all([ provider.mockTransactionTimeline(deployTransaction, [ @@ -202,7 +200,7 @@ describe("test contract", () => { new TransactionStatus("executed"), new MarkCompleted(), ]), - watcher.awaitCompleted(hashString), + watcher.awaitCompleted(hash), ]); assert.isTrue((await provider.getTransaction(hash)).status.isCompleted()); diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 702f9d7a7..8e77a9878 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -63,11 +63,11 @@ describe("test transaction", function () { await signTransaction({ transaction: transactionOne, wallet: alice }); await signTransaction({ transaction: transactionTwo, wallet: alice }); - await provider.sendTransaction(transactionOne); - await provider.sendTransaction(transactionTwo); + const hashOne = await provider.sendTransaction(transactionOne); + const hashTwo = await provider.sendTransaction(transactionTwo); - await watcher.awaitCompleted(transactionOne.getHash().hex()); - await watcher.awaitCompleted(transactionTwo.getHash().hex()); + await watcher.awaitCompleted(hashOne); + await watcher.awaitCompleted(hashTwo); await bob.sync(provider); let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); @@ -100,8 +100,8 @@ describe("test transaction", function () { transactionOne.setNonce(alice.account.nonce); await signTransaction({ transaction: transactionOne, wallet: alice }); - await provider.sendTransaction(transactionOne); - await watcher.awaitCompleted(transactionOne.getHash().hex()); + const hashOne = await provider.sendTransaction(transactionOne); + await watcher.awaitCompleted(hashOne); await bob.sync(provider); let newBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); From 5fc14af81f31212cbd8be12e9be118b61b3d5e3a Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 13:52:33 +0200 Subject: [PATCH 152/214] Mark all legacy method as deprecated and update code to use the new aproach --- src/abi/interaction.local.net.spec.ts | 5 +- src/abi/interaction.spec.ts | 114 ++++++++++-------- src/abi/interaction.ts | 2 +- src/abi/smartContract.spec.ts | 20 +-- src/abi/smartContract.ts | 6 +- .../smartContractResults.local.net.spec.ts | 8 +- src/testutils/mockNetworkProvider.ts | 4 +- src/testutils/utils.ts | 8 +- src/tokens.ts | 8 +- src/transaction.local.net.spec.ts | 17 ++- src/transaction.spec.ts | 78 +++++++----- src/transaction.ts | 62 +++++----- 12 files changed, 181 insertions(+), 151 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index cbe33c112..44fe1a1ad 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -483,8 +483,7 @@ describe("test smart contract interactor", function () { const transaction = options.transaction; const wallet = options.wallet; - const serialized = transaction.serializeForSigning(); - const signature = await wallet.signer.sign(serialized); - transaction.applySignature(signature); + const transactionComputer = new TransactionComputer(); + transaction.signature = await wallet.signer.sign(transactionComputer.computeBytesForSigning(transaction)); } }); diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index af32410b1..1741424f1 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -12,6 +12,7 @@ import { } from "../testutils"; import { Token, TokenTransfer } from "../tokens"; import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; @@ -21,7 +22,7 @@ describe("test smart contract interactor", function () { let dummyAddress = new Address("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"); let provider = new MockNetworkProvider(); let alice: TestWallet; - + const transactionComputer = new TransactionComputer(); before(async function () { ({ alice } = await loadTestWallets()); }); @@ -38,10 +39,10 @@ describe("test smart contract interactor", function () { .withGasLimit(20000000n) .buildTransaction(); - assert.deepEqual(transaction.getReceiver(), dummyAddress); - assert.equal(transaction.getValue().toString(), "1000000000000000000"); - assert.equal(transaction.getNonce(), 7n); - assert.equal(transaction.getGasLimit().valueOf(), 20000000n); + assert.deepEqual(transaction.receiver, dummyAddress); + assert.equal(transaction.value.toString(), "1000000000000000000"); + assert.equal(transaction.nonce, 7n); + assert.equal(transaction.gasLimit, 20000000n); }); it("should set transfers (payments) on contract calls (transfer and execute)", async function () { @@ -74,7 +75,7 @@ describe("test smart contract interactor", function () { .withSingleESDTTransfer(TokenFoo(10)) .buildTransaction(); - assert.equal(transaction.getData().toString(), `ESDTTransfer@${hexFoo}@0a@${hexDummyFunction}`); + assert.equal(transaction.data.toString(), `ESDTTransfer@${hexFoo}@0a@${hexDummyFunction}`); // Meta ESDT (special SFT), single transaction = new Interaction(contract, dummyFunction, []) @@ -82,10 +83,10 @@ describe("test smart contract interactor", function () { .withSingleESDTNFTTransfer(LKMEX(123456, "123456000000000000000")) .buildTransaction(); - assert.equal(transaction.getSender().toBech32(), alice.toBech32()); - assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); + assert.equal(transaction.sender.toBech32(), alice.toBech32()); + assert.equal(transaction.receiver.toBech32(), alice.toBech32()); assert.equal( - transaction.getData().toString(), + transaction.data.toString(), `ESDTNFTTransfer@${hexLKMEX}@01e240@06b14bd1e6eea00000@${hexContractAddress}@${hexDummyFunction}`, ); @@ -95,10 +96,10 @@ describe("test smart contract interactor", function () { .withSender(alice) .buildTransaction(); - assert.equal(transaction.getSender().toBech32(), alice.toBech32()); - assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); + assert.equal(transaction.sender.toBech32(), alice.toBech32()); + assert.equal(transaction.receiver.toBech32(), alice.toBech32()); assert.equal( - transaction.getData().toString(), + transaction.data.toString(), `ESDTNFTTransfer@${hexLKMEX}@01e240@06b14bd1e6eea00000@${hexContractAddress}@${hexDummyFunction}`, ); @@ -108,10 +109,10 @@ describe("test smart contract interactor", function () { .withSingleESDTNFTTransfer(nonFungibleToken(1)) .buildTransaction(); - assert.equal(transaction.getSender().toBech32(), alice.toBech32()); - assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); + assert.equal(transaction.sender.toBech32(), alice.toBech32()); + assert.equal(transaction.receiver.toBech32(), alice.toBech32()); assert.equal( - transaction.getData().toString(), + transaction.data.toString(), `ESDTNFTTransfer@${hexNFT}@01@01@${hexContractAddress}@${hexDummyFunction}`, ); @@ -121,10 +122,10 @@ describe("test smart contract interactor", function () { .withSender(alice) .buildTransaction(); - assert.equal(transaction.getSender().toBech32(), alice.toBech32()); - assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); + assert.equal(transaction.sender.toBech32(), alice.toBech32()); + assert.equal(transaction.receiver.toBech32(), alice.toBech32()); assert.equal( - transaction.getData().toString(), + transaction.data.toString(), `ESDTNFTTransfer@${hexNFT}@01@01@${hexContractAddress}@${hexDummyFunction}`, ); @@ -134,10 +135,10 @@ describe("test smart contract interactor", function () { .withMultiESDTNFTTransfer([TokenFoo(3), TokenBar(3140)]) .buildTransaction(); - assert.equal(transaction.getSender().toBech32(), alice.toBech32()); - assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); + assert.equal(transaction.sender.toBech32(), alice.toBech32()); + assert.equal(transaction.receiver.toBech32(), alice.toBech32()); assert.equal( - transaction.getData().toString(), + transaction.data.toString(), `MultiESDTNFTTransfer@${hexContractAddress}@02@${hexFoo}@@03@${hexBar}@@0c44@${hexDummyFunction}`, ); @@ -147,10 +148,10 @@ describe("test smart contract interactor", function () { .withSender(alice) .buildTransaction(); - assert.equal(transaction.getSender().toBech32(), alice.toBech32()); - assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); + assert.equal(transaction.sender.toBech32(), alice.toBech32()); + assert.equal(transaction.receiver.toBech32(), alice.toBech32()); assert.equal( - transaction.getData().toString(), + transaction.data.toString(), `MultiESDTNFTTransfer@${hexContractAddress}@02@${hexFoo}@@03@${hexBar}@@0c44@${hexDummyFunction}`, ); @@ -160,10 +161,10 @@ describe("test smart contract interactor", function () { .withMultiESDTNFTTransfer([nonFungibleToken(1), nonFungibleToken(42)]) .buildTransaction(); - assert.equal(transaction.getSender().toBech32(), alice.toBech32()); - assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); + assert.equal(transaction.sender.toBech32(), alice.toBech32()); + assert.equal(transaction.receiver.toBech32(), alice.toBech32()); assert.equal( - transaction.getData().toString(), + transaction.data.toString(), `MultiESDTNFTTransfer@${hexContractAddress}@02@${hexNFT}@01@01@${hexNFT}@2a@01@${hexDummyFunction}`, ); @@ -173,8 +174,8 @@ describe("test smart contract interactor", function () { .withSender(alice) .buildTransaction(); - assert.equal(transaction.getSender().toBech32(), alice.toBech32()); - assert.equal(transaction.getReceiver().toBech32(), alice.toBech32()); + assert.equal(transaction.sender.toBech32(), alice.toBech32()); + assert.equal(transaction.receiver.toBech32(), alice.toBech32()); }); it("should create transaction, with ABI, with transfer & execute", async function () { @@ -246,24 +247,24 @@ describe("test smart contract interactor", function () { // Execute, do not wait for execution let transaction = interaction.withSender(alice.address).withNonce(0n).buildTransaction(); - transaction.setSender(alice.address); - transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); + transaction.sender = alice.address; + transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); let hash = await provider.sendTransaction(transaction); - assert.equal(transaction.getNonce().valueOf(), 0n); - assert.equal(transaction.getData().toString(), "getUltimateAnswer"); + assert.equal(transaction.nonce, 0n); + assert.equal(transaction.data.toString(), "getUltimateAnswer"); assert.equal(hash, "3579ad09099feb9755c860ddd225251170806d833342e912fccdfe2ed5c3a364"); transaction = interaction.withNonce(1n).buildTransaction(); - transaction.setSender(alice.address); - transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); + transaction.sender = alice.address; + transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); hash = await provider.sendTransaction(transaction); - assert.equal(transaction.getNonce(), 1n); + assert.equal(transaction.nonce, 1n); assert.equal(hash, "ad513ce7c5d371d30e48f073326899766736eac1ac231d847d45bc3facbcb496"); // Execute, and wait for execution transaction = interaction.withNonce(2n).buildTransaction(); - transaction.setSender(alice.address); - transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning())); + transaction.sender = alice.address; + transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs", "getUltimateAnswer"); hash = await provider.sendTransaction(transaction); let responseExecute = await controller.awaitCompletedExecute(hash); @@ -312,7 +313,9 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - incrementTransaction.applySignature(await alice.signer.sign(incrementTransaction.serializeForSigning())); + incrementTransaction.signature = await alice.signer.sign( + transactionComputer.computeBytesForSigning(incrementTransaction), + ); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@08", "increment"); let hash = await provider.sendTransaction(incrementTransaction); let responseExecute = await controller.awaitCompletedExecute(hash); @@ -326,16 +329,22 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - decrementTransaction.applySignature(await alice.signer.sign(decrementTransaction.serializeForSigning())); + decrementTransaction.signature = await alice.signer.sign( + transactionComputer.computeBytesForSigning(decrementTransaction), + ); await provider.sendTransaction(decrementTransaction); // Decrement #2 decrementTransaction = decrementInteraction.withNonce(16n).buildTransaction(); - decrementTransaction.applySignature(await alice.signer.sign(decrementTransaction.serializeForSigning())); + decrementTransaction.signature = await alice.signer.sign( + transactionComputer.computeBytesForSigning(decrementTransaction), + ); await provider.sendTransaction(decrementTransaction); // Decrement #3 decrementTransaction = decrementInteraction.withNonce(17n).buildTransaction(); - decrementTransaction.applySignature(await alice.signer.sign(decrementTransaction.serializeForSigning())); + decrementTransaction.signature = await alice.signer.sign( + transactionComputer.computeBytesForSigning(decrementTransaction), + ); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@05", "decrement"); hash = await provider.sendTransaction(decrementTransaction); responseExecute = await controller.awaitCompletedExecute(hash); @@ -376,16 +385,15 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - startTransaction.applySignature(await alice.signer.sign(startTransaction.serializeForSigning())); + startTransaction.signature = await alice.signer.sign( + transactionComputer.computeBytesForSigning(startTransaction), + ); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b", "start"); let hash = await provider.sendTransaction(startTransaction); let response = await controller.awaitCompletedExecute(hash); - assert.equal( - startTransaction.getData().toString(), - "start@6c75636b79@6c75636b792d746f6b656e@01@@@0100000001@@", - ); + assert.equal(startTransaction.data.toString(), "start@6c75636b79@6c75636b792d746f6b656e@01@@@0100000001@@"); assert.isTrue(response.returnCode == "ok"); assert.isTrue(response.values.length == 0); @@ -396,13 +404,15 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - statusTransaction.applySignature(await alice.signer.sign(statusTransaction.serializeForSigning())); + statusTransaction.signature = await alice.signer.sign( + transactionComputer.computeBytesForSigning(statusTransaction), + ); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@01", "status"); hash = await provider.sendTransaction(startTransaction); response = await controller.awaitCompletedExecute(hash); - assert.equal(statusTransaction.getData().toString(), "status@6c75636b79"); + assert.equal(statusTransaction.data.toString(), "status@6c75636b79"); assert.isTrue(response.returnCode == "ok"); assert.isTrue(response.values.length == 1); assert.deepEqual(response.values[0]!.valueOf(), { name: "Running", fields: [] }); @@ -414,8 +424,8 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - getLotteryInfoTransaction.applySignature( - await alice.signer.sign(getLotteryInfoTransaction.serializeForSigning()), + getLotteryInfoTransaction.signature = await alice.signer.sign( + transactionComputer.computeBytesForSigning(getLotteryInfoTransaction), ); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult( "@6f6b@0000000b6c75636b792d746f6b656e000000010100000000000000005fc2b9dbffffffff00000001640000000a140ec80fa7ee88000000", @@ -423,7 +433,7 @@ describe("test smart contract interactor", function () { ); hash = await provider.sendTransaction(startTransaction); response = await controller.awaitCompletedExecute(hash); - assert.equal(getLotteryInfoTransaction.getData().toString(), "getLotteryInfo@6c75636b79"); + assert.equal(getLotteryInfoTransaction.data.toString(), "getLotteryInfo@6c75636b79"); assert.isTrue(response.returnCode == "ok"); assert.isTrue(response.values.length == 1); diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index 4f33f3632..b9ac422c4 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -21,7 +21,7 @@ interface ISmartContractWithinInteraction { } /** - * Legacy component. Use "SmartContractTransactionsFactory" (for transactions) or "SmartContractQueriesController" (for queries), instead. + * @deprecated component. Use "SmartContractTransactionsFactory" (for transactions) or "SmartContractQueriesController" (for queries), instead. * * Interactions can be seen as mutable transaction & query builders. * diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index d197518ef..501db6e3e 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -21,6 +21,7 @@ describe("test contract", () => { let provider = new MockNetworkProvider(); let chainID = "test"; let alice: TestWallet; + const computer = new TransactionComputer(); before(async function () { ({ alice } = await loadTestWallets()); @@ -58,7 +59,7 @@ describe("test contract", () => { await alice.sync(provider); deployTransaction.nonce = alice.account.nonce; - assert.equal(deployTransaction.getData().valueOf().toString(), "01020304@0500@0100"); + assert.equal(deployTransaction.data.toString(), "01020304@0500@0100"); assert.equal(deployTransaction.gasLimit, 1000000n); assert.equal(deployTransaction.nonce, 42n); @@ -70,11 +71,10 @@ describe("test contract", () => { ); // Sign the transaction - deployTransaction.applySignature(await alice.signer.sign(deployTransaction.serializeForSigning())); + deployTransaction.signature = await alice.signer.sign(computer.computeBytesForSigning(deployTransaction)); // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); - const computer = new TransactionComputer(); const hashString = computer.computeTransactionHash(deployTransaction); await Promise.all([ @@ -125,15 +125,15 @@ describe("test contract", () => { callTransactionTwo.nonce = alice.account.nonce; assert.equal(callTransactionOne.nonce, 42n); - assert.equal(callTransactionOne.getData().valueOf().toString(), "helloEarth@05@0123"); + assert.equal(callTransactionOne.data.toString(), "helloEarth@05@0123"); assert.equal(callTransactionOne.gasLimit, 150000n); assert.equal(callTransactionTwo.nonce, 43n); - assert.equal(callTransactionTwo.getData().valueOf().toString(), "helloMars@05@0123"); + assert.equal(callTransactionTwo.data.toString(), "helloMars@05@0123"); assert.equal(callTransactionTwo.gasLimit, 1500000n); // Sign transactions, broadcast them - callTransactionOne.applySignature(await alice.signer.sign(callTransactionOne.serializeForSigning())); - callTransactionTwo.applySignature(await alice.signer.sign(callTransactionTwo.serializeForSigning())); + callTransactionOne.signature = await alice.signer.sign(computer.computeBytesForSigning(callTransactionOne)); + callTransactionTwo.signature = await alice.signer.sign(computer.computeBytesForSigning(callTransactionTwo)); let hashOne = await provider.sendTransaction(callTransactionOne); let hashTwo = await provider.sendTransaction(callTransactionTwo); @@ -166,7 +166,7 @@ describe("test contract", () => { let watcher = new TransactionWatcher(provider); let contract = new SmartContract(); - contract.setAddress(Address.fromBech32("erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q")); + contract.setAddress(Address.newFromBech32("erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q")); let deployTransaction = contract.upgrade({ code: Code.fromBuffer(Buffer.from([1, 2, 3, 4])), @@ -182,12 +182,12 @@ describe("test contract", () => { await alice.sync(provider); deployTransaction.nonce = alice.account.nonce; - assert.equal(deployTransaction.getData().valueOf().toString(), "upgradeContract@01020304@0100"); + assert.equal(deployTransaction.data.toString(), "upgradeContract@01020304@0100"); assert.equal(deployTransaction.gasLimit, 1000000n); assert.equal(deployTransaction.nonce, 42n); // Sign the transaction - deployTransaction.applySignature(await alice.signer.sign(deployTransaction.serializeForSigning())); + deployTransaction.signature = await alice.signer.sign(computer.computeBytesForSigning(deployTransaction)); // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 624ada69e..322132c50 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -220,7 +220,7 @@ export class SmartContract implements ISmartContract { isPayableBySmartContract: metadataAsJson.payableBySc, }); - transaction.setChainID(chainID); + transaction.chainID = chainID; transaction.value = value ?? 0n; transaction.gasPrice = gasPrice ?? BigInt(TRANSACTION_MIN_GAS_PRICE); @@ -255,8 +255,8 @@ export class SmartContract implements ISmartContract { arguments: args, }); - transaction.setChainID(chainID); - transaction.setValue(value); + transaction.chainID = chainID; + transaction.value = value; transaction.gasPrice = gasPrice ?? BigInt(TRANSACTION_MIN_GAS_PRICE); return transaction; diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 89ffcd141..297034536 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -14,7 +14,7 @@ describe("fetch transactions from local testnet", function () { let provider = createLocalnetProvider(); let watcher: TransactionWatcher; let parser: SmartContractTransactionsOutcomeParser; - + const transactionComputer = new TransactionComputer(); before(async function () { ({ alice } = await loadTestWallets()); watcher = new TransactionWatcher({ @@ -55,8 +55,10 @@ describe("fetch transactions from local testnet", function () { caller: alice.address, }); - transactionIncrement.setNonce(alice.account.nonce); - transactionIncrement.applySignature(await alice.signer.sign(transactionIncrement.serializeForSigning())); + transactionIncrement.nonce = alice.account.nonce; + transactionIncrement.signature = await alice.signer.sign( + transactionComputer.computeBytesForSigning(transactionIncrement), + ); alice.account.incrementNonce(); diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 5dfd1333b..0a147d212 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -228,8 +228,8 @@ export class MockNetworkProvider implements INetworkProvider { this.mockPutTransaction( computer.computeTransactionHash(transaction), new TransactionOnNetwork({ - sender: transaction.getSender(), - receiver: transaction.getReceiver(), + sender: transaction.sender, + receiver: transaction.receiver, data: Buffer.from(transaction.data), status: new TransactionStatus("pending"), }), diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index 96de9e707..bca35a365 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -2,6 +2,7 @@ import * as fs from "fs"; import { PathLike } from "fs"; import { AbiRegistry, Code, SmartContract, TypedValue } from "../abi"; import { Transaction } from "../transaction"; +import { TransactionComputer } from "../transactionComputer"; import { TransactionWatcher } from "../transactionWatcher"; import { getAxios } from "../utils"; import { TestWallet } from "./wallets"; @@ -25,12 +26,13 @@ export async function prepareDeployment(obj: { deployer: deployer.address, }); + const computer = new TransactionComputer(); let nonce = deployer.account.getNonceThenIncrement(); let contractAddress = SmartContract.computeAddress(deployer.address, nonce); - transaction.setNonce(nonce); - transaction.setSender(deployer.address); + transaction.nonce = nonce; + transaction.sender = deployer.address; contract.setAddress(contractAddress); - transaction.applySignature(await deployer.signer.sign(transaction.serializeForSigning())); + transaction.signature = await deployer.signer.sign(computer.computeBytesForSigning(transaction)); return transaction; } diff --git a/src/tokens.ts b/src/tokens.ts index 6e7776bd0..11c670ba4 100644 --- a/src/tokens.ts +++ b/src/tokens.ts @@ -33,22 +33,22 @@ export class TokenTransfer { readonly amount: bigint; /** - * Legacy field. Use "token.identifier" instead. + * @deprecated field. Use "token.identifier" instead. */ readonly tokenIdentifier: string; /** - * Legacy field. Use "token.nonce" instead. + * @deprecated field. Use "token.nonce" instead. */ readonly nonce: number; /** - * Legacy field. Use "amount" instead. + * @deprecated field. Use "amount" instead. */ readonly amountAsBigInteger: BigNumber; /** - * Legacy field. The number of decimals is not a concern of "sdk-core". + * @deprecated field. The number of decimals is not a concern of "sdk-core". * For formatting and parsing amounts, use "sdk-dapp" or "bignumber.js" directly. */ readonly numDecimals: number; diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 8e77a9878..07871ed76 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -13,7 +13,7 @@ import { TransferTransactionsFactory } from "./transfers/transferTransactionsFac describe("test transaction", function () { let alice: TestWallet, bob: TestWallet; - + const transactionComputer = new TransactionComputer(); before(async function () { ({ alice, bob } = await loadTestWallets()); }); @@ -56,9 +56,9 @@ describe("test transaction", function () { await bob.sync(provider); let initialBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); - transactionOne.setNonce(alice.account.nonce); + transactionOne.nonce = alice.account.nonce; alice.account.incrementNonce(); - transactionTwo.setNonce(alice.account.nonce); + transactionTwo.nonce = alice.account.nonce; await signTransaction({ transaction: transactionOne, wallet: alice }); await signTransaction({ transaction: transactionTwo, wallet: alice }); @@ -98,7 +98,7 @@ describe("test transaction", function () { await bob.sync(provider); let initialBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); - transactionOne.setNonce(alice.account.nonce); + transactionOne.nonce = alice.account.nonce; await signTransaction({ transaction: transactionOne, wallet: alice }); const hashOne = await provider.sendTransaction(transactionOne); await watcher.awaitCompleted(hashOne); @@ -137,8 +137,8 @@ describe("test transaction", function () { chainID: network.chainID, }); - transactionOne.setNonce(alice.account.nonce); - transactionTwo.setNonce(alice.account.nonce); + transactionOne.nonce = alice.account.nonce; + transactionTwo.nonce = alice.account.nonce; await signTransaction({ transaction: transactionOne, wallet: alice }); await signTransaction({ transaction: transactionTwo, wallet: alice }); @@ -168,7 +168,6 @@ describe("test transaction", function () { }); transaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); const txHash = await provider.sendTransaction(transaction); @@ -187,8 +186,8 @@ describe("test transaction", function () { const transaction = options.transaction; const wallet = options.wallet; - const serialized = transaction.serializeForSigning(); + const serialized = transactionComputer.computeBytesForSigning(transaction); const signature = await wallet.signer.sign(serialized); - transaction.applySignature(signature); + transaction.signature = signature; } }); diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index 6640aef79..201360331 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -78,10 +78,12 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); + transaction.signature = await wallets.alice.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); assert.equal( - transaction.getSignature().toString("hex"), + Buffer.from(transaction.signature).toString("hex"), "3f08a1dd64fbb627d10b048e0b45b1390f29bb0e457762a2ccb710b029f299022a67a4b8e45cf62f4314afec2e56b5574c71e38df96cc41fae757b7ee5062503", ); assert.equal( @@ -102,10 +104,12 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); + transaction.signature = await wallets.alice.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); assert.equal( - transaction.getSignature().toString("hex"), + Buffer.from(transaction.signature).toString("hex"), "f9e8c1caf7f36b99e7e76ee1118bf71b55cde11a2356e2b3adf15f4ad711d2e1982469cbba7eb0afbf74e8a8f78e549b9410cd86eeaa88fcba62611ac9f6e30e", ); assert.equal( @@ -198,7 +202,7 @@ describe("test transaction", async () => { }); assert.throws(() => { - transaction.serializeForSigning(); + transactionComputer.computeBytesForSigning(transaction); }, `Non-empty transaction options requires transaction version >= ${MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`); }); @@ -214,10 +218,12 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); + transaction.signature = await wallets.alice.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); assert.equal( - transaction.getSignature().toString("hex"), + Buffer.from(transaction.signature).toString("hex"), "b45f22e9f57a6df22670fcc3566723a0711a05ac2547456de59fd222a54940e4a1d99bd414897ccbf5c02a842ad86e638989b7f4d30edd26c99a8cd1eb092304", ); assert.equal( @@ -238,10 +244,12 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); + transaction.signature = await wallets.alice.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); assert.equal( - transaction.getSignature().toString("hex"), + Buffer.from(transaction.signature).toString("hex"), "01f05aa8cb0614e12a94ab9dcbde5e78370a4e05d23ef25a1fb9d5fcf1cb3b1f33b919cd8dafb1704efb18fa233a8aa0d3344fb6ee9b613a7d7a403786ffbd0a", ); assert.equal( @@ -263,10 +271,12 @@ describe("test transaction", async () => { version: 1, }); - transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); + transaction.signature = await wallets.alice.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); assert.equal( - transaction.getSignature().toString("hex"), + Buffer.from(transaction.signature).toString("hex"), "dfa3e9f2fdec60dcb353bac3b3435b4a2ff251e7e98eaf8620f46c731fc70c8ba5615fd4e208b05e75fe0f7dc44b7a99567e29f94fcd91efac7e67b182cd2a04", ); assert.equal( @@ -286,10 +296,12 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); + transaction.signature = await wallets.alice.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); assert.equal( - transaction.getSignature().toString("hex"), + Buffer.from(transaction.signature).toString("hex"), "3f08a1dd64fbb627d10b048e0b45b1390f29bb0e457762a2ccb710b029f299022a67a4b8e45cf62f4314afec2e56b5574c71e38df96cc41fae757b7ee5062503", ); assert.equal( @@ -297,7 +309,7 @@ describe("test transaction", async () => { "1359fb9d5b0b47ca9f3b4adce6e4a524fa74099dd4732743b9226774a4cb0ad8", ); - const result = transaction.serializeForSigning(); + const result = transactionComputer.computeBytesForSigning(transaction); assert.isFalse(result.toString().includes("options")); }); @@ -312,10 +324,12 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); + transaction.signature = await wallets.alice.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); assert.equal( - transaction.getSignature().toString("hex"), + Buffer.from(transaction.signature).toString("hex"), "3f08a1dd64fbb627d10b048e0b45b1390f29bb0e457762a2ccb710b029f299022a67a4b8e45cf62f4314afec2e56b5574c71e38df96cc41fae757b7ee5062503", ); assert.equal( @@ -323,7 +337,7 @@ describe("test transaction", async () => { "1359fb9d5b0b47ca9f3b4adce6e4a524fa74099dd4732743b9226774a4cb0ad8", ); - const result = transaction.serializeForSigning(); + const result = transactionComputer.computeBytesForSigning(transaction); assert.isFalse(result.toString().includes("options")); }); @@ -331,18 +345,20 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 204n, value: 1000000000000000000n, - sender: Address.fromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"), - receiver: Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + sender: Address.newFromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"), + receiver: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), senderUsername: "carol", receiverUsername: "alice", gasLimit: 50000n, chainID: "T", }); - transaction.applySignature(await wallets.carol.signer.sign(transaction.serializeForSigning())); + transaction.signature = await wallets.carol.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); assert.equal( - transaction.getSignature().toString("hex"), + Buffer.from(transaction.signature).toString("hex"), "51e6cd78fb3ab4b53ff7ad6864df27cb4a56d70603332869d47a5cf6ea977c30e696103e41e8dddf2582996ad335229fdf4acb726564dbc1a0bc9e705b511f06", ); assert.equal( @@ -393,7 +409,7 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - const fee = transaction.computeFee(networkConfig); + const fee = transactionComputer.computeTransactionFee(transaction, networkConfig); assert.equal(fee.toString(), "50000000000000"); }); @@ -436,7 +452,7 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - let fee = transaction.computeFee(networkConfig); + let fee = transactionComputer.computeTransactionFee(transaction, networkConfig); assert.equal(fee.toString(), "62000100000000"); }); @@ -470,7 +486,7 @@ describe("test transaction", async () => { }); const plainObject = transaction.toPlainObject(); - const restoredTransaction = Transaction.fromPlainObject(plainObject); + const restoredTransaction = Transaction.newFromPlainObject(plainObject); assert.deepEqual(restoredTransaction, transaction); }); @@ -482,7 +498,7 @@ describe("test transaction", async () => { gasLimit: 50000n, chainID: "local-testnet", }); - assert.equal(tx1.getValue().toString(), "123456789000000000000000000000"); + assert.equal(tx1.value.toString(), "123456789000000000000000000000"); const tx2 = new Transaction({ value: 123456789000000000000000000000n, @@ -491,7 +507,7 @@ describe("test transaction", async () => { gasLimit: 50000n, chainID: "local-testnet", }); - assert.equal(tx2.getValue().toString(), "123456789000000000000000000000"); + assert.equal(tx2.value.toString(), "123456789000000000000000000000"); const tx3 = new Transaction({ value: BigInt("123456789000000000000000000000"), @@ -500,7 +516,7 @@ describe("test transaction", async () => { gasLimit: 50000n, chainID: "local-testnet", }); - assert.equal(tx3.getValue().toString(), "123456789000000000000000000000"); + assert.equal(tx3.value.toString(), "123456789000000000000000000000"); }); it("checks correctly the version and options of the transaction", async () => { @@ -588,8 +604,10 @@ describe("test transaction", async () => { version: 2, options: 2, }); - transaction.applySignature(await wallets.alice.signer.sign(transaction.serializeForSigning())); - transaction.applyGuardianSignature(transaction.getSignature()); + transaction.signature = await wallets.alice.signer.sign( + transactionComputer.computeBytesForSigning(transaction), + ); + transaction.guardianSignature = transaction.signature; assert.isTrue(transaction.isGuardedTransaction()); }); @@ -756,7 +774,7 @@ describe("test transaction", async () => { const restoredTransaction = Transaction.newFromPlainObject(plainObject); assert.deepEqual(plainObject, transaction.toPlainObject()); - assert.deepEqual(restoredTransaction, Transaction.fromPlainObject(plainObject)); + assert.deepEqual(restoredTransaction, Transaction.newFromPlainObject(plainObject)); assert.deepEqual(restoredTransaction, transaction); assert.deepEqual(plainObject, { nonce: 90, diff --git a/src/transaction.ts b/src/transaction.ts index 110ca9816..c6e68505c 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -139,14 +139,14 @@ export class Transaction { } /** - * Legacy method, use the "nonce" property instead. + * @deprecated method, use the "nonce" property instead. */ getNonce(): bigint { return this.nonce; } /** - * Legacy method, use the "nonce" property instead. + * @deprecated method, use the "nonce" property instead. * Sets the account sequence number of the sender. Must be done prior signing. */ setNonce(nonce: bigint) { @@ -154,147 +154,147 @@ export class Transaction { } /** - * Legacy method, use the "value" property instead. + * @deprecated method, use the "value" property instead. */ getValue(): bigint { return this.value; } /** - * Legacy method, use the "value" property instead. + * @deprecated method, use the "value" property instead. */ setValue(value: bigint) { this.value = value; } /** - * Legacy method, use the "sender" property instead. + * @deprecated method, use the "sender" property instead. */ getSender(): Address { return this.sender; } /** - * Legacy method, use the "sender" property instead. + * @deprecated method, use the "sender" property instead. */ setSender(sender: Address) { this.sender = sender; } /** - * Legacy method, use the "receiver" property instead. + * @deprecated method, use the "receiver" property instead. */ getReceiver(): Address { return this.receiver; } /** - * Legacy method, use the "senderUsername" property instead. + * @deprecated method, use the "senderUsername" property instead. */ getSenderUsername(): string { return this.senderUsername; } /** - * Legacy method, use the "senderUsername" property instead. + * @deprecated method, use the "senderUsername" property instead. */ setSenderUsername(senderUsername: string) { this.senderUsername = senderUsername; } /** - * Legacy method, use the "receiverUsername" property instead. + * @deprecated method, use the "receiverUsername" property instead. */ getReceiverUsername(): string { return this.receiverUsername; } /** - * Legacy method, use the "receiverUsername" property instead. + * @deprecated method, use the "receiverUsername" property instead. */ setReceiverUsername(receiverUsername: string) { this.receiverUsername = receiverUsername; } /** - * Legacy method, use the "guardian" property instead. + * @deprecated method, use the "guardian" property instead. */ getGuardian(): Address { return this.guardian; } /** - * Legacy method, use the "gasPrice" property instead. + * @deprecated method, use the "gasPrice" property instead. */ getGasPrice(): bigint { return this.gasPrice; } /** - * Legacy method, use the "gasPrice" property instead. + * @deprecated method, use the "gasPrice" property instead. */ setGasPrice(gasPrice: bigint) { this.gasPrice = gasPrice; } /** - * Legacy method, use the "gasLimit" property instead. + * @deprecated method, use the "gasLimit" property instead. */ getGasLimit(): bigint { return this.gasLimit; } /** - * Legacy method, use the "gasLimit" property instead. + * @deprecated method, use the "gasLimit" property instead. */ setGasLimit(gasLimit: bigint) { this.gasLimit = gasLimit; } /** - * Legacy method, use the "data" property instead. + * @deprecated method, use the "data" property instead. */ getData(): Uint8Array { return this.data; } /** - * Legacy method, use the "chainID" property instead. + * @deprecated method, use the "chainID" property instead. */ getChainID(): string { return this.chainID; } /** - * Legacy method, use the "chainID" property instead. + * @deprecated method, use the "chainID" property instead. */ setChainID(chainID: string) { this.chainID = chainID; } /** - * Legacy method, use the "version" property instead. + * @deprecated method, use the "version" property instead. */ getVersion(): number { return this.version; } /** - * Legacy method, use the "version" property instead. + * @deprecated method, use the "version" property instead. */ setVersion(version: number) { this.version = version; } /** - * Legacy method, use the "options" property instead. + * @deprecated method, use the "options" property instead. */ getOptions(): number { return this.options; } /** - * Legacy method, use the "options" property instead. + * @deprecated method, use the "options" property instead. * * Question for review: check how the options are set by sdk-dapp, wallet, ledger, extension. */ @@ -303,28 +303,28 @@ export class Transaction { } /** - * Legacy method, use the "signature" property instead. + * @deprecated method, use the "signature" property instead. */ getSignature(): Buffer { return Buffer.from(this.signature); } /** - * Legacy method, use the "guardianSignature" property instead. + * @deprecated method, use the "guardianSignature" property instead. */ getGuardianSignature(): Buffer { return Buffer.from(this.guardianSignature); } /** - * Legacy method, use the "guardian" property instead. + * @deprecated method, use the "guardian" property instead. */ setGuardian(guardian: Address) { this.guardian = guardian; } /** - * Legacy method, use "TransactionComputer.computeBytesForSigning()" instead. + * @deprecated method, use "TransactionComputer.computeBytesForSigning()" instead. * Serializes a transaction to a sequence of bytes, ready to be signed. * This function is called internally by signers. */ @@ -373,7 +373,7 @@ export class Transaction { } /** - * Legacy method, use "Transaction.newFromPlainObject()" instead. + * @deprecated method, use "Transaction.newFromPlainObject()" instead. * Converts a plain object transaction into a Transaction Object. * * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() @@ -412,7 +412,7 @@ export class Transaction { } /** - * Legacy method, use the "signature" property instead. + * @deprecated method, use the "signature" property instead. * Applies the signature on the transaction. * * @param signature The signature, as computed by a signer. @@ -422,7 +422,7 @@ export class Transaction { } /** - * Legacy method, use the "guardianSignature" property instead. + * @deprecated method, use the "guardianSignature" property instead. * Applies the guardian signature on the transaction. * * @param guardianSignature The signature, as computed by a signer. @@ -440,7 +440,7 @@ export class Transaction { } /** - * Legacy method, use "TransactionComputer.computeTransactionFee()" instead. + * @deprecated method, use "TransactionComputer.computeTransactionFee()" instead. * * Computes the current transaction fee based on the {@link NetworkConfig} and transaction properties * @param networkConfig {@link NetworkConfig} From caa7bc321b31c16653e73deb3fd33cc7cf6601ef Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 13:55:16 +0200 Subject: [PATCH 153/214] Update code to use new methods and not the deprecated one --- src/abi/smartContract.spec.ts | 8 ++++---- src/wallet/userSigner.ts | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index 501db6e3e..5dd1ddc22 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -227,8 +227,8 @@ describe("test contract", () => { ], }); - const callerAddress = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contractAddress = Address.fromBech32("erd1qqqqqqqqqqqqqpgqaxa53w6uk43n6dhyt2la6cd5lyv32qn4396qfsqlnk"); + const callerAddress = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contractAddress = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqaxa53w6uk43n6dhyt2la6cd5lyv32qn4396qfsqlnk"); const contract = new SmartContract({ abi, @@ -296,8 +296,8 @@ describe("test contract", () => { ], }); - const callerAddress = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contractAddress = Address.fromBech32("erd1qqqqqqqqqqqqqpgqaxa53w6uk43n6dhyt2la6cd5lyv32qn4396qfsqlnk"); + const callerAddress = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contractAddress = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqaxa53w6uk43n6dhyt2la6cd5lyv32qn4396qfsqlnk"); const contract = new SmartContract({ abi, diff --git a/src/wallet/userSigner.ts b/src/wallet/userSigner.ts index a74518ffd..6163e9dc0 100644 --- a/src/wallet/userSigner.ts +++ b/src/wallet/userSigner.ts @@ -36,7 +36,7 @@ export class UserSigner { * Gets the address of the signer. */ getAddress(hrp?: string): Address { - const bech32 = this.secretKey.generatePublicKey().toAddress(hrp).bech32(); + const bech32 = this.secretKey.generatePublicKey().toAddress(hrp).toBech32(); return Address.newFromBech32(bech32); } } From 21f3f0b718468bdcc1f97b281fcaa21f7583ef6d Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 14:14:42 +0200 Subject: [PATCH 154/214] Remove interfaces on network --- src/index.ts | 1 - src/interface.ts | 7 ++ src/interfaceOfNetwork.ts | 95 ---------------------------- src/testutils/mockNetworkProvider.ts | 3 +- src/testutils/wallets.ts | 4 +- src/transaction.ts | 3 +- src/transactionComputer.ts | 2 +- src/transactionWatcher.ts | 6 +- 8 files changed, 15 insertions(+), 106 deletions(-) delete mode 100644 src/interfaceOfNetwork.ts diff --git a/src/index.ts b/src/index.ts index fd82a4eb7..64b8861f7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,7 +16,6 @@ export * from "./delegation"; export * from "./entrypoints"; export * from "./errors"; export * from "./interface"; -export * from "./interfaceOfNetwork"; export * from "./logger"; export * from "./message"; export * from "./networkParams"; diff --git a/src/interface.ts b/src/interface.ts index d867b4629..62ac22c37 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -26,3 +26,10 @@ export interface IPlainTransactionObject { guardianSignature?: string; relayerSignature?: string; } + +export interface INetworkConfig { + MinGasLimit: number; + GasPerDataByte: number; + GasPriceModifier: number; + ChainID: string; +} diff --git a/src/interfaceOfNetwork.ts b/src/interfaceOfNetwork.ts deleted file mode 100644 index e3a4e7e59..000000000 --- a/src/interfaceOfNetwork.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { Address } from "./address"; - -export interface IAccountOnNetwork { - nonce: bigint; - balance: bigint; -} - -export interface INetworkConfig { - MinGasLimit: number; - GasPerDataByte: number; - GasPriceModifier: number; - ChainID: string; -} - -export interface ITransactionOnNetwork { - isCompleted?: boolean; - - hash: string; - type: string; - value: string; - receiver: Address; - sender: Address; - function?: string; - data: Buffer; - status: ITransactionStatus; - receipt: ITransactionReceipt; - contractResults: IContractResults; - logs: ITransactionLogs; -} - -export interface ITransactionStatus { - isPending(): boolean; - isFailed(): boolean; - isInvalid(): boolean; - isExecuted(): boolean; - isSuccessful(): boolean; - valueOf(): string; -} - -export interface ITransactionReceipt { - data: string; -} - -export interface IContractResults { - items: IContractResultItem[]; -} - -export interface IContractResultItem { - hash: string; - nonce: number; - receiver: Address; - sender: Address; - data: string; - returnMessage: string; - logs: ITransactionLogs; - previousHash?: string; -} - -export interface IContractQueryResponse { - returnCode: IContractReturnCode; - returnMessage: string; - getReturnDataParts(): Buffer[]; -} - -export interface IContractReturnCode { - toString(): string; -} - -export interface ITransactionLogs { - address: Address; - events: ITransactionEvent[]; - - findSingleOrNoneEvent( - identifier: string, - predicate?: (event: ITransactionEvent) => boolean, - ): ITransactionEvent | undefined; -} - -export interface ITransactionEvent { - readonly address: Address; - readonly identifier: string; - readonly topics: ITransactionEventTopic[]; - readonly data: string; - // See https://github.com/multiversx/mx-sdk-js-network-providers/blob/v2.4.0/src/transactionEvents.ts#L13 - readonly dataPayload?: { valueOf(): Uint8Array }; - readonly additionalData?: { valueOf(): Uint8Array }[]; - - findFirstOrNoneTopic(predicate: (topic: ITransactionEventTopic) => boolean): ITransactionEventTopic | undefined; - getLastTopic(): ITransactionEventTopic; -} - -export interface ITransactionEventTopic { - toString(): string; - hex(): string; -} diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 0a147d212..1d8883084 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -2,7 +2,6 @@ import { Address } from "../address"; import { AsyncTimer } from "../asyncTimer"; import * as errors from "../errors"; import { ErrMock } from "../errors"; -import { IAccountOnNetwork } from "../interfaceOfNetwork"; import { AccountOnNetwork, DefinitionOfFungibleTokenOnNetwork, @@ -123,7 +122,7 @@ export class MockNetworkProvider implements INetworkProvider { throw new Error("Method not implemented."); } - mockUpdateAccount(address: Address, mutate: (item: IAccountOnNetwork) => void) { + mockUpdateAccount(address: Address, mutate: (item: AccountOnNetwork) => void) { let account = this.accounts.get(address.toBech32()); if (account) { mutate(account); diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index ab0c9a740..7cb88fb9d 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -2,7 +2,7 @@ import * as fs from "fs"; import * as path from "path"; import { Account } from "../accounts"; import { Address } from "../address"; -import { IAccountOnNetwork } from "../interfaceOfNetwork"; +import { AccountOnNetwork } from "../networkProviders"; import { getAxios } from "../utils"; import { UserSecretKey, UserSigner } from "./../wallet"; import { readTestFile } from "./files"; @@ -11,7 +11,7 @@ import { isOnBrowserTests } from "./utils"; export const DummyMnemonicOf12Words = "matter trumpet twenty parade fame north lift sail valve salon foster cinnamon"; interface IAccountFetcher { - getAccount(address: Address): Promise; + getAccount(address: Address): Promise; } export async function loadAndSyncTestWallets(provider: IAccountFetcher): Promise> { diff --git a/src/transaction.ts b/src/transaction.ts index c6e68505c..a792173e6 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,8 +1,7 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; -import { IPlainTransactionObject } from "./interface"; -import { INetworkConfig } from "./interfaceOfNetwork"; +import { INetworkConfig, IPlainTransactionObject } from "./interface"; import { interpretSignatureAsBuffer } from "./signature"; import { TransactionComputer } from "./transactionComputer"; diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index 4384c621b..1d204046e 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -6,7 +6,7 @@ import { TRANSACTION_OPTIONS_TX_HASH_SIGN, } from "./constants"; import * as errors from "./errors"; -import { INetworkConfig } from "./interfaceOfNetwork"; +import { INetworkConfig } from "./interface"; import { ProtoSerializer } from "./proto"; import { Transaction } from "./transaction"; diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index 98bf20739..3442b117b 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -7,12 +7,12 @@ import { ErrIsCompletedFieldIsMissingOnTransaction, } from "./errors"; import { ITransactionFetcher } from "./interface"; -import { ITransactionStatus } from "./interfaceOfNetwork"; import { Logger } from "./logger"; import { TransactionEvent } from "./transactionEvents"; import { TransactionOnNetwork } from "./transactionOnNetwork"; +import { TransactionStatus } from "./transactionStatus"; -export type PredicateIsAwaitedStatus = (status: ITransactionStatus) => boolean; +export type PredicateIsAwaitedStatus = (status: TransactionStatus) => boolean; /** * Internal interface: a transaction, as seen from the perspective of a {@link TransactionWatcher}. @@ -29,7 +29,7 @@ export class TransactionWatcher { static DefaultTimeout: number = TransactionWatcher.DefaultPollingInterval * 15; static DefaultPatience: number = 0; - static NoopOnStatusReceived = (_: ITransactionStatus) => {}; + static NoopOnStatusReceived = (_: TransactionStatus) => {}; protected readonly fetcher: ITransactionFetcher; protected readonly pollingIntervalMilliseconds: number; From 5cc582fdd9238fac0202337d5d2835493c5535b6 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 14:41:03 +0200 Subject: [PATCH 155/214] Add core folder --- src/abi/argSerializer.ts | 2 +- src/abi/argumentErrorContext.ts | 2 +- src/abi/codec/address.ts | 2 +- src/abi/codec/binary.spec.ts | 13 +++-- src/abi/codec/binary.ts | 4 +- src/abi/codec/boolean.ts | 2 +- src/abi/codec/option.ts | 2 +- src/abi/codec/utils.ts | 2 +- src/abi/function.ts | 2 +- src/abi/interaction.local.net.spec.ts | 8 +-- src/abi/interaction.spec.ts | 10 ++-- src/abi/interaction.ts | 12 ++--- src/abi/interface.ts | 4 +- src/abi/nativeSerializer.spec.ts | 6 +-- src/abi/nativeSerializer.ts | 6 +-- src/abi/query.spec.ts | 2 +- src/abi/query.ts | 2 +- src/abi/smartContract.local.net.spec.ts | 8 +-- src/abi/smartContract.spec.ts | 8 +-- src/abi/smartContract.ts | 14 ++--- .../smartContractResults.local.net.spec.ts | 6 +-- src/abi/typesystem/abiRegistry.ts | 4 +- src/abi/typesystem/address.ts | 2 +- src/abi/typesystem/algebraic.ts | 2 +- src/abi/typesystem/composite.ts | 2 +- src/abi/typesystem/enum.spec.ts | 8 +-- src/abi/typesystem/enum.ts | 4 +- src/abi/typesystem/explicit-enum.ts | 2 +- src/abi/typesystem/factory.spec.ts | 6 +-- src/abi/typesystem/factory.ts | 2 +- src/abi/typesystem/fields.ts | 2 +- src/abi/typesystem/generic.ts | 4 +- src/abi/typesystem/genericArray.ts | 2 +- src/abi/typesystem/matchers.ts | 2 +- src/abi/typesystem/numerical.ts | 2 +- src/abi/typesystem/struct.spec.ts | 6 +-- src/abi/typesystem/struct.ts | 2 +- src/abi/typesystem/tuple.ts | 2 +- .../typesystem/typeExpressionParser.spec.ts | 2 +- src/abi/typesystem/typeExpressionParser.ts | 2 +- src/abi/typesystem/typeMapper.ts | 2 +- src/abi/typesystem/types.spec.ts | 6 +-- src/abi/typesystem/types.ts | 4 +- src/accountManagement/accountController.ts | 6 +-- .../accountTransactionsFactory.spec.ts | 3 +- .../accountTransactionsFactory.ts | 6 +-- src/accountManagement/resources.ts | 2 +- src/accounts/account.spec.ts | 4 +- src/accounts/account.ts | 8 +-- src/accounts/interfaces.ts | 2 +- src/{ => core}/address.spec.ts | 0 src/{ => core}/address.ts | 2 +- src/{ => core}/asyncTimer.spec.ts | 0 src/{ => core}/asyncTimer.ts | 0 src/{ => core}/compatibility.ts | 0 src/{ => core}/config.ts | 0 src/{ => core}/constants.ts | 0 src/{ => core}/errors.ts | 0 src/{ => core}/globals.ts | 0 src/{ => core}/index.ts | 26 ++++++---- src/{ => core}/interface.ts | 0 src/{ => core}/logger.ts | 0 src/{ => core}/message.spec.ts | 4 +- src/{ => core}/message.ts | 0 src/{ => core}/networkParams.spec.ts | 0 src/{ => core}/networkParams.ts | 0 src/{ => core}/reflection.ts | 0 src/{ => core}/signature.ts | 0 src/{ => core}/smartContractQuery.ts | 0 src/{ => core}/tokenTransfersDataBuilder.ts | 2 +- src/{ => core}/tokens.spec.ts | 0 src/{ => core}/tokens.ts | 0 src/{ => core}/transaction.local.net.spec.ts | 8 +-- src/{ => core}/transaction.spec.ts | 6 +-- src/{ => core}/transaction.ts | 0 src/{ => core}/transactionBuilder.ts | 0 src/{ => core}/transactionComputer.ts | 2 +- src/{ => core}/transactionEvents.ts | 0 src/{ => core}/transactionLogs.ts | 0 src/{ => core}/transactionOnNetwork.ts | 2 +- src/{ => core}/transactionPayload.ts | 0 src/{ => core}/transactionStatus.ts | 0 src/{ => core}/transactionWatcher.spec.ts | 2 +- src/{ => core}/transactionWatcher.ts | 0 src/{ => core}/transactionsFactoryConfig.ts | 0 src/{ => core}/utils.codec.spec.ts | 0 src/{ => core}/utils.codec.ts | 2 +- src/{ => core}/utils.ts | 0 src/delegation/delegationController.ts | 10 ++-- .../delegationTransactionsFactory.spec.ts | 6 +-- .../delegationTransactionsFactory.ts | 10 ++-- ...elegationTransactionsOutcomeParser.spec.ts | 6 +-- .../delegationTransactionsOutcomeParser.ts | 8 +-- src/delegation/resources.ts | 2 +- src/entrypoints/entrypoints.spec.ts | 3 +- src/entrypoints/entrypoints.ts | 16 +++--- .../accountAwaiter.dev.net.spec.ts | 4 +- src/networkProviders/accountAwaiter.ts | 4 +- src/networkProviders/accounts.ts | 2 +- .../apiNetworkProvider.dev.net.spec.ts | 16 +++--- src/networkProviders/apiNetworkProvider.ts | 20 ++++---- src/networkProviders/constants.ts | 2 +- src/networkProviders/contractQueryRequest.ts | 2 +- src/networkProviders/contractResults.ts | 4 +- src/networkProviders/interface.ts | 12 ++--- src/networkProviders/pairs.ts | 2 +- .../providers.dev.net.spec.ts | 5 +- .../proxyNetworkProvider.dev.net.spec.ts | 16 +++--- src/networkProviders/proxyNetworkProvider.ts | 20 ++++---- src/networkProviders/resources.ts | 6 +-- src/networkProviders/tokenDefinitions.ts | 2 +- src/networkProviders/tokens.ts | 4 +- src/networkProviders/transactionReceipt.ts | 2 +- src/proto/serializer.spec.ts | 4 +- src/proto/serializer.ts | 8 +-- src/relayed/relayedController.ts | 6 +-- .../relayedTransactionsFactory.spec.ts | 5 +- src/relayed/relayedTransactionsFactory.ts | 6 +-- src/relayed/resources.ts | 2 +- src/smartContracts/resources.ts | 4 +- .../smartContractController.spec.ts | 3 +- src/smartContracts/smartContractController.ts | 14 ++--- .../smartContractTransactionsFactory.spec.ts | 51 +++++++++---------- .../smartContractTransactionsFactory.ts | 18 +++---- ...tContractTransactionsOutcomeParser.spec.ts | 5 +- .../smartContractTransactionsOutcomeParser.ts | 10 ++-- src/testutils/mockNetworkProvider.ts | 20 ++++---- src/testutils/utils.ts | 8 +-- src/testutils/wallets.ts | 4 +- src/tokenManagement/resources.ts | 2 +- .../tokenManagementController.ts | 10 ++-- .../tokenManagementTransactionFactory.spec.ts | 5 +- .../tokenManagementTransactionsFactory.ts | 12 ++--- ...anagementTransactionsOutcomeParser.spec.ts | 14 ++--- ...okenManagementTransactionsOutcomeParser.ts | 8 +-- src/tokenOperations/codec.ts | 4 +- .../resources.spec.ts | 4 +- src/transactionsOutcomeParsers/resources.ts | 8 +-- .../transactionEventsParser.spec.ts | 5 +- .../transactionEventsParser.ts | 2 +- src/transfers/resources.ts | 4 +- .../transferTransactionsFactory.spec.ts | 8 ++- src/transfers/transferTransactionsFactory.ts | 14 ++--- src/transfers/transfersControllers.ts | 6 +-- src/wallet/assertions.ts | 2 +- src/wallet/crypto/decryptor.ts | 2 +- src/wallet/keypair.spec.ts | 2 +- src/wallet/mnemonic.ts | 2 +- src/wallet/pem.spec.ts | 2 +- src/wallet/pem.ts | 2 +- src/wallet/userKeys.ts | 2 +- src/wallet/userSigner.ts | 4 +- src/wallet/userVerifier.ts | 2 +- src/wallet/userWallet.ts | 6 +-- src/wallet/users.spec.ts | 4 +- src/wallet/validatorKeys.ts | 2 +- src/wallet/validatorSigner.ts | 2 +- 157 files changed, 371 insertions(+), 395 deletions(-) rename src/{ => core}/address.spec.ts (100%) rename src/{ => core}/address.ts (99%) rename src/{ => core}/asyncTimer.spec.ts (100%) rename src/{ => core}/asyncTimer.ts (100%) rename src/{ => core}/compatibility.ts (100%) rename src/{ => core}/config.ts (100%) rename src/{ => core}/constants.ts (100%) rename src/{ => core}/errors.ts (100%) rename src/{ => core}/globals.ts (100%) rename src/{ => core}/index.ts (56%) rename src/{ => core}/interface.ts (100%) rename src/{ => core}/logger.ts (100%) rename src/{ => core}/message.spec.ts (97%) rename src/{ => core}/message.ts (100%) rename src/{ => core}/networkParams.spec.ts (100%) rename src/{ => core}/networkParams.ts (100%) rename src/{ => core}/reflection.ts (100%) rename src/{ => core}/signature.ts (100%) rename src/{ => core}/smartContractQuery.ts (100%) rename src/{ => core}/tokenTransfersDataBuilder.ts (97%) rename src/{ => core}/tokens.spec.ts (100%) rename src/{ => core}/tokens.ts (100%) rename src/{ => core}/transaction.local.net.spec.ts (96%) rename src/{ => core}/transaction.spec.ts (99%) rename src/{ => core}/transaction.ts (100%) rename src/{ => core}/transactionBuilder.ts (100%) rename src/{ => core}/transactionComputer.ts (99%) rename src/{ => core}/transactionEvents.ts (100%) rename src/{ => core}/transactionLogs.ts (100%) rename src/{ => core}/transactionOnNetwork.ts (99%) rename src/{ => core}/transactionPayload.ts (100%) rename src/{ => core}/transactionStatus.ts (100%) rename src/{ => core}/transactionWatcher.spec.ts (96%) rename src/{ => core}/transactionWatcher.ts (100%) rename src/{ => core}/transactionsFactoryConfig.ts (100%) rename src/{ => core}/utils.codec.spec.ts (100%) rename src/{ => core}/utils.codec.ts (95%) rename src/{ => core}/utils.ts (100%) diff --git a/src/abi/argSerializer.ts b/src/abi/argSerializer.ts index 4adf35a7f..7ede36894 100644 --- a/src/abi/argSerializer.ts +++ b/src/abi/argSerializer.ts @@ -1,4 +1,4 @@ -import { ARGUMENTS_SEPARATOR } from "../constants"; +import { ARGUMENTS_SEPARATOR } from "../core/constants"; import { BinaryCodec } from "./codec"; import { Type, TypedValue, U32Type, U32Value } from "./typesystem"; import { OptionalType, OptionalValue } from "./typesystem/algebraic"; diff --git a/src/abi/argumentErrorContext.ts b/src/abi/argumentErrorContext.ts index 661f62b22..bef4d74a6 100644 --- a/src/abi/argumentErrorContext.ts +++ b/src/abi/argumentErrorContext.ts @@ -1,4 +1,4 @@ -import { ErrInvalidArgument } from "../errors"; +import { ErrInvalidArgument } from "../core/errors"; import { EndpointParameterDefinition, Type } from "./typesystem"; export class ArgumentErrorContext { diff --git a/src/abi/codec/address.ts b/src/abi/codec/address.ts index befe22ff4..0772922f9 100644 --- a/src/abi/codec/address.ts +++ b/src/abi/codec/address.ts @@ -1,4 +1,4 @@ -import { Address } from "../../address"; +import { Address } from "../../core/address"; import { AddressValue } from "../typesystem"; export class AddressBinaryCodec { diff --git a/src/abi/codec/binary.spec.ts b/src/abi/codec/binary.spec.ts index 8e6f92eca..983196a55 100644 --- a/src/abi/codec/binary.spec.ts +++ b/src/abi/codec/binary.spec.ts @@ -1,7 +1,7 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { Address } from "../../address"; -import * as errors from "../../errors"; +import { Address } from "../../core/address"; +import * as errors from "../../core/errors"; import { AddressType, AddressValue, @@ -13,10 +13,16 @@ import { BigUIntValue, BooleanType, BooleanValue, + BytesType, + BytesValue, EnumType, EnumValue, EnumVariantDefinition, + ExplicitEnumType, + ExplicitEnumValue, + ExplicitEnumVariantDefinition, Field, + FieldDefinition, I16Type, I16Value, I32Type, @@ -45,9 +51,6 @@ import { U8Type, U8Value, } from "../typesystem"; -import { BytesType, BytesValue } from "../typesystem/bytes"; -import { ExplicitEnumType, ExplicitEnumValue, ExplicitEnumVariantDefinition } from "../typesystem/explicit-enum"; -import { FieldDefinition } from "../typesystem/fields"; import { BinaryCodec, BinaryCodecConstraints } from "./binary"; import { isMsbOne } from "./utils"; diff --git a/src/abi/codec/binary.ts b/src/abi/codec/binary.ts index bd6be3ad3..17a41d8b4 100644 --- a/src/abi/codec/binary.ts +++ b/src/abi/codec/binary.ts @@ -1,5 +1,5 @@ -import * as errors from "../../errors"; -import { guardTrue } from "../../utils"; +import * as errors from "../../core/errors"; +import { guardTrue } from "../../core/utils"; import { ArrayVec, ArrayVecType, diff --git a/src/abi/codec/boolean.ts b/src/abi/codec/boolean.ts index d76184a70..5023bf304 100644 --- a/src/abi/codec/boolean.ts +++ b/src/abi/codec/boolean.ts @@ -1,4 +1,4 @@ -import * as errors from "../../errors"; +import * as errors from "../../core/errors"; import { BooleanValue } from "../typesystem"; /** diff --git a/src/abi/codec/option.ts b/src/abi/codec/option.ts index 37cdc58ef..af1d7c5f7 100644 --- a/src/abi/codec/option.ts +++ b/src/abi/codec/option.ts @@ -1,4 +1,4 @@ -import * as errors from "../../errors"; +import * as errors from "../../core/errors"; import { OptionValue, Type } from "../typesystem"; import { BinaryCodec } from "./binary"; diff --git a/src/abi/codec/utils.ts b/src/abi/codec/utils.ts index a1ce1225d..928d32d30 100644 --- a/src/abi/codec/utils.ts +++ b/src/abi/codec/utils.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import { numberToPaddedHex } from "../../utils.codec"; +import { numberToPaddedHex } from "../../core/utils.codec"; /** * Returns whether the most significant bit of a given byte (within a buffer) is 1. diff --git a/src/abi/function.ts b/src/abi/function.ts index b8547e46a..6648ef757 100644 --- a/src/abi/function.ts +++ b/src/abi/function.ts @@ -1,4 +1,4 @@ -import * as errors from "../errors"; +import * as errors from "../core/errors"; /** * A function of a Smart Contract, as an abstraction. diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 44fe1a1ad..37453e9aa 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -1,6 +1,10 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { promises } from "fs"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { TransactionWatcher } from "../core/transactionWatcher"; import { SmartContractController, SmartContractTransactionsFactory, @@ -8,10 +12,6 @@ import { } from "../smartContracts"; import { loadAbiRegistry, loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; -import { TransactionWatcher } from "../transactionWatcher"; import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; import { ManagedDecimalValue } from "./typesystem"; diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 1741424f1..ac61e6fc4 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -1,7 +1,10 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { Address } from "../address"; -import { SmartContractQueryResponse } from "../smartContractQuery"; +import { Address } from "../core/address"; +import { SmartContractQueryResponse } from "../core/smartContractQuery"; +import { Token, TokenTransfer } from "../core/tokens"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; import { SmartContractController } from "../smartContracts"; import { loadAbiRegistry, @@ -10,9 +13,6 @@ import { setupUnitTestWatcherTimeouts, TestWallet, } from "../testutils"; -import { Token, TokenTransfer } from "../tokens"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index b9ac422c4..e4b3a27ce 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -1,11 +1,11 @@ import { Account } from "../accounts"; -import { Address } from "../address"; -import { Compatibility } from "../compatibility"; -import { TRANSACTION_VERSION_DEFAULT } from "../constants"; +import { Address } from "../core/address"; +import { Compatibility } from "../core/compatibility"; +import { TRANSACTION_VERSION_DEFAULT } from "../core/constants"; +import { TokenTransfer } from "../core/tokens"; +import { Transaction } from "../core/transaction"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { SmartContractTransactionsFactory } from "../smartContracts"; -import { TokenTransfer } from "../tokens"; -import { Transaction } from "../transaction"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { ContractFunction } from "./function"; import { CallArguments } from "./interface"; import { Query } from "./query"; diff --git a/src/abi/interface.ts b/src/abi/interface.ts index 0f2b54e5d..7502b5623 100644 --- a/src/abi/interface.ts +++ b/src/abi/interface.ts @@ -1,5 +1,5 @@ -import { Address } from "../address"; -import { Transaction } from "../transaction"; +import { Address } from "../core/address"; +import { Transaction } from "../core/transaction"; import { ReturnCode } from "./returnCode"; import { TypedValue } from "./typesystem"; diff --git a/src/abi/nativeSerializer.spec.ts b/src/abi/nativeSerializer.spec.ts index 060ee3a8d..985860192 100644 --- a/src/abi/nativeSerializer.spec.ts +++ b/src/abi/nativeSerializer.spec.ts @@ -1,7 +1,6 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { Address } from "../address"; -import { ErrInvalidArgument } from "../errors"; +import { Address, ErrInvalidArgument } from "../core"; import { NativeSerializer } from "./nativeSerializer"; import { AbiRegistry, @@ -10,6 +9,8 @@ import { BigUIntType, BooleanType, BooleanValue, + BytesType, + BytesValue, CompositeType, CompositeValue, EndpointDefinition, @@ -34,7 +35,6 @@ import { VariadicType, VariadicValue, } from "./typesystem"; -import { BytesType, BytesValue } from "./typesystem/bytes"; describe("test native serializer", () => { it("should perform type inference", async () => { diff --git a/src/abi/nativeSerializer.ts b/src/abi/nativeSerializer.ts index 0632d97a0..5ea5dc133 100644 --- a/src/abi/nativeSerializer.ts +++ b/src/abi/nativeSerializer.ts @@ -1,8 +1,8 @@ /* eslint-disable @typescript-eslint/no-namespace */ import BigNumber from "bignumber.js"; -import { Address } from "../address"; -import { ErrInvalidArgument } from "../errors"; -import { numberToPaddedHex } from "../utils.codec"; +import { Address } from "../core/address"; +import { ErrInvalidArgument } from "../core/errors"; +import { numberToPaddedHex } from "../core/utils.codec"; import { ArgumentErrorContext } from "./argumentErrorContext"; import { AddressType, diff --git a/src/abi/query.spec.ts b/src/abi/query.spec.ts index b9e198cbc..10319f9fb 100644 --- a/src/abi/query.spec.ts +++ b/src/abi/query.spec.ts @@ -1,6 +1,6 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { Address } from "../address"; +import { Address } from "../core/address"; import { ContractFunction } from "./function"; import { Query } from "./query"; import { BigUIntValue, U32Value } from "./typesystem"; diff --git a/src/abi/query.ts b/src/abi/query.ts index 93e3e6091..07e44c3e1 100644 --- a/src/abi/query.ts +++ b/src/abi/query.ts @@ -1,4 +1,4 @@ -import { Address } from "../address"; +import { Address } from "../core/address"; import { ArgSerializer } from "./argSerializer"; import { IContractFunction } from "./interface"; import { TypedValue } from "./typesystem"; diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 559108a85..459cf6cf7 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -1,6 +1,9 @@ import { assert } from "chai"; import { promises } from "fs"; -import { Logger } from "../logger"; +import { Logger } from "../core/logger"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { TransactionWatcher } from "../core/transactionWatcher"; import { SmartContractController, SmartContractTransactionsFactory, @@ -9,9 +12,6 @@ import { import { stringifyBigIntJSON } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { loadTestWallets, TestWallet } from "../testutils/wallets"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; -import { TransactionWatcher } from "../transactionWatcher"; import { decodeUnsignedNumber } from "./codec"; import { SmartContract } from "./smartContract"; import { diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index 5dd1ddc22..c8f264093 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -1,5 +1,8 @@ import { assert } from "chai"; -import { Address } from "../address"; +import { Address } from "../core/address"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionStatus } from "../core/transactionStatus"; +import { TransactionWatcher } from "../core/transactionWatcher"; import { loadTestWallets, MarkCompleted, @@ -8,9 +11,6 @@ import { TestWallet, Wait, } from "../testutils"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionStatus } from "../transactionStatus"; -import { TransactionWatcher } from "../transactionWatcher"; import { Code } from "./code"; import { ContractFunction } from "./function"; import { SmartContract } from "./smartContract"; diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 322132c50..35605ea5c 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -1,10 +1,10 @@ -import { Address, AddressComputer } from "../address"; -import { Compatibility } from "../compatibility"; -import { TRANSACTION_MIN_GAS_PRICE } from "../constants"; -import { ErrContractHasNoAddress } from "../errors"; -import { Transaction } from "../transaction"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; -import { guardValueIsSet } from "../utils"; +import { Address, AddressComputer } from "../core/address"; +import { Compatibility } from "../core/compatibility"; +import { TRANSACTION_MIN_GAS_PRICE } from "../core/constants"; +import { ErrContractHasNoAddress } from "../core/errors"; +import { Transaction } from "../core/transaction"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { guardValueIsSet } from "../core/utils"; import { SmartContractTransactionsFactory } from "./../smartContracts/smartContractTransactionsFactory"; import { CodeMetadata } from "./codeMetadata"; import { ContractFunction } from "./function"; diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 297034536..cb448dc38 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -1,11 +1,11 @@ import { assert } from "chai"; import { promises } from "fs"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { TransactionWatcher } from "../core/transactionWatcher"; import { SmartContractTransactionsFactory, SmartContractTransactionsOutcomeParser } from "../smartContracts"; import { loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; -import { TransactionWatcher } from "../transactionWatcher"; import { ContractFunction } from "./function"; import { SmartContract } from "./smartContract"; diff --git a/src/abi/typesystem/abiRegistry.ts b/src/abi/typesystem/abiRegistry.ts index 60a6c46ff..984f45659 100644 --- a/src/abi/typesystem/abiRegistry.ts +++ b/src/abi/typesystem/abiRegistry.ts @@ -1,5 +1,5 @@ -import * as errors from "../../errors"; -import { guardValueIsSetWithMessage } from "../../utils"; +import * as errors from "../../core/errors"; +import { guardValueIsSetWithMessage } from "../../core/utils"; import { EndpointDefinition, EndpointParameterDefinition } from "./endpoint"; import { EnumType } from "./enum"; import { EventDefinition, EventTopicDefinition } from "./event"; diff --git a/src/abi/typesystem/address.ts b/src/abi/typesystem/address.ts index 7fc34fe90..c7e0e4b1e 100644 --- a/src/abi/typesystem/address.ts +++ b/src/abi/typesystem/address.ts @@ -1,4 +1,4 @@ -import { Address } from "../../address"; +import { Address } from "../../core/address"; import { PrimitiveType, PrimitiveValue } from "./types"; export class AddressType extends PrimitiveType { diff --git a/src/abi/typesystem/algebraic.ts b/src/abi/typesystem/algebraic.ts index 91225dee0..249ba5003 100644 --- a/src/abi/typesystem/algebraic.ts +++ b/src/abi/typesystem/algebraic.ts @@ -1,4 +1,4 @@ -import { guardValueIsSet } from "../../utils"; +import { guardValueIsSet } from "../../core/utils"; import { NullType, Type, TypeCardinality, TypedValue } from "./types"; /** diff --git a/src/abi/typesystem/composite.ts b/src/abi/typesystem/composite.ts index 6892a9a1f..27ed7a88a 100644 --- a/src/abi/typesystem/composite.ts +++ b/src/abi/typesystem/composite.ts @@ -1,4 +1,4 @@ -import { guardLength } from "../../utils"; +import { guardLength } from "../../core/utils"; import { Type, TypeCardinality, TypedValue } from "./types"; export class CompositeType extends Type { diff --git a/src/abi/typesystem/enum.spec.ts b/src/abi/typesystem/enum.spec.ts index 50ede8e21..7002a3db4 100644 --- a/src/abi/typesystem/enum.spec.ts +++ b/src/abi/typesystem/enum.spec.ts @@ -1,10 +1,10 @@ -import * as errors from "../../errors"; +import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { U8Type, U8Value } from "./numerical"; -import { Field, FieldDefinition } from "./fields"; +import * as errors from "../../core/errors"; import { EnumType, EnumValue, EnumVariantDefinition } from "./enum"; +import { Field, FieldDefinition } from "./fields"; +import { U8Type, U8Value } from "./numerical"; import { StringType, StringValue } from "./string"; -import BigNumber from "bignumber.js"; describe("test enums", () => { it("should get fields", () => { diff --git a/src/abi/typesystem/enum.ts b/src/abi/typesystem/enum.ts index a0a2b24d6..424a550a2 100644 --- a/src/abi/typesystem/enum.ts +++ b/src/abi/typesystem/enum.ts @@ -1,5 +1,5 @@ -import { ErrMissingFieldOnEnum } from "../../errors"; -import { guardTrue, guardValueIsSet } from "../../utils"; +import { ErrMissingFieldOnEnum } from "../../core/errors"; +import { guardTrue, guardValueIsSet } from "../../core/utils"; import { Field, FieldDefinition, Fields } from "./fields"; import { CustomType, TypedValue } from "./types"; diff --git a/src/abi/typesystem/explicit-enum.ts b/src/abi/typesystem/explicit-enum.ts index 264e18fa1..ac93c1fed 100644 --- a/src/abi/typesystem/explicit-enum.ts +++ b/src/abi/typesystem/explicit-enum.ts @@ -1,4 +1,4 @@ -import { guardValueIsSet } from "../../utils"; +import { guardValueIsSet } from "../../core/utils"; import { CustomType, TypedValue } from "./types"; export class ExplicitEnumType extends CustomType { diff --git a/src/abi/typesystem/factory.spec.ts b/src/abi/typesystem/factory.spec.ts index 8645a16cd..368ffadee 100644 --- a/src/abi/typesystem/factory.spec.ts +++ b/src/abi/typesystem/factory.spec.ts @@ -1,9 +1,9 @@ import { assert } from "chai"; -import { TokenIdentifierType } from "./tokenIdentifier"; -import { Address } from "../../address"; +import { Address } from "../../core/address"; +import { AddressType } from "./address"; import { createListOfAddresses, createListOfTokenIdentifiers } from "./factory"; import { ListType } from "./generic"; -import { AddressType } from "./address"; +import { TokenIdentifierType } from "./tokenIdentifier"; describe("test factory", () => { it("should create lists of addresses", () => { diff --git a/src/abi/typesystem/factory.ts b/src/abi/typesystem/factory.ts index 651de575e..c14319923 100644 --- a/src/abi/typesystem/factory.ts +++ b/src/abi/typesystem/factory.ts @@ -1,4 +1,4 @@ -import { Address } from "../../address"; +import { Address } from "../../core/address"; import { AddressValue } from "./address"; import { List } from "./generic"; import { TokenIdentifierValue } from "./tokenIdentifier"; diff --git a/src/abi/typesystem/fields.ts b/src/abi/typesystem/fields.ts index d8953cce4..1a546a1e2 100644 --- a/src/abi/typesystem/fields.ts +++ b/src/abi/typesystem/fields.ts @@ -1,4 +1,4 @@ -import * as errors from "../../errors"; +import * as errors from "../../core/errors"; import { TypeExpressionParser } from "./typeExpressionParser"; import { Type, TypedValue } from "./types"; diff --git a/src/abi/typesystem/generic.ts b/src/abi/typesystem/generic.ts index cfce5eb15..410351f1c 100644 --- a/src/abi/typesystem/generic.ts +++ b/src/abi/typesystem/generic.ts @@ -1,6 +1,6 @@ -import { guardValueIsSet } from "../../utils"; +import { guardValueIsSet } from "../../core/utils"; import { CollectionOfTypedValues } from "./collections"; -import { Type, TypedValue, NullType, TypePlaceholder } from "./types"; +import { NullType, Type, TypedValue, TypePlaceholder } from "./types"; // TODO: Move to a new file, "genericOption.ts" export class OptionType extends Type { diff --git a/src/abi/typesystem/genericArray.ts b/src/abi/typesystem/genericArray.ts index ff353b84d..f5b56e88e 100644 --- a/src/abi/typesystem/genericArray.ts +++ b/src/abi/typesystem/genericArray.ts @@ -1,4 +1,4 @@ -import { guardLength, guardTrue } from "../../utils"; +import { guardLength, guardTrue } from "../../core/utils"; import { CollectionOfTypedValues } from "./collections"; import { Type, TypedValue } from "./types"; diff --git a/src/abi/typesystem/matchers.ts b/src/abi/typesystem/matchers.ts index a877a9660..2304619c0 100644 --- a/src/abi/typesystem/matchers.ts +++ b/src/abi/typesystem/matchers.ts @@ -1,4 +1,4 @@ -import * as errors from "../../errors"; +import * as errors from "../../core/errors"; import { AddressType, AddressValue } from "./address"; import { BooleanType, BooleanValue } from "./boolean"; import { BytesType, BytesValue } from "./bytes"; diff --git a/src/abi/typesystem/numerical.ts b/src/abi/typesystem/numerical.ts index 440600284..de2a97df0 100644 --- a/src/abi/typesystem/numerical.ts +++ b/src/abi/typesystem/numerical.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import * as errors from "../../errors"; +import * as errors from "../../core/errors"; import { PrimitiveType, PrimitiveValue } from "./types"; export class NumericalType extends PrimitiveType { diff --git a/src/abi/typesystem/struct.spec.ts b/src/abi/typesystem/struct.spec.ts index 36209019d..38de0a00d 100644 --- a/src/abi/typesystem/struct.spec.ts +++ b/src/abi/typesystem/struct.spec.ts @@ -1,9 +1,9 @@ -import * as errors from "../../errors"; import { assert } from "chai"; -import { BigUIntType, BigUIntValue, U32Type, U32Value } from "./numerical"; +import * as errors from "../../core/errors"; import { BytesType, BytesValue } from "./bytes"; -import { Struct, StructType } from "./struct"; import { Field, FieldDefinition } from "./fields"; +import { BigUIntType, BigUIntValue, U32Type, U32Value } from "./numerical"; +import { Struct, StructType } from "./struct"; import { TokenIdentifierType, TokenIdentifierValue } from "./tokenIdentifier"; describe("test structs", () => { diff --git a/src/abi/typesystem/struct.ts b/src/abi/typesystem/struct.ts index 94e367f8f..4d44a8c0e 100644 --- a/src/abi/typesystem/struct.ts +++ b/src/abi/typesystem/struct.ts @@ -1,4 +1,4 @@ -import { ErrMissingFieldOnStruct } from "../../errors"; +import { ErrMissingFieldOnStruct } from "../../core/errors"; import { Field, FieldDefinition, Fields } from "./fields"; import { CustomType, TypedValue } from "./types"; diff --git a/src/abi/typesystem/tuple.ts b/src/abi/typesystem/tuple.ts index f249913db..e52fe3c0f 100644 --- a/src/abi/typesystem/tuple.ts +++ b/src/abi/typesystem/tuple.ts @@ -1,4 +1,4 @@ -import * as errors from "../../errors"; +import * as errors from "../../core/errors"; import { Field, FieldDefinition } from "./fields"; import { Struct, StructType } from "./struct"; import { Type, TypedValue } from "./types"; diff --git a/src/abi/typesystem/typeExpressionParser.spec.ts b/src/abi/typesystem/typeExpressionParser.spec.ts index 0aa09ae2c..91065da00 100644 --- a/src/abi/typesystem/typeExpressionParser.spec.ts +++ b/src/abi/typesystem/typeExpressionParser.spec.ts @@ -1,5 +1,5 @@ import { assert } from "chai"; -import { ErrTypingSystem } from "../../errors"; +import { ErrTypingSystem } from "../../core"; import { TypeExpressionParser } from "./typeExpressionParser"; import { Type } from "./types"; diff --git a/src/abi/typesystem/typeExpressionParser.ts b/src/abi/typesystem/typeExpressionParser.ts index 0c61d502f..076f44a04 100644 --- a/src/abi/typesystem/typeExpressionParser.ts +++ b/src/abi/typesystem/typeExpressionParser.ts @@ -1,6 +1,6 @@ import { TypeFormula } from "../../abi/typeFormula"; import { TypeFormulaParser } from "../../abi/typeFormulaParser"; -import { ErrTypingSystem } from "../../errors"; +import { ErrTypingSystem } from "../../core/errors"; import { Type } from "./types"; export class TypeExpressionParser { diff --git a/src/abi/typesystem/typeMapper.ts b/src/abi/typesystem/typeMapper.ts index 8eebdf5f8..9a527495a 100644 --- a/src/abi/typesystem/typeMapper.ts +++ b/src/abi/typesystem/typeMapper.ts @@ -1,4 +1,4 @@ -import * as errors from "../../errors"; +import * as errors from "../../core/errors"; import { AddressType } from "./address"; import { OptionalType } from "./algebraic"; import { BooleanType } from "./boolean"; diff --git a/src/abi/typesystem/types.spec.ts b/src/abi/typesystem/types.spec.ts index eb77985aa..540183847 100644 --- a/src/abi/typesystem/types.spec.ts +++ b/src/abi/typesystem/types.spec.ts @@ -1,16 +1,16 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import * as errors from "../../errors"; +import * as errors from "../../core/errors"; import { AddressType } from "./address"; import { BooleanType } from "./boolean"; import { BytesType, BytesValue } from "./bytes"; import { OptionType } from "./generic"; +import { ManagedDecimalType } from "./managedDecimal"; +import { ManagedDecimalSignedType } from "./managedDecimalSigned"; import { I64Type, NumericalValue, U16Type, U32Type, U32Value } from "./numerical"; import { StringType } from "./string"; import { TypeExpressionParser } from "./typeExpressionParser"; import { NullType, PrimitiveType, Type } from "./types"; -import { ManagedDecimalType } from "./managedDecimal"; -import { ManagedDecimalSignedType } from "./managedDecimalSigned"; describe("test types", () => { let parser = new TypeExpressionParser(); diff --git a/src/abi/typesystem/types.ts b/src/abi/typesystem/types.ts index 792d66e4b..40f51f0ff 100644 --- a/src/abi/typesystem/types.ts +++ b/src/abi/typesystem/types.ts @@ -1,5 +1,5 @@ -import { getJavascriptPrototypesInHierarchy } from "../../reflection"; -import { guardTrue, guardValueIsSet } from "../../utils"; +import { getJavascriptPrototypesInHierarchy } from "../../core/reflection"; +import { guardTrue, guardValueIsSet } from "../../core/utils"; /** * An abstraction that represents a Type. Handles both generic and non-generic types. diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index a73b92b8f..f7a67eef6 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -1,7 +1,7 @@ import { IAccount } from "../accounts/interfaces"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; import { SaveKeyValueInput, SetGuardianInput } from "./resources"; diff --git a/src/accountManagement/accountTransactionsFactory.spec.ts b/src/accountManagement/accountTransactionsFactory.spec.ts index 43129eb6b..3067a0112 100644 --- a/src/accountManagement/accountTransactionsFactory.spec.ts +++ b/src/accountManagement/accountTransactionsFactory.spec.ts @@ -1,6 +1,5 @@ import { assert } from "chai"; -import { Address } from "../address"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; +import { Address, TransactionsFactoryConfig } from "../core"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; describe("test account transactions factory", function () { diff --git a/src/accountManagement/accountTransactionsFactory.ts b/src/accountManagement/accountTransactionsFactory.ts index 2cdac3c70..a87fd37ef 100644 --- a/src/accountManagement/accountTransactionsFactory.ts +++ b/src/accountManagement/accountTransactionsFactory.ts @@ -1,6 +1,6 @@ -import { Address } from "../address"; -import { Transaction } from "../transaction"; -import { TransactionBuilder } from "../transactionBuilder"; +import { Address } from "../core/address"; +import { Transaction } from "../core/transaction"; +import { TransactionBuilder } from "../core/transactionBuilder"; import { SaveKeyValueInput, SetGuardianInput } from "./resources"; interface IConfig { diff --git a/src/accountManagement/resources.ts b/src/accountManagement/resources.ts index 26d10786d..9f8c34f71 100644 --- a/src/accountManagement/resources.ts +++ b/src/accountManagement/resources.ts @@ -1,4 +1,4 @@ -import { Address } from "../address"; +import { Address } from "../core/address"; export type SetGuardianInput = { guardianAddress: Address; serviceID: string }; export type SaveKeyValueInput = { keyValuePairs: Map }; diff --git a/src/accounts/account.spec.ts b/src/accounts/account.spec.ts index 8ad106b5d..fa4c1992e 100644 --- a/src/accounts/account.spec.ts +++ b/src/accounts/account.spec.ts @@ -1,8 +1,6 @@ import { assert } from "chai"; import { resolve } from "path"; -import { Address } from "../address"; -import { Message } from "../message"; -import { Transaction } from "../transaction"; +import { Address, Message, Transaction } from "../core"; import { KeyPair, UserSecretKey } from "../wallet"; import { Account } from "./account"; diff --git a/src/accounts/account.ts b/src/accounts/account.ts index a52258765..7dcbfd935 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -1,9 +1,9 @@ import * as fs from "fs"; import { PathLike } from "fs"; -import { Message, MessageComputer, TransactionComputer } from ".."; -import { Address } from "../address"; -import { LibraryConfig } from "../config"; -import { Transaction } from "../transaction"; +import { Message, MessageComputer, TransactionComputer } from "../core"; +import { Address } from "../core/address"; +import { LibraryConfig } from "../core/config"; +import { Transaction } from "../core/transaction"; import { KeyPair, Mnemonic, UserPublicKey, UserSecretKey, UserSigner, UserWallet } from "../wallet"; import { UserPem } from "../wallet/userPem"; import { IAccount } from "./interfaces"; diff --git a/src/accounts/interfaces.ts b/src/accounts/interfaces.ts index 72001424d..b17f0d7ce 100644 --- a/src/accounts/interfaces.ts +++ b/src/accounts/interfaces.ts @@ -1,4 +1,4 @@ -import { Address } from "../address"; +import { Address } from "../core/address"; export interface IAccount { readonly address: Address; diff --git a/src/address.spec.ts b/src/core/address.spec.ts similarity index 100% rename from src/address.spec.ts rename to src/core/address.spec.ts diff --git a/src/address.ts b/src/core/address.ts similarity index 99% rename from src/address.ts rename to src/core/address.ts index 4b1327b4d..67f40554c 100644 --- a/src/address.ts +++ b/src/core/address.ts @@ -1,9 +1,9 @@ import * as bech32 from "bech32"; import BigNumber from "bignumber.js"; +import { bigIntToBuffer } from "../tokenOperations/codec"; import { LibraryConfig } from "./config"; import { CURRENT_NUMBER_OF_SHARDS_WITHOUT_META, METACHAIN_ID, WasmVirtualMachine } from "./constants"; import * as errors from "./errors"; -import { bigIntToBuffer } from "./tokenOperations/codec"; const createKeccakHash = require("keccak"); /** diff --git a/src/asyncTimer.spec.ts b/src/core/asyncTimer.spec.ts similarity index 100% rename from src/asyncTimer.spec.ts rename to src/core/asyncTimer.spec.ts diff --git a/src/asyncTimer.ts b/src/core/asyncTimer.ts similarity index 100% rename from src/asyncTimer.ts rename to src/core/asyncTimer.ts diff --git a/src/compatibility.ts b/src/core/compatibility.ts similarity index 100% rename from src/compatibility.ts rename to src/core/compatibility.ts diff --git a/src/config.ts b/src/core/config.ts similarity index 100% rename from src/config.ts rename to src/core/config.ts diff --git a/src/constants.ts b/src/core/constants.ts similarity index 100% rename from src/constants.ts rename to src/core/constants.ts diff --git a/src/errors.ts b/src/core/errors.ts similarity index 100% rename from src/errors.ts rename to src/core/errors.ts diff --git a/src/globals.ts b/src/core/globals.ts similarity index 100% rename from src/globals.ts rename to src/core/globals.ts diff --git a/src/index.ts b/src/core/index.ts similarity index 56% rename from src/index.ts rename to src/core/index.ts index 64b8861f7..9e402555e 100644 --- a/src/index.ts +++ b/src/core/index.ts @@ -6,30 +6,34 @@ require("./globals"); -export * from "./abi"; -export * from "./accountManagement"; -export * from "./accounts"; +export * from "../abi"; +export * from "../accountManagement"; +export * from "../accounts"; +export * from "../delegation"; +export * from "../entrypoints"; +export * from "../networkProviders"; +export * from "../relayed"; +export * from "../tokenManagement"; +export * from "../transactionsOutcomeParsers"; +export * from "../transfers"; +export * from "../wallet"; export * from "./address"; export * from "./asyncTimer"; export * from "./config"; -export * from "./delegation"; -export * from "./entrypoints"; export * from "./errors"; export * from "./interface"; export * from "./logger"; export * from "./message"; export * from "./networkParams"; -export * from "./networkProviders"; -export * from "./relayed"; -export * from "./tokenManagement"; +export * from "./smartContractQuery"; export * from "./tokens"; export * from "./transaction"; export * from "./transactionComputer"; +export * from "./transactionEvents"; +export * from "./transactionLogs"; export * from "./transactionOnNetwork"; export * from "./transactionPayload"; -export * from "./transactionsOutcomeParsers"; +export * from "./transactionsFactoryConfig"; export * from "./transactionStatus"; export * from "./transactionWatcher"; -export * from "./transfers"; export * from "./utils"; -export * from "./wallet"; diff --git a/src/interface.ts b/src/core/interface.ts similarity index 100% rename from src/interface.ts rename to src/core/interface.ts diff --git a/src/logger.ts b/src/core/logger.ts similarity index 100% rename from src/logger.ts rename to src/core/logger.ts diff --git a/src/message.spec.ts b/src/core/message.spec.ts similarity index 97% rename from src/message.spec.ts rename to src/core/message.spec.ts index c7809d835..8fb62d5c2 100644 --- a/src/message.spec.ts +++ b/src/core/message.spec.ts @@ -1,8 +1,8 @@ -import { UserVerifier } from "./wallet"; import { assert } from "chai"; +import { TestWallet, loadTestWallets } from "../testutils"; +import { UserVerifier } from "../wallet"; import { DEFAULT_MESSAGE_VERSION, SDK_JS_SIGNER, UNKNOWN_SIGNER } from "./constants"; import { Message, MessageComputer } from "./message"; -import { TestWallet, loadTestWallets } from "./testutils"; describe("test message", () => { let alice: TestWallet; diff --git a/src/message.ts b/src/core/message.ts similarity index 100% rename from src/message.ts rename to src/core/message.ts diff --git a/src/networkParams.spec.ts b/src/core/networkParams.spec.ts similarity index 100% rename from src/networkParams.spec.ts rename to src/core/networkParams.spec.ts diff --git a/src/networkParams.ts b/src/core/networkParams.ts similarity index 100% rename from src/networkParams.ts rename to src/core/networkParams.ts diff --git a/src/reflection.ts b/src/core/reflection.ts similarity index 100% rename from src/reflection.ts rename to src/core/reflection.ts diff --git a/src/signature.ts b/src/core/signature.ts similarity index 100% rename from src/signature.ts rename to src/core/signature.ts diff --git a/src/smartContractQuery.ts b/src/core/smartContractQuery.ts similarity index 100% rename from src/smartContractQuery.ts rename to src/core/smartContractQuery.ts diff --git a/src/tokenTransfersDataBuilder.ts b/src/core/tokenTransfersDataBuilder.ts similarity index 97% rename from src/tokenTransfersDataBuilder.ts rename to src/core/tokenTransfersDataBuilder.ts index e2a2b2c17..3bdcf4e39 100644 --- a/src/tokenTransfersDataBuilder.ts +++ b/src/core/tokenTransfersDataBuilder.ts @@ -1,4 +1,4 @@ -import { AddressValue, ArgSerializer, BigUIntValue, TokenIdentifierValue, TypedValue, U32Value } from "./abi"; +import { AddressValue, ArgSerializer, BigUIntValue, TokenIdentifierValue, TypedValue, U32Value } from "../abi"; import { Address } from "./address"; import { TokenComputer, TokenTransfer } from "./tokens"; diff --git a/src/tokens.spec.ts b/src/core/tokens.spec.ts similarity index 100% rename from src/tokens.spec.ts rename to src/core/tokens.spec.ts diff --git a/src/tokens.ts b/src/core/tokens.ts similarity index 100% rename from src/tokens.ts rename to src/core/tokens.ts diff --git a/src/transaction.local.net.spec.ts b/src/core/transaction.local.net.spec.ts similarity index 96% rename from src/transaction.local.net.spec.ts rename to src/core/transaction.local.net.spec.ts index 07871ed76..3003f9c6d 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/core/transaction.local.net.spec.ts @@ -1,15 +1,15 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; +import { INetworkProvider } from "../networkProviders/interface"; +import { loadTestWallets, stringifyBigIntJSON, TestWallet } from "../testutils"; +import { createLocalnetProvider } from "../testutils/networkProviders"; +import { TransferTransactionsFactory } from "../transfers/transferTransactionsFactory"; import { Logger } from "./logger"; -import { INetworkProvider } from "./networkProviders/interface"; -import { loadTestWallets, stringifyBigIntJSON, TestWallet } from "./testutils"; -import { createLocalnetProvider } from "./testutils/networkProviders"; import { TokenTransfer } from "./tokens"; import { Transaction } from "./transaction"; import { TransactionComputer } from "./transactionComputer"; import { TransactionsFactoryConfig } from "./transactionsFactoryConfig"; import { TransactionWatcher } from "./transactionWatcher"; -import { TransferTransactionsFactory } from "./transfers/transferTransactionsFactory"; describe("test transaction", function () { let alice: TestWallet, bob: TestWallet; diff --git a/src/transaction.spec.ts b/src/core/transaction.spec.ts similarity index 99% rename from src/transaction.spec.ts rename to src/core/transaction.spec.ts index 201360331..08810add3 100644 --- a/src/transaction.spec.ts +++ b/src/core/transaction.spec.ts @@ -1,12 +1,12 @@ import { Buffer } from "buffer"; import { assert } from "chai"; +import { ProtoSerializer } from "../proto"; +import { TestWallet, loadTestWallets } from "../testutils"; +import { UserPublicKey, UserVerifier } from "../wallet"; import { Address } from "./address"; import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, TRANSACTION_OPTIONS_DEFAULT } from "./constants"; -import { ProtoSerializer } from "./proto"; -import { TestWallet, loadTestWallets } from "./testutils"; import { Transaction } from "./transaction"; import { TransactionComputer } from "./transactionComputer"; -import { UserPublicKey, UserVerifier } from "./wallet"; describe("test transaction", async () => { let wallets: Record; diff --git a/src/transaction.ts b/src/core/transaction.ts similarity index 100% rename from src/transaction.ts rename to src/core/transaction.ts diff --git a/src/transactionBuilder.ts b/src/core/transactionBuilder.ts similarity index 100% rename from src/transactionBuilder.ts rename to src/core/transactionBuilder.ts diff --git a/src/transactionComputer.ts b/src/core/transactionComputer.ts similarity index 99% rename from src/transactionComputer.ts rename to src/core/transactionComputer.ts index 1d204046e..ff4b0f82e 100644 --- a/src/transactionComputer.ts +++ b/src/core/transactionComputer.ts @@ -1,4 +1,5 @@ import BigNumber from "bignumber.js"; +import { ProtoSerializer } from "../proto"; import { Address } from "./address"; import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, @@ -7,7 +8,6 @@ import { } from "./constants"; import * as errors from "./errors"; import { INetworkConfig } from "./interface"; -import { ProtoSerializer } from "./proto"; import { Transaction } from "./transaction"; const createTransactionHasher = require("blake2b"); diff --git a/src/transactionEvents.ts b/src/core/transactionEvents.ts similarity index 100% rename from src/transactionEvents.ts rename to src/core/transactionEvents.ts diff --git a/src/transactionLogs.ts b/src/core/transactionLogs.ts similarity index 100% rename from src/transactionLogs.ts rename to src/core/transactionLogs.ts diff --git a/src/transactionOnNetwork.ts b/src/core/transactionOnNetwork.ts similarity index 99% rename from src/transactionOnNetwork.ts rename to src/core/transactionOnNetwork.ts index 7e9a82c6a..1d5cc96c3 100644 --- a/src/transactionOnNetwork.ts +++ b/src/core/transactionOnNetwork.ts @@ -1,7 +1,7 @@ +import { SmartContractResult } from "../transactionsOutcomeParsers"; import { Address } from "./address"; import { Transaction } from "./transaction"; import { TransactionLogs } from "./transactionLogs"; -import { SmartContractResult } from "./transactionsOutcomeParsers"; import { TransactionStatus } from "./transactionStatus"; export function prepareTransactionForBroadcasting(transaction: Transaction): any { diff --git a/src/transactionPayload.ts b/src/core/transactionPayload.ts similarity index 100% rename from src/transactionPayload.ts rename to src/core/transactionPayload.ts diff --git a/src/transactionStatus.ts b/src/core/transactionStatus.ts similarity index 100% rename from src/transactionStatus.ts rename to src/core/transactionStatus.ts diff --git a/src/transactionWatcher.spec.ts b/src/core/transactionWatcher.spec.ts similarity index 96% rename from src/transactionWatcher.spec.ts rename to src/core/transactionWatcher.spec.ts index c9189ceec..967be8037 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/core/transactionWatcher.spec.ts @@ -1,5 +1,5 @@ import { assert } from "chai"; -import { MarkCompleted, MockNetworkProvider, Wait } from "./testutils"; +import { MarkCompleted, MockNetworkProvider, Wait } from "../testutils"; import { TransactionOnNetwork } from "./transactionOnNetwork"; import { TransactionStatus } from "./transactionStatus"; import { TransactionWatcher } from "./transactionWatcher"; diff --git a/src/transactionWatcher.ts b/src/core/transactionWatcher.ts similarity index 100% rename from src/transactionWatcher.ts rename to src/core/transactionWatcher.ts diff --git a/src/transactionsFactoryConfig.ts b/src/core/transactionsFactoryConfig.ts similarity index 100% rename from src/transactionsFactoryConfig.ts rename to src/core/transactionsFactoryConfig.ts diff --git a/src/utils.codec.spec.ts b/src/core/utils.codec.spec.ts similarity index 100% rename from src/utils.codec.spec.ts rename to src/core/utils.codec.spec.ts diff --git a/src/utils.codec.ts b/src/core/utils.codec.ts similarity index 95% rename from src/utils.codec.ts rename to src/core/utils.codec.ts index 467f6d31c..299efda1e 100644 --- a/src/utils.codec.ts +++ b/src/core/utils.codec.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import * as contractsCodecUtils from "./abi/codec/utils"; +import * as contractsCodecUtils from "../abi/codec/utils"; export function numberToPaddedHex(value: bigint | number | BigNumber.Value) { let hexableNumber: { toString(radix?: number): string }; diff --git a/src/utils.ts b/src/core/utils.ts similarity index 100% rename from src/utils.ts rename to src/core/utils.ts diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index 868cbc554..1d21ce731 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -1,10 +1,10 @@ import { IAccount } from "../accounts/interfaces"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { TransactionWatcher } from "../core/transactionWatcher"; import { INetworkProvider } from "../networkProviders/interface"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; -import { TransactionWatcher } from "../transactionWatcher"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; import * as resources from "./resources"; diff --git a/src/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index 338571359..47f325988 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -1,8 +1,6 @@ import { assert } from "chai"; -import { Address } from "../address"; -import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../constants"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; -import { ValidatorPublicKey } from "../wallet"; +import { Address, TransactionsFactoryConfig, ValidatorPublicKey } from "../core"; +import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../core/constants"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; describe("test delegation transactions factory", function () { diff --git a/src/delegation/delegationTransactionsFactory.ts b/src/delegation/delegationTransactionsFactory.ts index 2ee48bd20..bfd2d5b3d 100644 --- a/src/delegation/delegationTransactionsFactory.ts +++ b/src/delegation/delegationTransactionsFactory.ts @@ -1,9 +1,9 @@ import { ArgSerializer, BigUIntValue, BytesValue, StringValue } from "../abi"; -import { Address } from "../address"; -import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../constants"; -import { Err } from "../errors"; -import { Transaction } from "../transaction"; -import { TransactionBuilder } from "../transactionBuilder"; +import { Address } from "../core/address"; +import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../core/constants"; +import { Err } from "../core/errors"; +import { Transaction } from "../core/transaction"; +import { TransactionBuilder } from "../core/transactionBuilder"; import * as resources from "./resources"; interface IConfig { diff --git a/src/delegation/delegationTransactionsOutcomeParser.spec.ts b/src/delegation/delegationTransactionsOutcomeParser.spec.ts index bdbcc7694..c804a295a 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.spec.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.spec.ts @@ -1,10 +1,6 @@ import { assert } from "chai"; -import { Address } from "../address"; +import { Address, SmartContractResult, TransactionEvent, TransactionLogs, TransactionOnNetwork } from "../core"; import { b64TopicsToBytes } from "../testutils"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { SmartContractResult } from "../transactionsOutcomeParsers"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; describe("test delegation transactions outcome parser", () => { diff --git a/src/delegation/delegationTransactionsOutcomeParser.ts b/src/delegation/delegationTransactionsOutcomeParser.ts index ec7a51442..137a28f68 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.ts @@ -1,7 +1,7 @@ -import { Address } from "../address"; -import { ErrParseTransactionOutcome } from "../errors"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { Address } from "../core/address"; +import { ErrParseTransactionOutcome } from "../core/errors"; +import { TransactionEvent } from "../core/transactionEvents"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; export class DelegationTransactionsOutcomeParser { diff --git a/src/delegation/resources.ts b/src/delegation/resources.ts index fd566cf16..b09a9f5a8 100644 --- a/src/delegation/resources.ts +++ b/src/delegation/resources.ts @@ -1,4 +1,4 @@ -import { Address } from "../address"; +import { Address } from "../core/address"; import { ValidatorPublicKey } from "../wallet"; export type NewDelegationContractInput = { totalDelegationCap: bigint; serviceFee: bigint; amount: bigint }; diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index d86816cc6..bee63e3fa 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -2,9 +2,8 @@ import { assert } from "chai"; import { readFileSync } from "fs"; import path from "path"; import { Account } from "../accounts/account"; -import { Address } from "../address"; +import { Address, TransactionComputer } from "../core"; import { loadAbiRegistry } from "../testutils"; -import { TransactionComputer } from "../transactionComputer"; import { DevnetEntrypoint } from "./entrypoints"; describe("TestEntrypoint", () => { diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 750b9c660..141546b1a 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -2,10 +2,15 @@ import { AbiRegistry } from "../abi"; import { AccountController, AccountTransactionsFactory } from "../accountManagement"; import { Account } from "../accounts"; import { IAccount } from "../accounts/interfaces"; -import { Address } from "../address"; +import { Address } from "../core/address"; +import { ErrInvalidNetworkProviderKind } from "../core/errors"; +import { Message, MessageComputer } from "../core/message"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { TransactionWatcher } from "../core/transactionWatcher"; import { DelegationController, DelegationTransactionsFactory } from "../delegation"; -import { ErrInvalidNetworkProviderKind } from "../errors"; -import { Message, MessageComputer } from "../message"; import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { INetworkProvider } from "../networkProviders/interface"; import { RelayedTransactionsFactory } from "../relayed"; @@ -13,11 +18,6 @@ import { RelayedController } from "../relayed/relayedController"; import { SmartContractTransactionsFactory } from "../smartContracts"; import { SmartContractController } from "../smartContracts/smartContractController"; import { TokenManagementController, TokenManagementTransactionsFactory } from "../tokenManagement"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; -import { TransactionWatcher } from "../transactionWatcher"; import { TransferTransactionsFactory } from "../transfers"; import { TransfersController } from "../transfers/transfersControllers"; import { UserSecretKey, UserVerifier } from "../wallet"; diff --git a/src/networkProviders/accountAwaiter.dev.net.spec.ts b/src/networkProviders/accountAwaiter.dev.net.spec.ts index 3322216ee..9a9e40e64 100644 --- a/src/networkProviders/accountAwaiter.dev.net.spec.ts +++ b/src/networkProviders/accountAwaiter.dev.net.spec.ts @@ -1,10 +1,8 @@ import { assert } from "chai"; -import { Address } from "../address"; +import { Address, Transaction, TransactionComputer } from "../core"; import { MarkCompleted, MockNetworkProvider, Wait } from "../testutils/mockNetworkProvider"; import { createAccountBalance } from "../testutils/utils"; import { loadTestWallet } from "../testutils/wallets"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; import { AccountAwaiter } from "./accountAwaiter"; import { AccountOnNetwork } from "./accounts"; import { ApiNetworkProvider } from "./apiNetworkProvider"; diff --git a/src/networkProviders/accountAwaiter.ts b/src/networkProviders/accountAwaiter.ts index 72b27a98b..b83690587 100644 --- a/src/networkProviders/accountAwaiter.ts +++ b/src/networkProviders/accountAwaiter.ts @@ -1,5 +1,5 @@ -import { Address } from "../address"; -import { ExpectedAccountConditionNotReachedError } from "../errors"; +import { Address } from "../core/address"; +import { ExpectedAccountConditionNotReachedError } from "../core/errors"; import { AccountOnNetwork } from "./accounts"; import { DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS, diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index c163ed6f1..fb6beca51 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -1,5 +1,5 @@ import { CodeMetadata } from "../abi"; -import { Address } from "../address"; +import { Address } from "../core/address"; /** * A plain view of an account, as queried from the Network. diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index b63c5cfe9..e7a834178 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -1,12 +1,14 @@ import { assert, expect } from "chai"; -import { Address } from "../address"; -import { SmartContractQuery } from "../smartContractQuery"; +import { + Address, + SmartContractQuery, + Token, + Transaction, + TransactionComputer, + TransactionOnNetwork, + TransactionStatus, +} from "../core"; import { loadTestWallet } from "../testutils/wallets"; -import { Token } from "../tokens"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionStatus } from "../transactionStatus"; import { ApiNetworkProvider } from "./apiNetworkProvider"; describe("ApiNetworkProvider Tests", function () { diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index e7030d8c2..4f24841eb 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,13 +1,13 @@ -import { Address } from "../address"; -import { METACHAIN_ID } from "../constants"; -import { ErrContractQuery, ErrNetworkProvider } from "../errors"; -import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; -import { Token, TokenComputer } from "../tokens"; -import { Transaction } from "../transaction"; -import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionStatus } from "../transactionStatus"; -import { TransactionWatcher } from "../transactionWatcher"; -import { getAxios } from "../utils"; +import { Address } from "../core/address"; +import { METACHAIN_ID } from "../core/constants"; +import { ErrContractQuery, ErrNetworkProvider } from "../core/errors"; +import { SmartContractQuery, SmartContractQueryResponse } from "../core/smartContractQuery"; +import { Token, TokenComputer } from "../core/tokens"; +import { Transaction } from "../core/transaction"; +import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../core/transactionOnNetwork"; +import { TransactionStatus } from "../core/transactionStatus"; +import { TransactionWatcher } from "../core/transactionWatcher"; +import { getAxios } from "../core/utils"; import { AccountAwaiter } from "./accountAwaiter"; import { AccountOnNetwork } from "./accounts"; import { defaultAxiosConfig, defaultPagination } from "./config"; diff --git a/src/networkProviders/constants.ts b/src/networkProviders/constants.ts index 06d93c10a..f31aee782 100644 --- a/src/networkProviders/constants.ts +++ b/src/networkProviders/constants.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import { Address } from "../address"; +import { Address } from "../core/address"; export const MaxUint64AsBigNumber = new BigNumber("18446744073709551615"); export const EsdtContractAddress = new Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); diff --git a/src/networkProviders/contractQueryRequest.ts b/src/networkProviders/contractQueryRequest.ts index 2b1f8b0fc..3bafd74f9 100644 --- a/src/networkProviders/contractQueryRequest.ts +++ b/src/networkProviders/contractQueryRequest.ts @@ -1,4 +1,4 @@ -import { SmartContractQuery } from "../smartContractQuery"; +import { SmartContractQuery } from "../core/smartContractQuery"; export class ContractQueryRequest { private readonly query: SmartContractQuery; diff --git a/src/networkProviders/contractResults.ts b/src/networkProviders/contractResults.ts index 45e0bb26f..38c057f75 100644 --- a/src/networkProviders/contractResults.ts +++ b/src/networkProviders/contractResults.ts @@ -1,5 +1,5 @@ -import { Address } from "../address"; -import { TransactionLogs } from "../transactionLogs"; +import { Address } from "../core/address"; +import { TransactionLogs } from "../core/transactionLogs"; export class ContractResults { readonly items: ContractResultItem[]; diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 8290c8bb3..1e845a12e 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,9 +1,9 @@ -import { Address } from "../address"; -import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; -import { Token } from "../tokens"; -import { Transaction } from "../transaction"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionStatus } from "../transactionStatus"; +import { Address } from "../core/address"; +import { SmartContractQuery, SmartContractQueryResponse } from "../core/smartContractQuery"; +import { Token } from "../core/tokens"; +import { Transaction } from "../core/transaction"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; +import { TransactionStatus } from "../core/transactionStatus"; import { AccountOnNetwork } from "./accounts"; import { NetworkConfig } from "./networkConfig"; import { NetworkStatus } from "./networkStatus"; diff --git a/src/networkProviders/pairs.ts b/src/networkProviders/pairs.ts index f8dd7e797..26e2605a1 100644 --- a/src/networkProviders/pairs.ts +++ b/src/networkProviders/pairs.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import { Address } from "../address"; +import { Address } from "../core/address"; export class PairOnNetwork { address: Address = Address.empty(); diff --git a/src/networkProviders/providers.dev.net.spec.ts b/src/networkProviders/providers.dev.net.spec.ts index 2e0615cce..e2555f4f6 100644 --- a/src/networkProviders/providers.dev.net.spec.ts +++ b/src/networkProviders/providers.dev.net.spec.ts @@ -1,9 +1,6 @@ import { AxiosHeaders } from "axios"; import { assert } from "chai"; -import { Address } from "../address"; -import { SmartContractQuery } from "../smartContractQuery"; -import { Transaction } from "../transaction"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { Address, SmartContractQuery, Transaction, TransactionOnNetwork } from "../core"; import { ApiNetworkProvider } from "./apiNetworkProvider"; import { INetworkProvider } from "./interface"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 07ac78785..0b35ea86f 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -1,12 +1,14 @@ import { assert, expect } from "chai"; -import { Address } from "../address"; -import { SmartContractQuery } from "../smartContractQuery"; +import { + Address, + SmartContractQuery, + Token, + Transaction, + TransactionComputer, + TransactionOnNetwork, + TransactionStatus, +} from "../core"; import { loadTestWallet } from "../testutils/wallets"; -import { Token } from "../tokens"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionStatus } from "../transactionStatus"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; describe("ProxyNetworkProvider Tests", function () { diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index ed454ca0a..8882c961b 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,13 +1,13 @@ -import { Address } from "../address"; -import { ESDT_CONTRACT_ADDRESS_HEX, METACHAIN_ID } from "../constants"; -import { ErrContractQuery, ErrNetworkProvider } from "../errors"; -import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; -import { Token } from "../tokens"; -import { Transaction } from "../transaction"; -import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionStatus } from "../transactionStatus"; -import { TransactionWatcher } from "../transactionWatcher"; -import { getAxios } from "../utils"; +import { Address } from "../core/address"; +import { ESDT_CONTRACT_ADDRESS_HEX, METACHAIN_ID } from "../core/constants"; +import { ErrContractQuery, ErrNetworkProvider } from "../core/errors"; +import { SmartContractQuery, SmartContractQueryResponse } from "../core/smartContractQuery"; +import { Token } from "../core/tokens"; +import { Transaction } from "../core/transaction"; +import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../core/transactionOnNetwork"; +import { TransactionStatus } from "../core/transactionStatus"; +import { TransactionWatcher } from "../core/transactionWatcher"; +import { getAxios } from "../core/utils"; import { AccountAwaiter } from "./accountAwaiter"; import { AccountOnNetwork, GuardianData } from "./accounts"; import { defaultAxiosConfig } from "./config"; diff --git a/src/networkProviders/resources.ts b/src/networkProviders/resources.ts index 3a555857f..98c76d5af 100644 --- a/src/networkProviders/resources.ts +++ b/src/networkProviders/resources.ts @@ -1,7 +1,7 @@ import { BytesValue } from "../abi"; -import { Address } from "../address"; -import { Token } from "../tokens"; -import { TransactionStatus } from "../transactionStatus"; +import { Address } from "../core/address"; +import { Token } from "../core/tokens"; +import { TransactionStatus } from "../core/transactionStatus"; import { DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS, DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS, diff --git a/src/networkProviders/tokenDefinitions.ts b/src/networkProviders/tokenDefinitions.ts index 150c2c325..e5ff77442 100644 --- a/src/networkProviders/tokenDefinitions.ts +++ b/src/networkProviders/tokenDefinitions.ts @@ -1,5 +1,5 @@ import BigNumber from "bignumber.js"; -import { Address } from "../address"; +import { Address } from "../core/address"; export class DefinitionOfFungibleTokenOnNetwork { identifier: string = ""; diff --git a/src/networkProviders/tokens.ts b/src/networkProviders/tokens.ts index d61930766..60d52ac9e 100644 --- a/src/networkProviders/tokens.ts +++ b/src/networkProviders/tokens.ts @@ -1,6 +1,6 @@ import { BigNumber } from "bignumber.js"; -import { Address } from "../address"; -import { numberToPaddedHex } from "../utils.codec"; +import { Address } from "../core/address"; +import { numberToPaddedHex } from "../core/utils.codec"; export class FungibleTokenOfAccountOnNetwork { identifier: string = ""; diff --git a/src/networkProviders/transactionReceipt.ts b/src/networkProviders/transactionReceipt.ts index 10947b2e7..5b4b7f607 100644 --- a/src/networkProviders/transactionReceipt.ts +++ b/src/networkProviders/transactionReceipt.ts @@ -1,4 +1,4 @@ -import { Address } from "../address"; +import { Address } from "../core/address"; export class TransactionReceipt { value: string = ""; diff --git a/src/proto/serializer.spec.ts b/src/proto/serializer.spec.ts index 226eb101c..6a8ccce84 100644 --- a/src/proto/serializer.spec.ts +++ b/src/proto/serializer.spec.ts @@ -1,8 +1,6 @@ import { assert } from "chai"; -import { Address } from "../address"; +import { Address, TokenTransfer, Transaction } from "../core"; import { loadTestWallets, TestWallet } from "../testutils"; -import { TokenTransfer } from "../tokens"; -import { Transaction } from "../transaction"; import { ProtoSerializer } from "./serializer"; describe("serialize transactions", () => { diff --git a/src/proto/serializer.ts b/src/proto/serializer.ts index 4988b362a..ed1bd5f89 100644 --- a/src/proto/serializer.ts +++ b/src/proto/serializer.ts @@ -1,9 +1,9 @@ import BigNumber from "bignumber.js"; import { bigIntToBuffer } from "../abi/codec/utils"; -import { Address } from "../address"; -import { TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_OPTIONS_TX_GUARDED } from "../constants"; -import * as errors from "../errors"; -import { Transaction } from "../transaction"; +import { Address } from "../core/address"; +import { TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_OPTIONS_TX_GUARDED } from "../core/constants"; +import * as errors from "../core/errors"; +import { Transaction } from "../core/transaction"; /** * Hides away the serialization complexity, for each type of object (e.g. transactions). diff --git a/src/relayed/relayedController.ts b/src/relayed/relayedController.ts index 558cbb95f..43c9979d3 100644 --- a/src/relayed/relayedController.ts +++ b/src/relayed/relayedController.ts @@ -1,7 +1,7 @@ import { IAccount } from "../accounts/interfaces"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; import { RelayedV1TransactionInput, RelayedV2TransactionInput } from "./resources"; diff --git a/src/relayed/relayedTransactionsFactory.spec.ts b/src/relayed/relayedTransactionsFactory.spec.ts index aed994fa2..3535b8a77 100644 --- a/src/relayed/relayedTransactionsFactory.spec.ts +++ b/src/relayed/relayedTransactionsFactory.spec.ts @@ -1,9 +1,6 @@ import { assert } from "chai"; -import { Address } from "../address"; +import { Address, Transaction, TransactionComputer, TransactionsFactoryConfig } from "../core"; import { TestWallet, loadTestWallets } from "../testutils"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; describe("test relayed transactions factory", function () { diff --git a/src/relayed/relayedTransactionsFactory.ts b/src/relayed/relayedTransactionsFactory.ts index 71f6a440e..8e14eee1b 100644 --- a/src/relayed/relayedTransactionsFactory.ts +++ b/src/relayed/relayedTransactionsFactory.ts @@ -1,8 +1,8 @@ import BigNumber from "bignumber.js"; import { AddressValue, ArgSerializer, BytesValue, U64Value } from "../abi"; -import { Address } from "../address"; -import { ErrInvalidInnerTransaction } from "../errors"; -import { Transaction } from "../transaction"; +import { Address } from "../core/address"; +import { ErrInvalidInnerTransaction } from "../core/errors"; +import { Transaction } from "../core/transaction"; const JSONbig = require("json-bigint"); diff --git a/src/relayed/resources.ts b/src/relayed/resources.ts index e4d0589fa..62e4ecc9b 100644 --- a/src/relayed/resources.ts +++ b/src/relayed/resources.ts @@ -1,4 +1,4 @@ -import { Transaction } from "../transaction"; +import { Transaction } from "../core/transaction"; export type RelayedV1TransactionInput = { innerTransaction: Transaction }; export type RelayedV2TransactionInput = { diff --git a/src/smartContracts/resources.ts b/src/smartContracts/resources.ts index 71b1f5c60..f9008b85e 100644 --- a/src/smartContracts/resources.ts +++ b/src/smartContracts/resources.ts @@ -1,5 +1,5 @@ -import { Address } from "../address"; -import { TokenTransfer } from "../tokens"; +import { Address } from "../core/address"; +import { TokenTransfer } from "../core/tokens"; export type ContractDeployInput = { bytecode: Uint8Array; diff --git a/src/smartContracts/smartContractController.spec.ts b/src/smartContracts/smartContractController.spec.ts index 679e124ee..59010660b 100644 --- a/src/smartContracts/smartContractController.spec.ts +++ b/src/smartContracts/smartContractController.spec.ts @@ -1,8 +1,7 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { AbiRegistry, BigUIntValue, BooleanValue, BytesValue, Tuple, U16Value, U64Value } from "../abi"; -import { Address } from "../address"; -import { SmartContractQueryResponse } from "../smartContractQuery"; +import { Address, SmartContractQueryResponse } from "../core"; import { MockNetworkProvider, loadAbiRegistry } from "../testutils"; import { bigIntToBuffer } from "../tokenOperations/codec"; import { SmartContractController } from "./smartContractController"; diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index cbe495623..01a8327b1 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -1,14 +1,14 @@ import { AbiRegistry, ArgSerializer, isTyped, NativeSerializer } from "../abi"; import { IAccount } from "../accounts/interfaces"; -import { Err, ErrSmartContractQuery } from "../errors"; +import { Err, ErrSmartContractQuery } from "../core/errors"; +import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../core/smartContractQuery"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { TransactionWatcher } from "../core/transactionWatcher"; import { INetworkProvider } from "../networkProviders/interface"; -import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../smartContractQuery"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { SmartContractTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; -import { TransactionWatcher } from "../transactionWatcher"; import * as resources from "./resources"; import { SmartContractTransactionsFactory } from "./smartContractTransactionsFactory"; diff --git a/src/smartContracts/smartContractTransactionsFactory.spec.ts b/src/smartContracts/smartContractTransactionsFactory.spec.ts index 7e72d63dc..546f76465 100644 --- a/src/smartContracts/smartContractTransactionsFactory.spec.ts +++ b/src/smartContracts/smartContractTransactionsFactory.spec.ts @@ -1,10 +1,7 @@ import { assert } from "chai"; import { AbiRegistry, Code, U32Value } from "../abi"; -import { Address } from "../address"; -import { Err } from "../errors"; +import { Address, Err, Token, TokenTransfer, TransactionsFactoryConfig } from "../core"; import { loadAbiRegistry, loadContractCode } from "../testutils/utils"; -import { Token, TokenTransfer } from "../tokens"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { SmartContractTransactionsFactory } from "./smartContractTransactionsFactory"; describe("test smart contract transactions factory", function () { @@ -29,7 +26,7 @@ describe("test smart contract transactions factory", function () { }); it("should throw error when args are not of type 'TypedValue'", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const gasLimit = 6000000n; const args = [0]; @@ -46,7 +43,7 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for deploy", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const gasLimit = 6000000n; const args = [new U32Value(1)]; @@ -78,8 +75,8 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for execute without transfer", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const func = "add"; const gasLimit = 6000000n; const args = [new U32Value(7)]; @@ -114,8 +111,8 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for execute and transfer native token", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const func = "add"; const gasLimit = 6000000n; const egldAmount = 1000000000000000000n; @@ -152,8 +149,8 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for execute and transfer single esdt", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const func = "add"; const gasLimit = 6000000n; const args = [new U32Value(7)]; @@ -192,8 +189,8 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for execute and transfer multiple esdts", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"); const func = "add"; const gasLimit = 6000000n; const args = [new U32Value(7)]; @@ -242,8 +239,8 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for execute and transfer single nft", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const func = "add"; const gasLimit = 6000000n; const args = [new U32Value(7)]; @@ -291,8 +288,8 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for execute and transfer multiple nfts", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const func = "add"; const gasLimit = 6000000n; const args = [new U32Value(7)]; @@ -342,8 +339,8 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for execute and transfer native and nfts", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const func = "add"; const gasLimit = 6000000n; const args = [new U32Value(7)]; @@ -395,8 +392,8 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for upgrade", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const gasLimit = 6000000n; const args = [new U32Value(7)]; @@ -472,8 +469,8 @@ describe("test smart contract transactions factory", function () { }); const bytecode = Buffer.from("abba", "hex"); - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const receiver = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const receiver = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); const gasLimit = 6000000n; // By default, use the upgrade constructor. @@ -548,9 +545,9 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for changing owner address", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); - const newOwner = Address.fromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqhy6nl6zq07rnzry8uyh6rtyq0uzgtk3e69fqgtz9l4"); + const newOwner = Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); const transaction = factory.createTransactionForChangingOwnerAddress({ sender: sender, diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index 42113e174..fde7dded3 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -1,15 +1,15 @@ import { ArgSerializer, CodeMetadata, ContractFunction, EndpointDefinition } from "../abi"; import { NativeSerializer } from "../abi/nativeSerializer"; import { isTyped } from "../abi/typesystem"; -import { Address } from "../address"; -import { CONTRACT_DEPLOY_ADDRESS_HEX, VM_TYPE_WASM_VM } from "../constants"; -import { Err } from "../errors"; -import { Logger } from "../logger"; -import { TokenComputer, TokenTransfer } from "../tokens"; -import { TokenTransfersDataBuilder } from "../tokenTransfersDataBuilder"; -import { Transaction } from "../transaction"; -import { TransactionBuilder } from "../transactionBuilder"; -import { byteArrayToHex, utf8ToHex } from "../utils.codec"; +import { Address } from "../core/address"; +import { CONTRACT_DEPLOY_ADDRESS_HEX, VM_TYPE_WASM_VM } from "../core/constants"; +import { Err } from "../core/errors"; +import { Logger } from "../core/logger"; +import { TokenComputer, TokenTransfer } from "../core/tokens"; +import { TokenTransfersDataBuilder } from "../core/tokenTransfersDataBuilder"; +import { Transaction } from "../core/transaction"; +import { TransactionBuilder } from "../core/transactionBuilder"; +import { byteArrayToHex, utf8ToHex } from "../core/utils.codec"; import * as resources from "./resources"; interface IConfig { diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index b835dbf6d..90528b854 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -1,10 +1,7 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { Address } from "../address"; +import { Address, TransactionEvent, TransactionLogs, TransactionOnNetwork } from "../core"; import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { SmartContractTransactionsOutcomeParser } from "./smartContractTransactionsOutcomeParser"; diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index f342a78dd..fdb0d4588 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -1,9 +1,9 @@ import { AbiRegistry, ArgSerializer } from "../abi"; -import { Address } from "../address"; -import { ARGUMENTS_SEPARATOR } from "../constants"; -import { Err } from "../errors"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { Address } from "../core/address"; +import { ARGUMENTS_SEPARATOR } from "../core/constants"; +import { Err } from "../core/errors"; +import { TransactionEvent } from "../core/transactionEvents"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { SmartContractCallOutcome, SmartContractResult } from "../transactionsOutcomeParsers/resources"; import * as resources from "./resources"; diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 1d8883084..08ce1b788 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -1,7 +1,13 @@ -import { Address } from "../address"; -import { AsyncTimer } from "../asyncTimer"; -import * as errors from "../errors"; -import { ErrMock } from "../errors"; +import { Address } from "../core/address"; +import { AsyncTimer } from "../core/asyncTimer"; +import * as errors from "../core/errors"; +import { ErrMock } from "../core/errors"; +import { SmartContractQuery, SmartContractQueryResponse } from "../core/smartContractQuery"; +import { Token } from "../core/tokens"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; +import { TransactionStatus } from "../core/transactionStatus"; import { AccountOnNetwork, DefinitionOfFungibleTokenOnNetwork, @@ -18,13 +24,7 @@ import { TokenAmountOnNetwork, TransactionCostResponse, } from "../networkProviders/resources"; -import { SmartContractQuery, SmartContractQueryResponse } from "../smartContractQuery"; -import { Token } from "../tokens"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; import { SmartContractResult } from "../transactionsOutcomeParsers"; -import { TransactionStatus } from "../transactionStatus"; import { createAccountBalance } from "./utils"; export class MockNetworkProvider implements INetworkProvider { diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index bca35a365..9a6f16ad7 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -1,10 +1,10 @@ import * as fs from "fs"; import { PathLike } from "fs"; import { AbiRegistry, Code, SmartContract, TypedValue } from "../abi"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionWatcher } from "../transactionWatcher"; -import { getAxios } from "../utils"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionWatcher } from "../core/transactionWatcher"; +import { getAxios } from "../core/utils"; import { TestWallet } from "./wallets"; export async function prepareDeployment(obj: { diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index 7cb88fb9d..723e4ef5a 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -1,9 +1,9 @@ import * as fs from "fs"; import * as path from "path"; import { Account } from "../accounts"; -import { Address } from "../address"; +import { Address } from "../core/address"; +import { getAxios } from "../core/utils"; import { AccountOnNetwork } from "../networkProviders"; -import { getAxios } from "../utils"; import { UserSecretKey, UserSigner } from "./../wallet"; import { readTestFile } from "./files"; import { isOnBrowserTests } from "./utils"; diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 1886c4920..18f7ce457 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -1,4 +1,4 @@ -import { Address } from "../address"; +import { Address } from "../core/address"; export type IssueFungibleInput = IssueInput & { initialSupply: bigint; numDecimals: bigint }; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index a00400d4e..a3a3bfd77 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -1,11 +1,11 @@ import { IAccount } from "../accounts/interfaces"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { TransactionWatcher } from "../core/transactionWatcher"; import { INetworkProvider } from "../networkProviders/interface"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TokenManagementTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; -import { TransactionWatcher } from "../transactionWatcher"; import * as resources from "./resources"; import { TokenManagementTransactionsFactory } from "./tokenManagementTransactionsFactory"; diff --git a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts index 904fa4f2e..a339af6a7 100644 --- a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts @@ -1,8 +1,7 @@ import { assert } from "chai"; -import { Address } from "../address"; -import { ESDT_CONTRACT_ADDRESS_HEX } from "../constants"; +import { Address, TransactionsFactoryConfig } from "../core"; +import { ESDT_CONTRACT_ADDRESS_HEX } from "../core/constants"; import { loadTestWallets, TestWallet } from "../testutils"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; import { TokenManagementTransactionsFactory } from "./tokenManagementTransactionsFactory"; describe("test token management transactions factory", () => { diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index bf902580e..d6d14e5e4 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -1,10 +1,10 @@ import { AddressValue, ArgSerializer, BigUIntValue, BytesValue, StringValue } from "../abi"; -import { Address } from "../address"; -import { ESDT_CONTRACT_ADDRESS_HEX } from "../constants"; -import { ErrBadUsage } from "../errors"; -import { Logger } from "../logger"; -import { Transaction } from "../transaction"; -import { TransactionBuilder } from "../transactionBuilder"; +import { Address } from "../core/address"; +import { ESDT_CONTRACT_ADDRESS_HEX } from "../core/constants"; +import { ErrBadUsage } from "../core/errors"; +import { Logger } from "../core/logger"; +import { Transaction } from "../core/transaction"; +import { TransactionBuilder } from "../core/transactionBuilder"; import * as resources from "./resources"; interface IConfig { diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts index 583c137a4..b5d68676c 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts @@ -1,11 +1,13 @@ import { assert } from "chai"; -import { Address } from "../address"; -import { ErrParseTransactionOutcome } from "../errors"; +import { + Address, + ErrParseTransactionOutcome, + SmartContractResult, + TransactionEvent, + TransactionLogs, + TransactionOnNetwork, +} from "../core"; import { b64TopicsToBytes } from "../testutils"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; -import { SmartContractResult } from "../transactionsOutcomeParsers"; import { TokenManagementTransactionsOutcomeParser } from "./tokenManagementTransactionsOutcomeParser"; describe("test token management transactions outcome parser", () => { diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts index 81078d1ba..6bb5be95d 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.ts @@ -1,9 +1,9 @@ import BigNumber from "bignumber.js"; import { bufferToBigInt } from "../abi/codec/utils"; -import { Address } from "../address"; -import { ErrParseTransactionOutcome } from "../errors"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { Address } from "../core/address"; +import { ErrParseTransactionOutcome } from "../core/errors"; +import { TransactionEvent } from "../core/transactionEvents"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { findEventsByIdentifier } from "../transactionsOutcomeParsers/resources"; import { ChangeToDynamicOutput, diff --git a/src/tokenOperations/codec.ts b/src/tokenOperations/codec.ts index 5dcd62c13..be43feff8 100644 --- a/src/tokenOperations/codec.ts +++ b/src/tokenOperations/codec.ts @@ -1,6 +1,6 @@ import BigNumber from "bignumber.js"; import * as contractsCodecUtils from "../abi/codec/utils"; -import * as codecUtils from "../utils.codec"; +import * as codecUtils from "../core/utils.codec"; export function stringToBuffer(value: string): Buffer { return Buffer.from(value); @@ -22,7 +22,7 @@ export function bigIntToBuffer(value: BigNumber.Value): Buffer { return contractsCodecUtils.bigIntToBuffer(value); } -export { bigIntToHex, utf8ToHex } from "../utils.codec"; +export { bigIntToHex, utf8ToHex } from "../core/utils.codec"; export function bufferToHex(value: Buffer) { const hex = value.toString("hex"); diff --git a/src/transactionsOutcomeParsers/resources.spec.ts b/src/transactionsOutcomeParsers/resources.spec.ts index 8aa37074e..c02d567cd 100644 --- a/src/transactionsOutcomeParsers/resources.spec.ts +++ b/src/transactionsOutcomeParsers/resources.spec.ts @@ -1,7 +1,5 @@ import { assert } from "chai"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { TransactionEvent, TransactionLogs, TransactionOnNetwork } from "../core"; import { findEventsByFirstTopic, findEventsByIdentifier, SmartContractResult } from "./resources"; describe("test resources", () => { diff --git a/src/transactionsOutcomeParsers/resources.ts b/src/transactionsOutcomeParsers/resources.ts index 8bbfadcf2..d47382038 100644 --- a/src/transactionsOutcomeParsers/resources.ts +++ b/src/transactionsOutcomeParsers/resources.ts @@ -1,7 +1,7 @@ -import { Address } from "../address"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; +import { Address } from "../core/address"; +import { TransactionEvent } from "../core/transactionEvents"; +import { TransactionLogs } from "../core/transactionLogs"; +import { TransactionOnNetwork } from "../core/transactionOnNetwork"; export class SmartContractResult { raw: Record; diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts index 5770853a0..2fb33ed8e 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts @@ -1,11 +1,8 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { AbiRegistry } from "../abi"; -import { Address } from "../address"; +import { Address, TransactionEvent, TransactionLogs, TransactionOnNetwork } from "../core"; import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; -import { TransactionEvent } from "../transactionEvents"; -import { TransactionLogs } from "../transactionLogs"; -import { TransactionOnNetwork } from "../transactionOnNetwork"; import { findEventsByFirstTopic, SmartContractResult } from "./resources"; import { TransactionEventsParser } from "./transactionEventsParser"; diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.ts b/src/transactionsOutcomeParsers/transactionEventsParser.ts index 93b53df94..c73f3e26a 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.ts @@ -1,5 +1,5 @@ import { AbiRegistry, ArgSerializer } from "../abi"; -import { TransactionEvent } from "../transactionEvents"; +import { TransactionEvent } from "../core/transactionEvents"; export class TransactionEventsParser { private readonly abi: AbiRegistry; diff --git a/src/transfers/resources.ts b/src/transfers/resources.ts index 7a6aa975b..779a858fa 100644 --- a/src/transfers/resources.ts +++ b/src/transfers/resources.ts @@ -1,5 +1,5 @@ -import { Address } from "../address"; -import { TokenTransfer } from "../tokens"; +import { Address } from "../core/address"; +import { TokenTransfer } from "../core/tokens"; export type NativeTokenTransferInput = { receiver: Address; diff --git a/src/transfers/transferTransactionsFactory.spec.ts b/src/transfers/transferTransactionsFactory.spec.ts index e753db24e..b9342535d 100644 --- a/src/transfers/transferTransactionsFactory.spec.ts +++ b/src/transfers/transferTransactionsFactory.spec.ts @@ -1,9 +1,7 @@ import { assert } from "chai"; -import { Address } from "../address"; -import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../constants"; -import { ErrBadUsage } from "../errors"; -import { Token, TokenTransfer } from "../tokens"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; +import { Address, ErrBadUsage, Token, TokenTransfer } from "../core"; +import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../core/constants"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { TransferTransactionsFactory } from "./transferTransactionsFactory"; describe("test transfer transactions factory", function () { diff --git a/src/transfers/transferTransactionsFactory.ts b/src/transfers/transferTransactionsFactory.ts index 3423142fd..733a95107 100644 --- a/src/transfers/transferTransactionsFactory.ts +++ b/src/transfers/transferTransactionsFactory.ts @@ -1,10 +1,10 @@ -import { Address } from "../address"; -import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../constants"; -import { ErrBadUsage } from "../errors"; -import { TokenComputer, TokenTransfer } from "../tokens"; -import { TokenTransfersDataBuilder } from "../tokenTransfersDataBuilder"; -import { Transaction } from "../transaction"; -import { TransactionBuilder } from "../transactionBuilder"; +import { Address } from "../core/address"; +import { EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER } from "../core/constants"; +import { ErrBadUsage } from "../core/errors"; +import { TokenComputer, TokenTransfer } from "../core/tokens"; +import { TokenTransfersDataBuilder } from "../core/tokenTransfersDataBuilder"; +import { Transaction } from "../core/transaction"; +import { TransactionBuilder } from "../core/transactionBuilder"; import * as resources from "./resources"; const ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 100000; diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index 74a0e3085..cb9316be0 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -1,7 +1,7 @@ import { IAccount } from "../accounts/interfaces"; -import { Transaction } from "../transaction"; -import { TransactionComputer } from "../transactionComputer"; -import { TransactionsFactoryConfig } from "../transactionsFactoryConfig"; +import { Transaction } from "../core/transaction"; +import { TransactionComputer } from "../core/transactionComputer"; +import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import * as resources from "./resources"; import { TransferTransactionsFactory } from "./transferTransactionsFactory"; diff --git a/src/wallet/assertions.ts b/src/wallet/assertions.ts index 09ac481d2..07e240e36 100644 --- a/src/wallet/assertions.ts +++ b/src/wallet/assertions.ts @@ -1,4 +1,4 @@ -import { ErrInvariantFailed } from "../errors"; +import { ErrInvariantFailed } from "../core/errors"; export function guardLength(withLength: { length?: number }, expectedLength: number) { let actualLength = withLength.length || 0; diff --git a/src/wallet/crypto/decryptor.ts b/src/wallet/crypto/decryptor.ts index 388b9fd63..296a6f259 100644 --- a/src/wallet/crypto/decryptor.ts +++ b/src/wallet/crypto/decryptor.ts @@ -1,5 +1,5 @@ import crypto from "crypto"; -import { Err } from "../../errors"; +import { Err } from "../../core/errors"; import { DigestAlgorithm } from "./constants"; import { EncryptedData } from "./encryptedData"; diff --git a/src/wallet/keypair.spec.ts b/src/wallet/keypair.spec.ts index 971423b83..303438afb 100644 --- a/src/wallet/keypair.spec.ts +++ b/src/wallet/keypair.spec.ts @@ -1,5 +1,5 @@ import { assert } from "chai"; -import { Address, Transaction, TransactionComputer } from ".."; +import { Address, Transaction, TransactionComputer } from "../core"; import { KeyPair } from "./keypair"; import { UserSecretKey } from "./userKeys"; diff --git a/src/wallet/mnemonic.ts b/src/wallet/mnemonic.ts index 77c397b4c..7b69eeef8 100644 --- a/src/wallet/mnemonic.ts +++ b/src/wallet/mnemonic.ts @@ -1,5 +1,5 @@ import { derivePath } from "ed25519-hd-key"; -import { ErrBadMnemonicEntropy, ErrWrongMnemonic } from "../errors"; +import { ErrBadMnemonicEntropy, ErrWrongMnemonic } from "../core/errors"; import { UserSecretKey } from "./userKeys"; const MNEMONIC_STRENGTH = 256; diff --git a/src/wallet/pem.spec.ts b/src/wallet/pem.spec.ts index 3c4557ae1..34a3a9ef4 100644 --- a/src/wallet/pem.spec.ts +++ b/src/wallet/pem.spec.ts @@ -1,6 +1,6 @@ import { Buffer } from "buffer"; import { assert } from "chai"; -import { ErrBadPEM } from "../errors"; +import { ErrBadPEM } from "../core/errors"; import { loadTestWallet, TestWallet } from "./../testutils/wallets"; import { parse, parseUserKey, parseValidatorKey } from "./pem"; import { BLS } from "./validatorKeys"; diff --git a/src/wallet/pem.ts b/src/wallet/pem.ts index b60119699..f95a5b8fe 100644 --- a/src/wallet/pem.ts +++ b/src/wallet/pem.ts @@ -1,4 +1,4 @@ -import { ErrBadPEM } from "../errors"; +import { ErrBadPEM } from "../core/errors"; import { USER_PUBKEY_LENGTH, USER_SEED_LENGTH, UserSecretKey } from "./userKeys"; import { VALIDATOR_SECRETKEY_LENGTH, ValidatorSecretKey } from "./validatorKeys"; diff --git a/src/wallet/userKeys.ts b/src/wallet/userKeys.ts index 31bcb8133..21b43c6b5 100644 --- a/src/wallet/userKeys.ts +++ b/src/wallet/userKeys.ts @@ -1,7 +1,7 @@ import * as ed from "@noble/ed25519"; import { sha512 } from "@noble/hashes/sha512"; import nacl from "tweetnacl"; -import { Address } from "../address"; +import { Address } from "../core/address"; import { guardLength } from "./assertions"; import { parseUserKey } from "./pem"; diff --git a/src/wallet/userSigner.ts b/src/wallet/userSigner.ts index 6163e9dc0..75b2787a3 100644 --- a/src/wallet/userSigner.ts +++ b/src/wallet/userSigner.ts @@ -1,5 +1,5 @@ -import { Address } from "../address"; -import { ErrSignerCannotSign } from "../errors"; +import { Address } from "../core/address"; +import { ErrSignerCannotSign } from "../core/errors"; import { UserSecretKey } from "./userKeys"; import { UserWallet } from "./userWallet"; diff --git a/src/wallet/userVerifier.ts b/src/wallet/userVerifier.ts index b143c760e..c13035ce3 100644 --- a/src/wallet/userVerifier.ts +++ b/src/wallet/userVerifier.ts @@ -1,4 +1,4 @@ -import { Address } from "../address"; +import { Address } from "../core/address"; import { UserPublicKey } from "./userKeys"; /** diff --git a/src/wallet/userWallet.ts b/src/wallet/userWallet.ts index 974cf2be0..70712d339 100644 --- a/src/wallet/userWallet.ts +++ b/src/wallet/userWallet.ts @@ -1,8 +1,8 @@ import { PathLike, readFileSync, writeFileSync } from "fs"; import path, { isAbsolute, join, resolve } from "path"; -import { LibraryConfig } from "../config"; -import { Err } from "../errors"; -import { Logger } from "../logger"; +import { LibraryConfig } from "../core/config"; +import { Err } from "../core/errors"; +import { Logger } from "../core/logger"; import { CipherAlgorithm, Decryptor, EncryptedData, Encryptor, KeyDerivationFunction, Randomness } from "./crypto"; import { ScryptKeyDerivationParams } from "./crypto/derivationParams"; import { Mnemonic } from "./mnemonic"; diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index 2e329f905..07cfd840a 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -1,7 +1,6 @@ import { assert } from "chai"; import path from "path"; -import { Address, Message, Transaction } from ".."; -import { ErrBadMnemonicEntropy, ErrInvariantFailed } from "../errors"; +import { Address, ErrBadMnemonicEntropy, ErrInvariantFailed, Message, Randomness, Transaction } from "../core"; import { DummyMnemonicOf12Words, loadMnemonic, @@ -10,7 +9,6 @@ import { loadTestWallet, TestWallet, } from "./../testutils/wallets"; -import { Randomness } from "./crypto"; import { Mnemonic } from "./mnemonic"; import { UserSecretKey } from "./userKeys"; import { UserSigner } from "./userSigner"; diff --git a/src/wallet/validatorKeys.ts b/src/wallet/validatorKeys.ts index 4b2b856f7..888f80c1b 100644 --- a/src/wallet/validatorKeys.ts +++ b/src/wallet/validatorKeys.ts @@ -1,4 +1,4 @@ -import { ErrInvariantFailed } from "../errors"; +import { ErrInvariantFailed } from "../core/errors"; import { guardLength } from "./assertions"; import { parseValidatorKey } from "./pem"; diff --git a/src/wallet/validatorSigner.ts b/src/wallet/validatorSigner.ts index 161c2dad1..7842c53a6 100644 --- a/src/wallet/validatorSigner.ts +++ b/src/wallet/validatorSigner.ts @@ -1,4 +1,4 @@ -import { ErrSignerCannotSign } from "../errors"; +import { ErrSignerCannotSign } from "../core/errors"; import { BLS, ValidatorSecretKey } from "./validatorKeys"; /** From 3e3117c9177da1c4fbc2a59845d48f3459cae6b1 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 15:08:17 +0200 Subject: [PATCH 156/214] Code review follow up --- src/abi/interaction.local.net.spec.ts | 5 +---- src/abi/interaction.spec.ts | 1 + src/abi/interaction.ts | 2 +- src/abi/smartContract.local.net.spec.ts | 5 +---- src/abi/smartContractResults.local.net.spec.ts | 2 +- src/networkProviders/apiNetworkProvider.dev.net.spec.ts | 4 +--- src/networkProviders/proxyNetworkProvider.dev.net.spec.ts | 6 ++---- src/transaction.local.net.spec.ts | 4 ++-- 8 files changed, 10 insertions(+), 19 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 44fe1a1ad..5457a2084 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -19,6 +19,7 @@ import { ManagedDecimalValue } from "./typesystem"; describe("test smart contract interactor", function () { let provider = createLocalnetProvider(); let alice: TestWallet; + const transactionComputer = new TransactionComputer(); before(async function () { ({ alice } = await loadTestWallets()); @@ -46,7 +47,6 @@ describe("test smart contract interactor", function () { }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); deployTransaction.signature = await alice.signer.sign( Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), ); @@ -283,7 +283,6 @@ describe("test smart contract interactor", function () { }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); deployTransaction.signature = await alice.signer.sign( Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), ); @@ -385,7 +384,6 @@ describe("test smart contract interactor", function () { }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); deployTransaction.signature = await alice.signer.sign( Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), ); @@ -483,7 +481,6 @@ describe("test smart contract interactor", function () { const transaction = options.transaction; const wallet = options.wallet; - const transactionComputer = new TransactionComputer(); transaction.signature = await wallet.signer.sign(transactionComputer.computeBytesForSigning(transaction)); } }); diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 1741424f1..efec69cef 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -23,6 +23,7 @@ describe("test smart contract interactor", function () { let provider = new MockNetworkProvider(); let alice: TestWallet; const transactionComputer = new TransactionComputer(); + before(async function () { ({ alice } = await loadTestWallets()); }); diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index b9ac422c4..835946968 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -21,7 +21,7 @@ interface ISmartContractWithinInteraction { } /** - * @deprecated component. Use "SmartContractTransactionsFactory" (for transactions) or "SmartContractQueriesController" (for queries), instead. + * @deprecated component. Use "SmartContractTransactionsFactory" (for transactions) or "SmartContractController" (for queries), instead. * * Interactions can be seen as mutable transaction & query builders. * diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 559108a85..09af4f948 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -29,6 +29,7 @@ describe("test on local testnet", function () { let provider = createLocalnetProvider(); let watcher: TransactionWatcher; let parser: SmartContractTransactionsOutcomeParser; + const transactionComputer = new TransactionComputer(); before(async function () { ({ alice, bob, carol } = await loadTestWallets()); @@ -61,7 +62,6 @@ describe("test on local testnet", function () { }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); deployTransaction.signature = await alice.signer.sign( Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), ); @@ -146,7 +146,6 @@ describe("test on local testnet", function () { }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); deployTransaction.signature = await alice.signer.sign( Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), ); @@ -224,7 +223,6 @@ describe("test on local testnet", function () { arguments: [new U32Value(10000)], }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); deployTransaction.signature = await alice.signer.sign( Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), ); @@ -327,7 +325,6 @@ describe("test on local testnet", function () { }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); deployTransaction.signature = await alice.signer.sign( Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), ); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 297034536..5f320b9ce 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -15,6 +15,7 @@ describe("fetch transactions from local testnet", function () { let watcher: TransactionWatcher; let parser: SmartContractTransactionsOutcomeParser; const transactionComputer = new TransactionComputer(); + before(async function () { ({ alice } = await loadTestWallets()); watcher = new TransactionWatcher({ @@ -99,7 +100,6 @@ describe("fetch transactions from local testnet", function () { }); deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - const transactionComputer = new TransactionComputer(); deployTransaction.signature = await alice.signer.sign( Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), ); diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index b63c5cfe9..96af455da 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -11,6 +11,7 @@ import { ApiNetworkProvider } from "./apiNetworkProvider"; describe("ApiNetworkProvider Tests", function () { const apiProvider = new ApiNetworkProvider("https://devnet-api.multiversx.com"); + const transactionComputer = new TransactionComputer(); it("should fetch network configuration", async () => { const result = await apiProvider.getNetworkConfig(); @@ -282,7 +283,6 @@ describe("ApiNetworkProvider Tests", function () { it("should simulate transaction", async () => { const bob = await loadTestWallet("bob"); - const transactionComputer = new TransactionComputer(); let transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -334,7 +334,6 @@ describe("ApiNetworkProvider Tests", function () { it("should estimate transaction cost", async function () { const bob = await loadTestWallet("bob"); - const transactionComputer = new TransactionComputer(); const transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -351,7 +350,6 @@ describe("ApiNetworkProvider Tests", function () { it("should send and await for completed transaction", async function () { this.timeout(30000); const bob = await loadTestWallet("bob"); - const transactionComputer = new TransactionComputer(); let transaction = new Transaction({ sender: bob.address, receiver: bob.address, diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index 07ac78785..b7d196264 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -11,7 +11,7 @@ import { ProxyNetworkProvider } from "./proxyNetworkProvider"; describe("ProxyNetworkProvider Tests", function () { const proxy = new ProxyNetworkProvider("https://devnet-gateway.multiversx.com"); - + const transactionComputer = new TransactionComputer(); it("should fetch network configuration", async () => { const result = await proxy.getNetworkConfig(); assert.equal(result.chainID, "D"); @@ -282,7 +282,7 @@ describe("ProxyNetworkProvider Tests", function () { it("should simulate transaction", async () => { const bob = await loadTestWallet("bob"); - const transactionComputer = new TransactionComputer(); + let transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -334,7 +334,6 @@ describe("ProxyNetworkProvider Tests", function () { it("should estimate transaction cost", async function () { const bob = await loadTestWallet("bob"); - const transactionComputer = new TransactionComputer(); const transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -351,7 +350,6 @@ describe("ProxyNetworkProvider Tests", function () { it("should send and await for completed transaction", async function () { this.timeout(50000); const bob = await loadTestWallet("bob"); - const transactionComputer = new TransactionComputer(); let transaction = new Transaction({ sender: bob.address, receiver: bob.address, diff --git a/src/transaction.local.net.spec.ts b/src/transaction.local.net.spec.ts index 07871ed76..8f1abc826 100644 --- a/src/transaction.local.net.spec.ts +++ b/src/transaction.local.net.spec.ts @@ -14,6 +14,7 @@ import { TransferTransactionsFactory } from "./transfers/transferTransactionsFac describe("test transaction", function () { let alice: TestWallet, bob: TestWallet; const transactionComputer = new TransactionComputer(); + before(async function () { ({ alice, bob } = await loadTestWallets()); }); @@ -56,8 +57,7 @@ describe("test transaction", function () { await bob.sync(provider); let initialBalanceOfBob = new BigNumber((await bob.getBalance(provider)).toString()); - transactionOne.nonce = alice.account.nonce; - alice.account.incrementNonce(); + transactionOne.nonce = alice.account.getNonceThenIncrement(); transactionTwo.nonce = alice.account.nonce; await signTransaction({ transaction: transactionOne, wallet: alice }); From 64d3b40d6123aec1b0f4a3fa6cac7eb8fc0d5612 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 15:15:31 +0200 Subject: [PATCH 157/214] Add new line and update comments --- src/abi/interaction.ts | 2 +- src/networkProviders/proxyNetworkProvider.dev.net.spec.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/abi/interaction.ts b/src/abi/interaction.ts index 835946968..e673de3fe 100644 --- a/src/abi/interaction.ts +++ b/src/abi/interaction.ts @@ -21,7 +21,7 @@ interface ISmartContractWithinInteraction { } /** - * @deprecated component. Use "SmartContractTransactionsFactory" (for transactions) or "SmartContractController" (for queries), instead. + * @deprecated component. Use "SmartContractTransactionsFactory" or "SmartContractController", instead. * * Interactions can be seen as mutable transaction & query builders. * diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index b7d196264..fc68c1bf7 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -12,6 +12,7 @@ import { ProxyNetworkProvider } from "./proxyNetworkProvider"; describe("ProxyNetworkProvider Tests", function () { const proxy = new ProxyNetworkProvider("https://devnet-gateway.multiversx.com"); const transactionComputer = new TransactionComputer(); + it("should fetch network configuration", async () => { const result = await proxy.getNetworkConfig(); assert.equal(result.chainID, "D"); From bca5c059d0d6200416a3a05b222ce7d379c1b792 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 15:28:35 +0200 Subject: [PATCH 158/214] Add back index.ts to root folder --- src/core/index.ts | 11 ---------- .../delegationTransactionsFactory.spec.ts | 3 ++- ...elegationTransactionsOutcomeParser.spec.ts | 3 ++- src/index.ts | 20 +++++++++++++++++++ ...anagementTransactionsOutcomeParser.spec.ts | 10 ++-------- src/wallet/users.spec.ts | 3 ++- 6 files changed, 28 insertions(+), 22 deletions(-) create mode 100644 src/index.ts diff --git a/src/core/index.ts b/src/core/index.ts index 9e402555e..237adc21a 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -6,17 +6,6 @@ require("./globals"); -export * from "../abi"; -export * from "../accountManagement"; -export * from "../accounts"; -export * from "../delegation"; -export * from "../entrypoints"; -export * from "../networkProviders"; -export * from "../relayed"; -export * from "../tokenManagement"; -export * from "../transactionsOutcomeParsers"; -export * from "../transfers"; -export * from "../wallet"; export * from "./address"; export * from "./asyncTimer"; export * from "./config"; diff --git a/src/delegation/delegationTransactionsFactory.spec.ts b/src/delegation/delegationTransactionsFactory.spec.ts index 47f325988..2b35d3000 100644 --- a/src/delegation/delegationTransactionsFactory.spec.ts +++ b/src/delegation/delegationTransactionsFactory.spec.ts @@ -1,6 +1,7 @@ import { assert } from "chai"; -import { Address, TransactionsFactoryConfig, ValidatorPublicKey } from "../core"; +import { Address, TransactionsFactoryConfig } from "../core"; import { DELEGATION_MANAGER_SC_ADDRESS_HEX } from "../core/constants"; +import { ValidatorPublicKey } from "../wallet"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; describe("test delegation transactions factory", function () { diff --git a/src/delegation/delegationTransactionsOutcomeParser.spec.ts b/src/delegation/delegationTransactionsOutcomeParser.spec.ts index c804a295a..99067b286 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.spec.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.spec.ts @@ -1,6 +1,7 @@ import { assert } from "chai"; -import { Address, SmartContractResult, TransactionEvent, TransactionLogs, TransactionOnNetwork } from "../core"; +import { Address, TransactionEvent, TransactionLogs, TransactionOnNetwork } from "../core"; import { b64TopicsToBytes } from "../testutils"; +import { SmartContractResult } from "../transactionsOutcomeParsers"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; describe("test delegation transactions outcome parser", () => { diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 000000000..2ed005e1a --- /dev/null +++ b/src/index.ts @@ -0,0 +1,20 @@ +/** + * A library for interacting with the MultiversX blockchain (in general) and Smart Contracts (in particular). + * + * @packageDocumentation + */ + +require("./globals"); + +export * from "./abi"; +export * from "./accountManagement"; +export * from "./accounts"; +export * from "./core"; +export * from "./delegation"; +export * from "./entrypoints"; +export * from "./networkProviders"; +export * from "./relayed"; +export * from "./tokenManagement"; +export * from "./transactionsOutcomeParsers"; +export * from "./transfers"; +export * from "./wallet"; diff --git a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts index b5d68676c..1c68feccd 100644 --- a/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionsOutcomeParser.spec.ts @@ -1,13 +1,7 @@ import { assert } from "chai"; -import { - Address, - ErrParseTransactionOutcome, - SmartContractResult, - TransactionEvent, - TransactionLogs, - TransactionOnNetwork, -} from "../core"; +import { Address, ErrParseTransactionOutcome, TransactionEvent, TransactionLogs, TransactionOnNetwork } from "../core"; import { b64TopicsToBytes } from "../testutils"; +import { SmartContractResult } from "../transactionsOutcomeParsers"; import { TokenManagementTransactionsOutcomeParser } from "./tokenManagementTransactionsOutcomeParser"; describe("test token management transactions outcome parser", () => { diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index 07cfd840a..c4578b03d 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -1,6 +1,6 @@ import { assert } from "chai"; import path from "path"; -import { Address, ErrBadMnemonicEntropy, ErrInvariantFailed, Message, Randomness, Transaction } from "../core"; +import { Address, ErrBadMnemonicEntropy, ErrInvariantFailed, Message, Transaction } from "../core"; import { DummyMnemonicOf12Words, loadMnemonic, @@ -9,6 +9,7 @@ import { loadTestWallet, TestWallet, } from "./../testutils/wallets"; +import { Randomness } from "./crypto"; import { Mnemonic } from "./mnemonic"; import { UserSecretKey } from "./userKeys"; import { UserSigner } from "./userSigner"; From aa4953e7e4f94512b97af44b91039c62cfbf3465 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 15:34:43 +0200 Subject: [PATCH 159/214] Remove INetworkConfig --- src/interface.ts | 7 ------- src/transaction.spec.ts | 28 ++++++++++++++-------------- src/transaction.ts | 5 +++-- src/transactionComputer.ts | 8 ++++---- 4 files changed, 21 insertions(+), 27 deletions(-) diff --git a/src/interface.ts b/src/interface.ts index 62ac22c37..d867b4629 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -26,10 +26,3 @@ export interface IPlainTransactionObject { guardianSignature?: string; relayerSignature?: string; } - -export interface INetworkConfig { - MinGasLimit: number; - GasPerDataByte: number; - GasPriceModifier: number; - ChainID: string; -} diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index 201360331..07c6c90f8 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -2,6 +2,7 @@ import { Buffer } from "buffer"; import { assert } from "chai"; import { Address } from "./address"; import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, TRANSACTION_OPTIONS_DEFAULT } from "./constants"; +import { NetworkConfig } from "./networkProviders"; import { ProtoSerializer } from "./proto"; import { TestWallet, loadTestWallets } from "./testutils"; import { Transaction } from "./transaction"; @@ -15,12 +16,11 @@ describe("test transaction", async () => { const transactionComputer = new TransactionComputer(); - const networkConfig = { - MinGasLimit: 50000, - GasPerDataByte: 1500, - GasPriceModifier: 0.01, - ChainID: "D", - }; + const networkConfig = new NetworkConfig(); + networkConfig.chainID = "D"; + networkConfig.minGasLimit = 50000n; + networkConfig.gasPerDataByte = 1500n; + networkConfig.gasPriceModifier = 0.01; before(async function () { wallets = await loadTestWallets(); @@ -28,7 +28,7 @@ describe("test transaction", async () => { it("should serialize transaction for signing (without data)", async () => { const transaction = new Transaction({ - chainID: networkConfig.ChainID, + chainID: networkConfig.chainID, sender: wallets.alice.address, receiver: wallets.bob.address, gasLimit: 50000n, @@ -48,7 +48,7 @@ describe("test transaction", async () => { it("should serialize transaction for signing (with data)", async () => { const transaction = new Transaction({ - chainID: networkConfig.ChainID, + chainID: networkConfig.chainID, sender: wallets.alice.address, receiver: wallets.bob.address, gasLimit: 70000n, @@ -143,7 +143,7 @@ describe("test transaction", async () => { it("should compute hash", async () => { const transaction = new Transaction({ - chainID: networkConfig.ChainID, + chainID: networkConfig.chainID, sender: wallets.alice.address, receiver: wallets.alice.address, gasLimit: 100000n, @@ -165,7 +165,7 @@ describe("test transaction", async () => { it("should compute hash (with usernames)", async () => { const transaction = new Transaction({ - chainID: networkConfig.ChainID, + chainID: networkConfig.chainID, sender: wallets.alice.address, receiver: wallets.alice.address, gasLimit: 100000n, @@ -428,7 +428,7 @@ describe("test transaction", async () => { it("computes fee, but should throw `NotEnoughGas` error", async () => { const transaction = new Transaction({ - chainID: networkConfig.ChainID, + chainID: networkConfig.chainID, sender: wallets.alice.address, receiver: wallets.alice.address, gasLimit: 50000n, @@ -458,7 +458,7 @@ describe("test transaction", async () => { it("computes fee (with data field)", async () => { const transaction = new Transaction({ - chainID: networkConfig.ChainID, + chainID: networkConfig.chainID, sender: wallets.alice.address, receiver: wallets.alice.address, gasLimit: 50000n + 12010n, @@ -798,7 +798,7 @@ describe("test transaction", async () => { }); it("should serialize transaction with relayer", async () => { const transaction = new Transaction({ - chainID: networkConfig.ChainID, + chainID: networkConfig.chainID, sender: wallets.alice.address, receiver: wallets.alice.address, relayer: wallets.bob.address, @@ -819,7 +819,7 @@ describe("test transaction", async () => { it("should test relayed v3", async () => { const transaction = new Transaction({ - chainID: networkConfig.ChainID, + chainID: networkConfig.chainID, sender: wallets.alice.address, receiver: wallets.alice.address, senderUsername: "alice", diff --git a/src/transaction.ts b/src/transaction.ts index a792173e6..7749191f0 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,7 +1,8 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; -import { INetworkConfig, IPlainTransactionObject } from "./interface"; +import { IPlainTransactionObject } from "./interface"; +import { NetworkConfig } from "./networkProviders"; import { interpretSignatureAsBuffer } from "./signature"; import { TransactionComputer } from "./transactionComputer"; @@ -444,7 +445,7 @@ export class Transaction { * Computes the current transaction fee based on the {@link NetworkConfig} and transaction properties * @param networkConfig {@link NetworkConfig} */ - computeFee(networkConfig: INetworkConfig): BigNumber { + computeFee(networkConfig: NetworkConfig): BigNumber { const computer = new TransactionComputer(); const fee = computer.computeTransactionFee(this, networkConfig); return new BigNumber(fee.toString()); diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index 1d204046e..d37889db4 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -6,7 +6,7 @@ import { TRANSACTION_OPTIONS_TX_HASH_SIGN, } from "./constants"; import * as errors from "./errors"; -import { INetworkConfig } from "./interface"; +import { NetworkConfig } from "./networkProviders"; import { ProtoSerializer } from "./proto"; import { Transaction } from "./transaction"; @@ -22,10 +22,10 @@ export class TransactionComputer { computeTransactionFee( transaction: { gasPrice: bigint; gasLimit: bigint; data: Uint8Array }, - networkConfig: INetworkConfig, + networkConfig: NetworkConfig, ): bigint { const moveBalanceGas = BigInt( - networkConfig.MinGasLimit + transaction.data.length * networkConfig.GasPerDataByte, + networkConfig.minGasLimit + BigInt(transaction.data.length) * networkConfig.gasPerDataByte, ); if (moveBalanceGas > transaction.gasLimit) { throw new errors.ErrNotEnoughGas(parseInt(transaction.gasLimit.toString(), 10)); @@ -39,7 +39,7 @@ export class TransactionComputer { const diff = transaction.gasLimit - moveBalanceGas; const modifiedGasPrice = BigInt( - new BigNumber(gasPrice.toString()).multipliedBy(new BigNumber(networkConfig.GasPriceModifier)).toFixed(0), + new BigNumber(gasPrice.toString()).multipliedBy(new BigNumber(networkConfig.gasPriceModifier)).toFixed(0), ); const processingFee = diff * modifiedGasPrice; From bd5ebb4e209135c36cc136d0e922c8237bc45ce4 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 15:43:46 +0200 Subject: [PATCH 160/214] Add back INetworkConfig --- src/interface.ts | 7 +++++++ src/transaction.spec.ts | 13 +++++++------ src/transaction.ts | 5 ++--- src/transactionComputer.ts | 4 ++-- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/interface.ts b/src/interface.ts index d867b4629..eb2d5283c 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -26,3 +26,10 @@ export interface IPlainTransactionObject { guardianSignature?: string; relayerSignature?: string; } + +export interface INetworkConfig { + minGasLimit: bigint; + gasPerDataByte: bigint; + gasPriceModifier: number; + chainID: string; +} diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index 07c6c90f8..cef90f0c8 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -2,7 +2,7 @@ import { Buffer } from "buffer"; import { assert } from "chai"; import { Address } from "./address"; import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, TRANSACTION_OPTIONS_DEFAULT } from "./constants"; -import { NetworkConfig } from "./networkProviders"; +import { INetworkConfig } from "./interface"; import { ProtoSerializer } from "./proto"; import { TestWallet, loadTestWallets } from "./testutils"; import { Transaction } from "./transaction"; @@ -16,11 +16,12 @@ describe("test transaction", async () => { const transactionComputer = new TransactionComputer(); - const networkConfig = new NetworkConfig(); - networkConfig.chainID = "D"; - networkConfig.minGasLimit = 50000n; - networkConfig.gasPerDataByte = 1500n; - networkConfig.gasPriceModifier = 0.01; + const networkConfig: INetworkConfig = { + minGasLimit: 50000n, + gasPerDataByte: 1500n, + gasPriceModifier: 0.01, + chainID: "D", + }; before(async function () { wallets = await loadTestWallets(); diff --git a/src/transaction.ts b/src/transaction.ts index 7749191f0..a792173e6 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,8 +1,7 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; -import { IPlainTransactionObject } from "./interface"; -import { NetworkConfig } from "./networkProviders"; +import { INetworkConfig, IPlainTransactionObject } from "./interface"; import { interpretSignatureAsBuffer } from "./signature"; import { TransactionComputer } from "./transactionComputer"; @@ -445,7 +444,7 @@ export class Transaction { * Computes the current transaction fee based on the {@link NetworkConfig} and transaction properties * @param networkConfig {@link NetworkConfig} */ - computeFee(networkConfig: NetworkConfig): BigNumber { + computeFee(networkConfig: INetworkConfig): BigNumber { const computer = new TransactionComputer(); const fee = computer.computeTransactionFee(this, networkConfig); return new BigNumber(fee.toString()); diff --git a/src/transactionComputer.ts b/src/transactionComputer.ts index d37889db4..d2b48eea2 100644 --- a/src/transactionComputer.ts +++ b/src/transactionComputer.ts @@ -6,7 +6,7 @@ import { TRANSACTION_OPTIONS_TX_HASH_SIGN, } from "./constants"; import * as errors from "./errors"; -import { NetworkConfig } from "./networkProviders"; +import { INetworkConfig } from "./interface"; import { ProtoSerializer } from "./proto"; import { Transaction } from "./transaction"; @@ -22,7 +22,7 @@ export class TransactionComputer { computeTransactionFee( transaction: { gasPrice: bigint; gasLimit: bigint; data: Uint8Array }, - networkConfig: NetworkConfig, + networkConfig: INetworkConfig, ): bigint { const moveBalanceGas = BigInt( networkConfig.minGasLimit + BigInt(transaction.data.length) * networkConfig.gasPerDataByte, From fb0e5702008d6b8c486e292abbf924e70b5ed469 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 15:58:51 +0200 Subject: [PATCH 161/214] Update index files --- src/core/globals.ts => globals.ts | 0 src/core/index.ts | 8 -------- 2 files changed, 8 deletions(-) rename src/core/globals.ts => globals.ts (100%) diff --git a/src/core/globals.ts b/globals.ts similarity index 100% rename from src/core/globals.ts rename to globals.ts diff --git a/src/core/index.ts b/src/core/index.ts index 237adc21a..e21d641bc 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,11 +1,3 @@ -/** - * A library for interacting with the MultiversX blockchain (in general) and Smart Contracts (in particular). - * - * @packageDocumentation - */ - -require("./globals"); - export * from "./address"; export * from "./asyncTimer"; export * from "./config"; From 7fc05d2b13cae7bce40be4ea7345a1b943de520f Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 29 Jan 2025 16:02:09 +0200 Subject: [PATCH 162/214] Move globals --- globals.ts => src/core/globals.ts | 0 src/core/index.ts | 2 ++ src/index.ts | 2 -- 3 files changed, 2 insertions(+), 2 deletions(-) rename globals.ts => src/core/globals.ts (100%) diff --git a/globals.ts b/src/core/globals.ts similarity index 100% rename from globals.ts rename to src/core/globals.ts diff --git a/src/core/index.ts b/src/core/index.ts index e21d641bc..ce95f33f4 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,3 +1,5 @@ +require("./globals"); + export * from "./address"; export * from "./asyncTimer"; export * from "./config"; diff --git a/src/index.ts b/src/index.ts index 2ed005e1a..4229e47be 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,8 +4,6 @@ * @packageDocumentation */ -require("./globals"); - export * from "./abi"; export * from "./accountManagement"; export * from "./accounts"; From ce865e8ef59cc326d2e16b2ad34bf09e377e11c9 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 30 Jan 2025 10:04:32 +0200 Subject: [PATCH 163/214] Add relayer fields --- src/core/transactionOnNetwork.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/transactionOnNetwork.ts b/src/core/transactionOnNetwork.ts index 1d5cc96c3..5d6cbafc6 100644 --- a/src/core/transactionOnNetwork.ts +++ b/src/core/transactionOnNetwork.ts @@ -28,6 +28,11 @@ export function prepareTransactionForBroadcasting(transaction: Transaction): any transaction.guardianSignature.length === 0 ? undefined : Buffer.from(transaction.guardianSignature).toString("hex"), + relayer: transaction.relayer.isEmpty() ? undefined : transaction.relayer.toBech32(), + relayerSignature: + transaction.relayerSignature.length === 0 + ? undefined + : Buffer.from(transaction.relayerSignature).toString("hex"), }; } From 94d246c8881edfad2cf617d67340bf4ae60b6579 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 30 Jan 2025 13:49:07 +0200 Subject: [PATCH 164/214] Update tests to use account.signTransaction --- src/abi/interaction.local.net.spec.ts | 121 ++++----- src/abi/interaction.spec.ts | 50 ++-- src/abi/smartContract.local.net.spec.ts | 120 ++++----- src/abi/smartContract.spec.ts | 35 ++- .../smartContractResults.local.net.spec.ts | 38 ++- src/accounts/account.spec.ts | 5 +- src/core/message.spec.ts | 19 +- src/core/transaction.spec.ts | 233 ++++++++---------- .../accountAwaiter.dev.net.spec.ts | 13 +- .../apiNetworkProvider.dev.net.spec.ts | 30 +-- .../proxyNetworkProvider.dev.net.spec.ts | 31 +-- src/proto/serializer.spec.ts | 54 ++-- .../relayedTransactionsFactory.spec.ts | 72 +++--- src/testutils/utils.ts | 15 +- 14 files changed, 346 insertions(+), 490 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 7ef19a40b..7169a5170 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -1,8 +1,8 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; import { promises } from "fs"; +import { Account } from "../accounts"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { TransactionWatcher } from "../core/transactionWatcher"; import { @@ -10,19 +10,18 @@ import { SmartContractTransactionsFactory, SmartContractTransactionsOutcomeParser, } from "../smartContracts"; -import { loadAbiRegistry, loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; +import { loadAbiRegistry, prepareDeployment } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; +import { getTestWalletsPath } from "../testutils/utils"; import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; import { ManagedDecimalValue } from "./typesystem"; - describe("test smart contract interactor", function () { let provider = createLocalnetProvider(); - let alice: TestWallet; - const transactionComputer = new TransactionComputer(); + let alice: Account; before(async function () { - ({ alice } = await loadTestWallets()); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); }); it("should interact with 'answer' (local testnet) using the SmartContractTransactionsFactory", async function () { @@ -31,7 +30,6 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); let network = await provider.getNetworkConfig(); - await alice.sync(provider); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ @@ -45,14 +43,12 @@ describe("test smart contract interactor", function () { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); + deployTransaction.nonce = BigInt(alice.nonce.valueOf()); - deployTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), - ); + deployTransaction.signature = alice.signTransaction(deployTransaction); - const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); - alice.account.incrementNonce(); + const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); + alice.incrementNonce(); const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { @@ -89,12 +85,10 @@ describe("test smart contract interactor", function () { function: "getUltimateAnswer", gasLimit: 3000000n, }); - transaction.nonce = BigInt(alice.account.nonce.valueOf()); - transaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(transaction)), - ); + transaction.nonce = BigInt(alice.nonce.valueOf()); + transaction.signature = alice.signTransaction(transaction); - alice.account.incrementNonce(); + alice.incrementNonce(); await provider.sendTransaction(transaction); @@ -104,12 +98,10 @@ describe("test smart contract interactor", function () { function: "getUltimateAnswer", gasLimit: 3000000n, }); - transaction.nonce = BigInt(alice.account.nonce.valueOf()); - transaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(transaction)), - ); + transaction.nonce = BigInt(alice.nonce.valueOf()); + transaction.signature = alice.signTransaction(transaction); - alice.account.incrementNonce(); + alice.incrementNonce(); const executeTxHash = await provider.sendTransaction(transaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(executeTxHash); @@ -132,7 +124,6 @@ describe("test smart contract interactor", function () { }); let network = await provider.getNetworkConfig(); - await alice.sync(provider); // Deploy the contract let deployTransaction = await prepareDeployment({ @@ -159,7 +150,7 @@ describe("test smart contract interactor", function () { // returnEgld() let returnEgldTransaction = returnEgldInteraction .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) + .useThenIncrementNonceOf(alice) .buildTransaction(); let additionInteraction = contract.methods @@ -172,7 +163,7 @@ describe("test smart contract interactor", function () { // addition() let additionTransaction = additionInteraction .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) + .useThenIncrementNonceOf(alice) .buildTransaction(); // log @@ -186,7 +177,7 @@ describe("test smart contract interactor", function () { // mdLn() let mdLnTransaction = mdLnInteraction .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) + .useThenIncrementNonceOf(alice) .buildTransaction(); let additionVarInteraction = contract.methods @@ -202,7 +193,7 @@ describe("test smart contract interactor", function () { // addition() let additionVarTransaction = additionVarInteraction .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) + .useThenIncrementNonceOf(alice) .buildTransaction(); let lnVarInteraction = contract.methods @@ -215,7 +206,7 @@ describe("test smart contract interactor", function () { // managed_decimal_ln_var() let lnVarTransaction = lnVarInteraction .withSender(alice.address) - .useThenIncrementNonceOf(alice.account) + .useThenIncrementNonceOf(alice) .buildTransaction(); // returnEgld() @@ -266,7 +257,6 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/counter.abi.json"); let network = await provider.getNetworkConfig(); - await alice.sync(provider); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ @@ -281,14 +271,12 @@ describe("test smart contract interactor", function () { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); + deployTransaction.nonce = BigInt(alice.nonce.valueOf()); - deployTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), - ); + deployTransaction.signature = alice.signTransaction(deployTransaction); - const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); - alice.account.incrementNonce(); + const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); + alice.incrementNonce(); const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { @@ -312,13 +300,11 @@ describe("test smart contract interactor", function () { function: "increment", gasLimit: 3000000n, }); - incrementTransaction.nonce = BigInt(alice.account.nonce.valueOf()); + incrementTransaction.nonce = BigInt(alice.nonce.valueOf()); - incrementTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(incrementTransaction)), - ); + incrementTransaction.signature = alice.signTransaction(incrementTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); // Query "get()" const query = queryController.createQuery({ @@ -341,19 +327,15 @@ describe("test smart contract interactor", function () { function: "decrement", gasLimit: 3000000n, }); - decrementTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - decrementTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(decrementTransaction)), - ); + decrementTransaction.nonce = alice.nonce; + decrementTransaction.signature = alice.signTransaction(decrementTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); await provider.sendTransaction(decrementTransaction); - decrementTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - decrementTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(decrementTransaction)), - ); + decrementTransaction.nonce = alice.nonce; + decrementTransaction.signature = alice.signTransaction(decrementTransaction); const decrementTxHash = await provider.sendTransaction(decrementTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(decrementTxHash); @@ -367,7 +349,6 @@ describe("test smart contract interactor", function () { let parser = new SmartContractTransactionsOutcomeParser({ abi: abiRegistry }); let network = await provider.getNetworkConfig(); - await alice.sync(provider); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ @@ -382,14 +363,12 @@ describe("test smart contract interactor", function () { bytecode: bytecode, gasLimit: 100000000n, }); - deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), - ); + deployTransaction.signature = alice.signTransaction(deployTransaction); - const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); - alice.account.incrementNonce(); + const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); + alice.incrementNonce(); const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { @@ -409,12 +388,10 @@ describe("test smart contract interactor", function () { arguments: ["lucky", "EGLD", 1, null, null, 1, null, null], gasLimit: 30000000n, }); - startTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - startTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(startTransaction)), - ); + startTransaction.nonce = alice.nonce; + startTransaction.signature = alice.signTransaction(startTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); const startTxHash = await provider.sendTransaction(startTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(startTxHash); @@ -429,12 +406,10 @@ describe("test smart contract interactor", function () { arguments: ["lucky"], gasLimit: 5000000n, }); - lotteryStatusTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - lotteryStatusTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(lotteryStatusTransaction)), - ); + lotteryStatusTransaction.nonce = alice.nonce; + lotteryStatusTransaction.signature = alice.signTransaction(lotteryStatusTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); const statusTxHash = await provider.sendTransaction(lotteryStatusTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(statusTxHash); @@ -450,12 +425,10 @@ describe("test smart contract interactor", function () { arguments: ["lucky"], gasLimit: 5000000n, }); - lotteryInfoTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - lotteryInfoTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(lotteryInfoTransaction)), - ); + lotteryInfoTransaction.nonce = alice.nonce; + lotteryInfoTransaction.signature = alice.signTransaction(lotteryInfoTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); const infoTxHash = await provider.sendTransaction(lotteryInfoTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(infoTxHash); @@ -477,10 +450,10 @@ describe("test smart contract interactor", function () { }); }); - async function signTransaction(options: { transaction: Transaction; wallet: TestWallet }) { + async function signTransaction(options: { transaction: Transaction; wallet: Account }) { const transaction = options.transaction; const wallet = options.wallet; - transaction.signature = await wallet.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = wallet.signTransaction(transaction); } }); diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index edfe365a6..9c2e2c59a 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -1,18 +1,13 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; +import { Account } from "../accounts"; import { Address } from "../core/address"; import { SmartContractQueryResponse } from "../core/smartContractQuery"; import { Token, TokenTransfer } from "../core/tokens"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { SmartContractController } from "../smartContracts"; -import { - loadAbiRegistry, - loadTestWallets, - MockNetworkProvider, - setupUnitTestWatcherTimeouts, - TestWallet, -} from "../testutils"; +import { loadAbiRegistry, MockNetworkProvider, setupUnitTestWatcherTimeouts } from "../testutils"; +import { getTestWalletsPath } from "../testutils/utils"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; import { SmartContract } from "./smartContract"; @@ -21,11 +16,10 @@ import { BigUIntValue, BytesValue, OptionalValue, OptionValue, TokenIdentifierVa describe("test smart contract interactor", function () { let dummyAddress = new Address("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"); let provider = new MockNetworkProvider(); - let alice: TestWallet; - const transactionComputer = new TransactionComputer(); + let alice: Account; before(async function () { - ({ alice } = await loadTestWallets()); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); }); it("should set transaction fields", async function () { @@ -249,7 +243,7 @@ describe("test smart contract interactor", function () { // Execute, do not wait for execution let transaction = interaction.withSender(alice.address).withNonce(0n).buildTransaction(); transaction.sender = alice.address; - transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = alice.signTransaction(transaction); let hash = await provider.sendTransaction(transaction); assert.equal(transaction.nonce, 0n); assert.equal(transaction.data.toString(), "getUltimateAnswer"); @@ -257,7 +251,7 @@ describe("test smart contract interactor", function () { transaction = interaction.withNonce(1n).buildTransaction(); transaction.sender = alice.address; - transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = alice.signTransaction(transaction); hash = await provider.sendTransaction(transaction); assert.equal(transaction.nonce, 1n); assert.equal(hash, "ad513ce7c5d371d30e48f073326899766736eac1ac231d847d45bc3facbcb496"); @@ -265,7 +259,7 @@ describe("test smart contract interactor", function () { // Execute, and wait for execution transaction = interaction.withNonce(2n).buildTransaction(); transaction.sender = alice.address; - transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = alice.signTransaction(transaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs", "getUltimateAnswer"); hash = await provider.sendTransaction(transaction); let responseExecute = await controller.awaitCompletedExecute(hash); @@ -314,9 +308,7 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - incrementTransaction.signature = await alice.signer.sign( - transactionComputer.computeBytesForSigning(incrementTransaction), - ); + incrementTransaction.signature = alice.signTransaction(incrementTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@08", "increment"); let hash = await provider.sendTransaction(incrementTransaction); let responseExecute = await controller.awaitCompletedExecute(hash); @@ -330,22 +322,16 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - decrementTransaction.signature = await alice.signer.sign( - transactionComputer.computeBytesForSigning(decrementTransaction), - ); + decrementTransaction.signature = alice.signTransaction(decrementTransaction); await provider.sendTransaction(decrementTransaction); // Decrement #2 decrementTransaction = decrementInteraction.withNonce(16n).buildTransaction(); - decrementTransaction.signature = await alice.signer.sign( - transactionComputer.computeBytesForSigning(decrementTransaction), - ); + decrementTransaction.signature = alice.signTransaction(decrementTransaction); await provider.sendTransaction(decrementTransaction); // Decrement #3 decrementTransaction = decrementInteraction.withNonce(17n).buildTransaction(); - decrementTransaction.signature = await alice.signer.sign( - transactionComputer.computeBytesForSigning(decrementTransaction), - ); + decrementTransaction.signature = alice.signTransaction(decrementTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@05", "decrement"); hash = await provider.sendTransaction(decrementTransaction); responseExecute = await controller.awaitCompletedExecute(hash); @@ -386,9 +372,7 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - startTransaction.signature = await alice.signer.sign( - transactionComputer.computeBytesForSigning(startTransaction), - ); + startTransaction.signature = alice.signTransaction(startTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b", "start"); let hash = await provider.sendTransaction(startTransaction); @@ -405,9 +389,7 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - statusTransaction.signature = await alice.signer.sign( - transactionComputer.computeBytesForSigning(statusTransaction), - ); + statusTransaction.signature = alice.signTransaction(statusTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@01", "status"); hash = await provider.sendTransaction(startTransaction); @@ -425,9 +407,7 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - getLotteryInfoTransaction.signature = await alice.signer.sign( - transactionComputer.computeBytesForSigning(getLotteryInfoTransaction), - ); + getLotteryInfoTransaction.signature = alice.signTransaction(getLotteryInfoTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult( "@6f6b@0000000b6c75636b792d746f6b656e000000010100000000000000005fc2b9dbffffffff00000001640000000a140ec80fa7ee88000000", "getLotteryInfo", diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 336a0b816..cec28ed12 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import { promises } from "fs"; +import { Account } from "../accounts"; import { Logger } from "../core/logger"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { TransactionWatcher } from "../core/transactionWatcher"; import { @@ -9,9 +9,8 @@ import { SmartContractTransactionsFactory, SmartContractTransactionsOutcomeParser, } from "../smartContracts"; -import { stringifyBigIntJSON } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; -import { loadTestWallets, TestWallet } from "../testutils/wallets"; +import { getTestWalletsPath, stringifyBigIntJSON } from "../testutils/utils"; import { decodeUnsignedNumber } from "./codec"; import { SmartContract } from "./smartContract"; import { @@ -25,14 +24,15 @@ import { } from "./typesystem"; describe("test on local testnet", function () { - let alice: TestWallet, bob: TestWallet, carol: TestWallet; + let alice: Account, bob: Account, carol: Account; let provider = createLocalnetProvider(); let watcher: TransactionWatcher; let parser: SmartContractTransactionsOutcomeParser; - const transactionComputer = new TransactionComputer(); before(async function () { - ({ alice, bob, carol } = await loadTestWallets()); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); + bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); + carol = await Account.newFromPem(`${getTestWalletsPath()}/carol.pem`); watcher = new TransactionWatcher({ getTransaction: async (hash: string) => { @@ -49,7 +49,6 @@ describe("test on local testnet", function () { TransactionWatcher.DefaultTimeout = 50000; let network = await provider.getNetworkConfig(); - await alice.sync(provider); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); @@ -60,26 +59,22 @@ describe("test on local testnet", function () { bytecode: bytecode, gasLimit: 4000000n, }); - deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); + deployTransaction.nonce = BigInt(alice.nonce.valueOf()); - deployTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), - ); + deployTransaction.signature = alice.signTransaction(deployTransaction); - const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); - alice.account.incrementNonce(); + const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); + alice.incrementNonce(); const smartContractCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 4000000n, }); - smartContractCallTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - smartContractCallTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(smartContractCallTransaction)), - ); + smartContractCallTransaction.nonce = alice.nonce; + smartContractCallTransaction.signature = alice.signTransaction(smartContractCallTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); const simulateOne = factory.createTransactionForExecute(alice.address, { function: "increment", @@ -87,12 +82,10 @@ describe("test on local testnet", function () { gasLimit: 200000n, }); - simulateOne.nonce = BigInt(alice.account.nonce.valueOf()); - simulateOne.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(simulateOne)), - ); + simulateOne.nonce = alice.nonce; + simulateOne.signature = alice.signTransaction(simulateOne); - alice.account.incrementNonce(); + alice.incrementNonce(); const simulateTwo = factory.createTransactionForExecute(alice.address, { function: "foobar", @@ -100,12 +93,10 @@ describe("test on local testnet", function () { gasLimit: 700000n, }); - simulateTwo.nonce = BigInt(alice.account.nonce.valueOf()); - simulateTwo.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(simulateTwo)), - ); + simulateTwo.nonce = alice.nonce; + simulateTwo.signature = alice.signTransaction(simulateTwo); - alice.account.incrementNonce(); + alice.incrementNonce(); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); @@ -133,7 +124,6 @@ describe("test on local testnet", function () { TransactionWatcher.DefaultTimeout = 50000; let network = await provider.getNetworkConfig(); - await alice.sync(provider); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); @@ -144,38 +134,32 @@ describe("test on local testnet", function () { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), - ); + deployTransaction.signature = alice.signTransaction(deployTransaction); - const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); - alice.account.incrementNonce(); + const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); + alice.incrementNonce(); const firstScCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, }); - firstScCallTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - firstScCallTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(firstScCallTransaction)), - ); + firstScCallTransaction.nonce = alice.nonce; + firstScCallTransaction.signature = alice.signTransaction(firstScCallTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); const secondScCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, }); - secondScCallTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - secondScCallTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(secondScCallTransaction)), - ); + secondScCallTransaction.nonce = alice.nonce; + secondScCallTransaction.signature = alice.signTransaction(secondScCallTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); @@ -210,7 +194,6 @@ describe("test on local testnet", function () { TransactionWatcher.DefaultTimeout = 50000; let network = await provider.getNetworkConfig(); - await alice.sync(provider); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); @@ -222,13 +205,11 @@ describe("test on local testnet", function () { gasLimit: 50000000n, arguments: [new U32Value(10000)], }); - deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - deployTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), - ); + deployTransaction.nonce = alice.nonce; + deployTransaction.signature = alice.signTransaction(deployTransaction); - const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); - alice.account.incrementNonce(); + const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); + alice.incrementNonce(); const transactionMintBob = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -236,12 +217,10 @@ describe("test on local testnet", function () { gasLimit: 9000000n, arguments: [new AddressValue(bob.address), new U32Value(1000)], }); - transactionMintBob.nonce = BigInt(alice.account.nonce.valueOf()); - transactionMintBob.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(transactionMintBob)), - ); + transactionMintBob.nonce = alice.nonce; + transactionMintBob.signature = alice.signTransaction(transactionMintBob); - alice.account.incrementNonce(); + alice.incrementNonce(); const transactionMintCarol = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -249,12 +228,10 @@ describe("test on local testnet", function () { gasLimit: 9000000n, arguments: [new AddressValue(carol.address), new U32Value(1500)], }); - transactionMintCarol.nonce = BigInt(alice.account.nonce.valueOf()); - transactionMintCarol.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(transactionMintCarol)), - ); + transactionMintCarol.nonce = alice.nonce; + transactionMintCarol.signature = alice.signTransaction(transactionMintCarol); - alice.account.incrementNonce(); + alice.incrementNonce(); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); @@ -312,7 +289,6 @@ describe("test on local testnet", function () { TransactionWatcher.DefaultTimeout = 50000; let network = await provider.getNetworkConfig(); - await alice.sync(provider); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); @@ -323,14 +299,12 @@ describe("test on local testnet", function () { bytecode: bytecode, gasLimit: 50000000n, }); - deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), - ); + deployTransaction.signature = alice.signTransaction(deployTransaction); - const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); - alice.account.incrementNonce(); + const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); + alice.incrementNonce(); const startTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -348,12 +322,10 @@ describe("test on local testnet", function () { OptionalValue.newMissing(), ], }); - startTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - startTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(startTransaction)), - ); + startTransaction.nonce = alice.nonce; + startTransaction.signature = alice.signTransaction(startTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); // Broadcast & execute const deployTx = await provider.sendTransaction(deployTransaction); diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index c8f264093..c74182628 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -1,14 +1,14 @@ import { assert } from "chai"; +import { Account } from "../accounts"; import { Address } from "../core/address"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionStatus } from "../core/transactionStatus"; import { TransactionWatcher } from "../core/transactionWatcher"; import { - loadTestWallets, + getTestWalletsPath, MarkCompleted, MockNetworkProvider, setupUnitTestWatcherTimeouts, - TestWallet, Wait, } from "../testutils"; import { Code } from "./code"; @@ -20,11 +20,11 @@ import { BytesValue } from "./typesystem/bytes"; describe("test contract", () => { let provider = new MockNetworkProvider(); let chainID = "test"; - let alice: TestWallet; + let alice: Account; const computer = new TransactionComputer(); before(async function () { - ({ alice } = await loadTestWallets()); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); }); it("should compute contract address", async () => { @@ -52,16 +52,11 @@ describe("test contract", () => { deployer: alice.address, }); - provider.mockUpdateAccount(alice.address, (account) => { - account.nonce = 42n; - }); - - await alice.sync(provider); - deployTransaction.nonce = alice.account.nonce; + deployTransaction.nonce = alice.nonce; assert.equal(deployTransaction.data.toString(), "01020304@0500@0100"); assert.equal(deployTransaction.gasLimit, 1000000n); - assert.equal(deployTransaction.nonce, 42n); + assert.equal(deployTransaction.nonce, alice.nonce); // Compute & set the contract address contract.setAddress(SmartContract.computeAddress(alice.address, 42n)); @@ -71,7 +66,7 @@ describe("test contract", () => { ); // Sign the transaction - deployTransaction.signature = await alice.signer.sign(computer.computeBytesForSigning(deployTransaction)); + deployTransaction.signature = alice.signTransaction(deployTransaction); // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); @@ -119,10 +114,9 @@ describe("test contract", () => { caller: alice.address, }); - await alice.sync(provider); - callTransactionOne.nonce = alice.account.nonce; - alice.account.incrementNonce(); - callTransactionTwo.nonce = alice.account.nonce; + callTransactionOne.nonce = alice.nonce; + alice.incrementNonce(); + callTransactionTwo.nonce = alice.nonce; assert.equal(callTransactionOne.nonce, 42n); assert.equal(callTransactionOne.data.toString(), "helloEarth@05@0123"); @@ -132,8 +126,8 @@ describe("test contract", () => { assert.equal(callTransactionTwo.gasLimit, 1500000n); // Sign transactions, broadcast them - callTransactionOne.signature = await alice.signer.sign(computer.computeBytesForSigning(callTransactionOne)); - callTransactionTwo.signature = await alice.signer.sign(computer.computeBytesForSigning(callTransactionTwo)); + callTransactionOne.signature = alice.signTransaction(callTransactionOne); + callTransactionTwo.signature = alice.signTransaction(callTransactionTwo); let hashOne = await provider.sendTransaction(callTransactionOne); let hashTwo = await provider.sendTransaction(callTransactionTwo); @@ -179,15 +173,14 @@ describe("test contract", () => { account.nonce = 42n; }); - await alice.sync(provider); - deployTransaction.nonce = alice.account.nonce; + deployTransaction.nonce = alice.nonce; assert.equal(deployTransaction.data.toString(), "upgradeContract@01020304@0100"); assert.equal(deployTransaction.gasLimit, 1000000n); assert.equal(deployTransaction.nonce, 42n); // Sign the transaction - deployTransaction.signature = await alice.signer.sign(computer.computeBytesForSigning(deployTransaction)); + deployTransaction.signature = alice.signTransaction(deployTransaction); // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index b681f19b9..e78bfd1f3 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -1,23 +1,22 @@ import { assert } from "chai"; import { promises } from "fs"; -import { TransactionComputer } from "../core/transactionComputer"; +import { Account } from "../accounts"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { TransactionWatcher } from "../core/transactionWatcher"; import { SmartContractTransactionsFactory, SmartContractTransactionsOutcomeParser } from "../smartContracts"; -import { loadTestWallets, prepareDeployment, TestWallet } from "../testutils"; +import { getTestWalletsPath, prepareDeployment } from "../testutils"; import { createLocalnetProvider } from "../testutils/networkProviders"; import { ContractFunction } from "./function"; import { SmartContract } from "./smartContract"; describe("fetch transactions from local testnet", function () { - let alice: TestWallet; + let alice: Account; let provider = createLocalnetProvider(); let watcher: TransactionWatcher; let parser: SmartContractTransactionsOutcomeParser; - const transactionComputer = new TransactionComputer(); before(async function () { - ({ alice } = await loadTestWallets()); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); watcher = new TransactionWatcher({ getTransaction: async (hash: string) => { return await provider.getTransaction(hash); @@ -34,7 +33,6 @@ describe("fetch transactions from local testnet", function () { TransactionWatcher.DefaultTimeout = 50000; let network = await provider.getNetworkConfig(); - await alice.sync(provider); // Deploy let contract = new SmartContract({}); @@ -56,12 +54,10 @@ describe("fetch transactions from local testnet", function () { caller: alice.address, }); - transactionIncrement.nonce = alice.account.nonce; - transactionIncrement.signature = await alice.signer.sign( - transactionComputer.computeBytesForSigning(transactionIncrement), - ); + transactionIncrement.nonce = alice.nonce; + transactionIncrement.signature = alice.signTransaction(transactionIncrement); - alice.account.incrementNonce(); + alice.incrementNonce(); // Broadcast & execute const txHashDeploy = await provider.sendTransaction(transactionDeploy); @@ -87,7 +83,6 @@ describe("fetch transactions from local testnet", function () { TransactionWatcher.DefaultTimeout = 50000; let network = await provider.getNetworkConfig(); - await alice.sync(provider); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); @@ -98,26 +93,21 @@ describe("fetch transactions from local testnet", function () { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = BigInt(alice.account.nonce.valueOf()); + deployTransaction.nonce = alice.nonce; + deployTransaction.signature = alice.signTransaction(deployTransaction); - deployTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(deployTransaction)), - ); - - const contractAddress = SmartContract.computeAddress(alice.address, alice.account.nonce); - alice.account.incrementNonce(); + const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); + alice.incrementNonce(); const smartContractCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, }); - smartContractCallTransaction.nonce = BigInt(alice.account.nonce.valueOf()); - smartContractCallTransaction.signature = await alice.signer.sign( - Buffer.from(transactionComputer.computeBytesForSigning(smartContractCallTransaction)), - ); + smartContractCallTransaction.nonce = alice.nonce; + smartContractCallTransaction.signature = alice.signTransaction(smartContractCallTransaction); - alice.account.incrementNonce(); + alice.incrementNonce(); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); diff --git a/src/accounts/account.spec.ts b/src/accounts/account.spec.ts index fa4c1992e..853663098 100644 --- a/src/accounts/account.spec.ts +++ b/src/accounts/account.spec.ts @@ -1,14 +1,13 @@ import { assert } from "chai"; -import { resolve } from "path"; import { Address, Message, Transaction } from "../core"; +import { getTestWalletsPath } from "../testutils/utils"; import { KeyPair, UserSecretKey } from "../wallet"; import { Account } from "./account"; describe("test account methods", function () { - const testWallets = resolve(__dirname, "..", "testdata", "testwallets"); const DUMMY_MNEMONIC = "moral volcano peasant pass circle pen over picture flat shop clap goat never lyrics gather prepare woman film husband gravity behind test tiger improve"; - const alice = `${testWallets}/alice.pem`; + const alice = `${getTestWalletsPath()}/alice.pem`; it("should create account from pem file", async function () { const account = await Account.newFromPem(alice); diff --git a/src/core/message.spec.ts b/src/core/message.spec.ts index 8fb62d5c2..2cb0776e2 100644 --- a/src/core/message.spec.ts +++ b/src/core/message.spec.ts @@ -1,15 +1,16 @@ import { assert } from "chai"; -import { TestWallet, loadTestWallets } from "../testutils"; +import { Account } from "../accounts"; +import { getTestWalletsPath } from "../testutils/utils"; import { UserVerifier } from "../wallet"; import { DEFAULT_MESSAGE_VERSION, SDK_JS_SIGNER, UNKNOWN_SIGNER } from "./constants"; import { Message, MessageComputer } from "./message"; describe("test message", () => { - let alice: TestWallet; + let alice: Account; const messageComputer = new MessageComputer(); before(async function () { - ({ alice } = await loadTestWallets()); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); }); it("should test message compute bytes for signing", async () => { @@ -32,10 +33,10 @@ describe("test message", () => { const message = new Message({ data: data, - address: alice.getAddress(), + address: alice.address, }); - message.signature = await alice.signer.sign(messageComputer.computeBytesForSigning(message)); + message.signature = alice.signMessage(message); assert.equal( Buffer.from(message.signature).toString("hex"), @@ -53,13 +54,13 @@ describe("test message", () => { }); const unpackedMessage = messageComputer.unpackMessage(packedMessage); - assert.deepEqual(unpackedMessage.address, alice.getAddress()); + assert.deepEqual(unpackedMessage.address, alice.address); assert.deepEqual(unpackedMessage.data, message.data); assert.deepEqual(unpackedMessage.signature, message.signature); assert.deepEqual(unpackedMessage.version, message.version); assert.deepEqual(unpackedMessage.signer, message.signer); - const verifier = UserVerifier.fromAddress(alice.getAddress()); + const verifier = UserVerifier.fromAddress(alice.address); const isValid = verifier.verify( Buffer.from(messageComputer.computeBytesForVerifying(unpackedMessage)), Buffer.from(unpackedMessage.signature!), @@ -78,7 +79,7 @@ describe("test message", () => { }; const message = messageComputer.unpackMessage(legacyMessage); - assert.deepEqual(message.address, alice.getAddress()); + assert.deepEqual(message.address, alice.address); assert.deepEqual(Buffer.from(message.data).toString(), "this is a test message"); assert.deepEqual( Buffer.from(message.signature!).toString("hex"), @@ -97,7 +98,7 @@ describe("test message", () => { }; const message = messageComputer.unpackMessage(packedMessage); - assert.deepEqual(message.address, alice.getAddress()); + assert.deepEqual(message.address, alice.address); assert.deepEqual(Buffer.from(message.data).toString(), "this is a test message"); assert.deepEqual( Buffer.from(message.signature!).toString("hex"), diff --git a/src/core/transaction.spec.ts b/src/core/transaction.spec.ts index dfd6819bb..40f48a4d8 100644 --- a/src/core/transaction.spec.ts +++ b/src/core/transaction.spec.ts @@ -1,7 +1,8 @@ import { Buffer } from "buffer"; import { assert } from "chai"; +import { Account } from "../accounts"; import { ProtoSerializer } from "../proto"; -import { TestWallet, loadTestWallets } from "../testutils"; +import { getTestWalletsPath } from "../testutils/utils"; import { UserPublicKey, UserVerifier } from "../wallet"; import { Address } from "./address"; import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, TRANSACTION_OPTIONS_DEFAULT } from "./constants"; @@ -10,7 +11,9 @@ import { Transaction } from "./transaction"; import { TransactionComputer } from "./transactionComputer"; describe("test transaction", async () => { - let wallets: Record; + let alice: Account; + let bob: Account; + let carol: Account; const minGasLimit = 50000; const minGasPrice = 1000000000; @@ -24,14 +27,16 @@ describe("test transaction", async () => { }; before(async function () { - wallets = await loadTestWallets(); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); + bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); + carol = await Account.newFromPem(`${getTestWalletsPath()}/carol.pem`); }); it("should serialize transaction for signing (without data)", async () => { const transaction = new Transaction({ chainID: networkConfig.chainID, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, value: 0n, version: 2, @@ -50,8 +55,8 @@ describe("test transaction", async () => { it("should serialize transaction for signing (with data)", async () => { const transaction = new Transaction({ chainID: networkConfig.chainID, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 70000n, value: 1000000000000000000n, version: 2, @@ -72,16 +77,14 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: BigInt(minGasLimit), chainID: "local-testnet", }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -97,17 +100,15 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 90n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: 80000n, data: Buffer.from("hello"), chainID: "local-testnet", }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -122,8 +123,8 @@ describe("test transaction", async () => { it("should sign transaction (with usernames)", async () => { const transaction = new Transaction({ chainID: "T", - sender: wallets.carol.address, - receiver: wallets.alice.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, value: 1000000000000000000n, version: 2, @@ -132,9 +133,7 @@ describe("test transaction", async () => { receiverUsername: "alice", }); - transaction.signature = await wallets.carol.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -145,8 +144,8 @@ describe("test transaction", async () => { it("should compute hash", async () => { const transaction = new Transaction({ chainID: networkConfig.chainID, - sender: wallets.alice.address, - receiver: wallets.alice.address, + sender: alice.address, + receiver: alice.address, gasLimit: 100000n, value: 1000000000000n, version: 2, @@ -167,8 +166,8 @@ describe("test transaction", async () => { it("should compute hash (with usernames)", async () => { const transaction = new Transaction({ chainID: networkConfig.chainID, - sender: wallets.alice.address, - receiver: wallets.alice.address, + sender: alice.address, + receiver: alice.address, gasLimit: 100000n, value: 1000000000000n, version: 2, @@ -192,8 +191,8 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: BigInt(minGasLimit), chainID: "local-testnet", @@ -211,17 +210,15 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 91n, value: 10000000000000000000n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: 100000n, data: Buffer.from("for the book"), chainID: "local-testnet", }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -237,17 +234,15 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 92n, value: BigInt("123456789000000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: 100000n, data: Buffer.from("for the spaceship"), chainID: "local-testnet", }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -263,8 +258,8 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 0n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: 80000n, data: Buffer.from("hello"), @@ -272,9 +267,7 @@ describe("test transaction", async () => { version: 1, }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -290,16 +283,14 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: BigInt(minGasLimit), chainID: "local-testnet", }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -318,16 +309,14 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: BigInt(minGasLimit), chainID: "local-testnet", }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -354,9 +343,7 @@ describe("test transaction", async () => { chainID: "T", }); - transaction.signature = await wallets.carol.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -369,12 +356,10 @@ describe("test transaction", async () => { }); it("should sign & compute hash (guarded transaction)", async () => { - const alice = wallets.alice; - const transaction = new Transaction({ chainID: "local-testnet", sender: alice.address, - receiver: wallets.bob.address, + receiver: bob.address, gasLimit: 150000n, gasPrice: 1000000000n, data: new Uint8Array(Buffer.from("test data field")), @@ -385,7 +370,7 @@ describe("test transaction", async () => { guardian: Address.newFromBech32("erd1x23lzn8483xs2su4fak0r0dqx6w38enpmmqf2yrkylwq7mfnvyhsxqw57y"), }); transaction.guardianSignature = new Uint8Array(64); - transaction.signature = await alice.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = alice.signTransaction(transaction); const serializer = new ProtoSerializer(); const buffer = serializer.serializeTransaction(transaction); @@ -403,8 +388,8 @@ describe("test transaction", async () => { const transaction = new Transaction({ nonce: 92n, value: BigInt("123456789000000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: BigInt(minGasLimit), chainID: "local-testnet", @@ -417,8 +402,8 @@ describe("test transaction", async () => { it("computes fee", async () => { const transaction = new Transaction({ chainID: "D", - sender: wallets.alice.address, - receiver: wallets.alice.address, + sender: alice.address, + receiver: alice.address, gasLimit: 50000n, gasPrice: BigInt(minGasPrice), }); @@ -430,8 +415,8 @@ describe("test transaction", async () => { it("computes fee, but should throw `NotEnoughGas` error", async () => { const transaction = new Transaction({ chainID: networkConfig.chainID, - sender: wallets.alice.address, - receiver: wallets.alice.address, + sender: alice.address, + receiver: alice.address, gasLimit: 50000n, data: Buffer.from("toolittlegaslimit"), }); @@ -445,8 +430,8 @@ describe("test transaction", async () => { let transaction = new Transaction({ nonce: 92n, value: BigInt("123456789000000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, data: Buffer.from("testdata"), gasPrice: BigInt(minGasPrice), gasLimit: BigInt(minGasLimit + 12010), @@ -460,8 +445,8 @@ describe("test transaction", async () => { it("computes fee (with data field)", async () => { const transaction = new Transaction({ chainID: networkConfig.chainID, - sender: wallets.alice.address, - receiver: wallets.alice.address, + sender: alice.address, + receiver: alice.address, gasLimit: 50000n + 12010n, gasPrice: BigInt(minGasPrice), data: Buffer.from("testdata"), @@ -472,12 +457,12 @@ describe("test transaction", async () => { }); it("should convert transaction to plain object and back", () => { - const sender = wallets.alice.address; + const sender = alice.address; const transaction = new Transaction({ nonce: 90n, value: 123456789000000000000000000000n, sender: sender, - receiver: wallets.bob.address, + receiver: bob.address, senderUsername: "alice", receiverUsername: "bob", gasPrice: BigInt(minGasPrice), @@ -494,8 +479,8 @@ describe("test transaction", async () => { it("should handle large values", () => { const tx1 = new Transaction({ value: 123456789000000000000000000000n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, chainID: "local-testnet", }); @@ -503,8 +488,8 @@ describe("test transaction", async () => { const tx2 = new Transaction({ value: 123456789000000000000000000000n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, chainID: "local-testnet", }); @@ -512,8 +497,8 @@ describe("test transaction", async () => { const tx3 = new Transaction({ value: BigInt("123456789000000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, chainID: "local-testnet", }); @@ -524,8 +509,8 @@ describe("test transaction", async () => { let transaction = new Transaction({ nonce: 90n, value: BigInt("1000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: 80000n, data: Buffer.from("hello"), @@ -538,8 +523,8 @@ describe("test transaction", async () => { transaction = new Transaction({ nonce: 90n, value: BigInt("1000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: 80000n, data: Buffer.from("hello"), @@ -552,8 +537,8 @@ describe("test transaction", async () => { transaction = new Transaction({ nonce: 90n, value: BigInt("1000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: 80000n, data: Buffer.from("hello"), @@ -566,8 +551,8 @@ describe("test transaction", async () => { transaction = new Transaction({ nonce: 90n, value: BigInt("1000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), gasLimit: 80000n, data: Buffer.from("hello"), @@ -580,10 +565,10 @@ describe("test transaction", async () => { transaction = new Transaction({ nonce: 90n, value: BigInt("1000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), - guardian: wallets.bob.address, + guardian: bob.address, gasLimit: 80000n, data: Buffer.from("hello"), chainID: "local-testnet", @@ -595,19 +580,17 @@ describe("test transaction", async () => { transaction = new Transaction({ nonce: 90n, value: BigInt("1000000000000000000"), - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasPrice: BigInt(minGasPrice), - guardian: wallets.bob.address, + guardian: bob.address, gasLimit: 80000n, data: Buffer.from("hello"), chainID: "local-testnet", version: 2, options: 2, }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); transaction.guardianSignature = transaction.signature; assert.isTrue(transaction.isGuardedTransaction()); }); @@ -616,8 +599,8 @@ describe("test transaction", async () => { let transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, gasPrice: 1000000000n, chainID: "integration tests chain ID", @@ -625,11 +608,11 @@ describe("test transaction", async () => { options: 1, }); - transaction.signature = await wallets.alice.signer.sign(transactionComputer.computeHashForSigning(transaction)); + transaction.signature = alice.signTransaction(transaction); assert.equal( - "f0c81f2393b1ec5972c813f817bae8daa00ade91c6f75ea604ab6a4d2797aca4378d783023ff98f1a02717fe4f24240cdfba0b674ee9abb18042203d713bc70a", Buffer.from(transaction.signature).toString("hex"), + "f0c81f2393b1ec5972c813f817bae8daa00ade91c6f75ea604ab6a4d2797aca4378d783023ff98f1a02717fe4f24240cdfba0b674ee9abb18042203d713bc70a", ); }); @@ -637,25 +620,25 @@ describe("test transaction", async () => { let transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, chainID: "localnet", }); - transactionComputer.applyGuardian(transaction, wallets.carol.address); + transactionComputer.applyGuardian(transaction, carol.address); assert.equal(transaction.version, 2); assert.equal(transaction.options, 2); - assert.equal(transaction.guardian, wallets.carol.address); + assert.equal(transaction.guardian, carol.address); }); it("should apply guardian with options set for hash signing", async () => { let transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, chainID: "localnet", version: 1, @@ -665,7 +648,7 @@ describe("test transaction", async () => { assert.equal(transaction.version, 2); assert.equal(transaction.options, 1); - transactionComputer.applyGuardian(transaction, wallets.carol.address); + transactionComputer.applyGuardian(transaction, carol.address); assert.equal(transaction.version, 2); assert.equal(transaction.options, 3); }); @@ -673,12 +656,12 @@ describe("test transaction", async () => { it("should ensure transaction is valid", async () => { let transaction = new Transaction({ sender: Address.empty(), - receiver: wallets.bob.address, + receiver: bob.address, gasLimit: 50000n, chainID: "", }); - transaction.sender = wallets.alice.address; + transaction.sender = alice.address; assert.throws(() => { transactionComputer.computeBytesForSigning(transaction); @@ -700,24 +683,22 @@ describe("test transaction", async () => { it("should compute bytes to verify transaction signature", async () => { let transaction = new Transaction({ - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, chainID: "D", nonce: 7n, }); - transaction.signature = await wallets.alice.signer.sign( - transactionComputer.computeBytesForSigning(transaction), - ); + transaction.signature = alice.signTransaction(transaction); - const userVerifier = new UserVerifier(new UserPublicKey(wallets.alice.address.getPublicKey())); + const userVerifier = new UserVerifier(new UserPublicKey(alice.address.getPublicKey())); const isSignedByAlice = userVerifier.verify( transactionComputer.computeBytesForVerifying(transaction), transaction.signature, ); - const wrongVerifier = new UserVerifier(new UserPublicKey(wallets.bob.address.getPublicKey())); + const wrongVerifier = new UserVerifier(new UserPublicKey(bob.address.getPublicKey())); const isSignedByBob = wrongVerifier.verify( transactionComputer.computeBytesForVerifying(transaction), transaction.signature, @@ -729,8 +710,8 @@ describe("test transaction", async () => { it("should compute bytes to verify transaction signature (signed by hash)", async () => { let transaction = new Transaction({ - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, chainID: "D", nonce: 7n, @@ -738,15 +719,15 @@ describe("test transaction", async () => { transactionComputer.applyOptionsForHashSigning(transaction); - transaction.signature = await wallets.alice.signer.sign(transactionComputer.computeHashForSigning(transaction)); + transaction.signature = alice.signTransaction(transaction); - const userVerifier = new UserVerifier(new UserPublicKey(wallets.alice.address.getPublicKey())); + const userVerifier = new UserVerifier(new UserPublicKey(alice.address.getPublicKey())); const isSignedByAlice = userVerifier.verify( transactionComputer.computeBytesForVerifying(transaction), transaction.signature, ); - const wrongVerifier = new UserVerifier(new UserPublicKey(wallets.bob.address.getPublicKey())); + const wrongVerifier = new UserVerifier(new UserPublicKey(bob.address.getPublicKey())); const isSignedByBob = wrongVerifier.verify( transactionComputer.computeBytesForVerifying(transaction), transaction.signature, @@ -800,9 +781,9 @@ describe("test transaction", async () => { it("should serialize transaction with relayer", async () => { const transaction = new Transaction({ chainID: networkConfig.chainID, - sender: wallets.alice.address, - receiver: wallets.alice.address, - relayer: wallets.bob.address, + sender: alice.address, + receiver: alice.address, + relayer: bob.address, gasLimit: 50000n, value: 0n, version: 2, @@ -821,8 +802,8 @@ describe("test transaction", async () => { it("should test relayed v3", async () => { const transaction = new Transaction({ chainID: networkConfig.chainID, - sender: wallets.alice.address, - receiver: wallets.alice.address, + sender: alice.address, + receiver: alice.address, senderUsername: "alice", receiverUsername: "bob", gasLimit: 80000n, @@ -833,7 +814,7 @@ describe("test transaction", async () => { }); assert.isFalse(transactionComputer.isRelayedV3Transaction(transaction)); - transaction.relayer = wallets.carol.address; + transaction.relayer = carol.address; assert.isTrue(transactionComputer.isRelayedV3Transaction(transaction)); }); }); diff --git a/src/networkProviders/accountAwaiter.dev.net.spec.ts b/src/networkProviders/accountAwaiter.dev.net.spec.ts index 9a9e40e64..0569de466 100644 --- a/src/networkProviders/accountAwaiter.dev.net.spec.ts +++ b/src/networkProviders/accountAwaiter.dev.net.spec.ts @@ -1,8 +1,8 @@ import { assert } from "chai"; -import { Address, Transaction, TransactionComputer } from "../core"; +import { Account } from "../accounts"; +import { Address, Transaction } from "../core"; import { MarkCompleted, MockNetworkProvider, Wait } from "../testutils/mockNetworkProvider"; -import { createAccountBalance } from "../testutils/utils"; -import { loadTestWallet } from "../testutils/wallets"; +import { createAccountBalance, getTestWalletsPath } from "../testutils/utils"; import { AccountAwaiter } from "./accountAwaiter"; import { AccountOnNetwork } from "./accounts"; import { ApiNetworkProvider } from "./apiNetworkProvider"; @@ -41,13 +41,12 @@ describe("AccountAwaiter Tests", () => { it("should await for account balance increase on the network", async function () { this.timeout(20000); - const alice = await loadTestWallet("alice"); - const aliceAddress = alice.getAddress(); + const alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); + const aliceAddress = alice.address; const frank = Address.newFromBech32("erd1kdl46yctawygtwg2k462307dmz2v55c605737dp3zkxh04sct7asqylhyv"); const api = new ApiNetworkProvider("https://devnet-api.multiversx.com"); const watcher = new AccountAwaiter({ fetcher: api }); - const txComputer = new TransactionComputer(); const value = 100_000n; // Create and sign the transaction @@ -59,7 +58,7 @@ describe("AccountAwaiter Tests", () => { value, }); transaction.nonce = (await api.getAccount(aliceAddress)).nonce; - transaction.signature = await alice.signer.sign(txComputer.computeBytesForSigning(transaction)); + transaction.signature = alice.signTransaction(transaction); const initialBalance = (await api.getAccount(frank)).balance; diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index 74a61d752..60efbd683 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -1,19 +1,11 @@ import { assert, expect } from "chai"; -import { - Address, - SmartContractQuery, - Token, - Transaction, - TransactionComputer, - TransactionOnNetwork, - TransactionStatus, -} from "../core"; -import { loadTestWallet } from "../testutils/wallets"; +import { Account } from "../accounts"; +import { Address, SmartContractQuery, Token, Transaction, TransactionOnNetwork, TransactionStatus } from "../core"; +import { getTestWalletsPath } from "../testutils/utils"; import { ApiNetworkProvider } from "./apiNetworkProvider"; describe("ApiNetworkProvider Tests", function () { const apiProvider = new ApiNetworkProvider("https://devnet-api.multiversx.com"); - const transactionComputer = new TransactionComputer(); it("should fetch network configuration", async () => { const result = await apiProvider.getNetworkConfig(); @@ -284,7 +276,7 @@ describe("ApiNetworkProvider Tests", function () { }); it("should simulate transaction", async () => { - const bob = await loadTestWallet("bob"); + const bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); let transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -297,7 +289,7 @@ describe("ApiNetworkProvider Tests", function () { let txOnNetwork = await apiProvider.simulateTransaction(transaction); assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); txOnNetwork = await apiProvider.simulateTransaction(transaction, true); transaction = new Transaction({ @@ -321,7 +313,7 @@ describe("ApiNetworkProvider Tests", function () { assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); assert.deepEqual(txOnNetwork.smartContractResults[0].data, "@6f6b"); - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); txOnNetwork = await apiProvider.simulateTransaction(transaction, true); assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); @@ -335,7 +327,7 @@ describe("ApiNetworkProvider Tests", function () { }); it("should estimate transaction cost", async function () { - const bob = await loadTestWallet("bob"); + const bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); const transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -344,14 +336,14 @@ describe("ApiNetworkProvider Tests", function () { data: new Uint8Array(Buffer.from("test transaction")), }); transaction.nonce = (await apiProvider.getAccount(bob.address)).nonce; - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); const response = await apiProvider.estimateTransactionCost(transaction); assert.equal(response.gasLimit, 74000); }); it("should send and await for completed transaction", async function () { this.timeout(30000); - const bob = await loadTestWallet("bob"); + const bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); let transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -360,7 +352,7 @@ describe("ApiNetworkProvider Tests", function () { }); const nonce = (await apiProvider.getAccount(bob.address)).nonce; transaction.nonce = nonce; - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); let hash = await apiProvider.sendTransaction(transaction); let transactionOnNetwork = await apiProvider.awaitTransactionCompleted(hash); assert.isTrue(transactionOnNetwork.status.isCompleted()); @@ -373,7 +365,7 @@ describe("ApiNetworkProvider Tests", function () { data: new Uint8Array(Buffer.from("dummy@05")), }); transaction.nonce = nonce + 1n; - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); const condition = (txOnNetwork: TransactionOnNetwork) => !txOnNetwork.status.isSuccessful(); hash = await apiProvider.sendTransaction(transaction); diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index d5eb66090..de66a18ac 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -1,19 +1,11 @@ import { assert, expect } from "chai"; -import { - Address, - SmartContractQuery, - Token, - Transaction, - TransactionComputer, - TransactionOnNetwork, - TransactionStatus, -} from "../core"; -import { loadTestWallet } from "../testutils/wallets"; +import { Account } from "../accounts"; +import { Address, SmartContractQuery, Token, Transaction, TransactionOnNetwork, TransactionStatus } from "../core"; +import { getTestWalletsPath } from "../testutils/utils"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; describe("ProxyNetworkProvider Tests", function () { const proxy = new ProxyNetworkProvider("https://devnet-gateway.multiversx.com"); - const transactionComputer = new TransactionComputer(); it("should fetch network configuration", async () => { const result = await proxy.getNetworkConfig(); @@ -284,8 +276,7 @@ describe("ProxyNetworkProvider Tests", function () { }); it("should simulate transaction", async () => { - const bob = await loadTestWallet("bob"); - + const bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); let transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -298,7 +289,7 @@ describe("ProxyNetworkProvider Tests", function () { let txOnNetwork = await proxy.simulateTransaction(transaction); assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); txOnNetwork = await proxy.simulateTransaction(transaction); transaction = new Transaction({ @@ -322,7 +313,7 @@ describe("ProxyNetworkProvider Tests", function () { assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); assert.equal(txOnNetwork.smartContractResults[0].data, "@6f6b"); - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); txOnNetwork = await proxy.simulateTransaction(transaction); assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); @@ -336,7 +327,7 @@ describe("ProxyNetworkProvider Tests", function () { }); it("should estimate transaction cost", async function () { - const bob = await loadTestWallet("bob"); + const bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); const transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -345,14 +336,14 @@ describe("ProxyNetworkProvider Tests", function () { data: new Uint8Array(Buffer.from("test transaction")), }); transaction.nonce = (await proxy.getAccount(bob.address)).nonce; - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); const response = await proxy.estimateTransactionCost(transaction); assert.equal(response.gasLimit, 74000); }); it("should send and await for completed transaction", async function () { this.timeout(50000); - const bob = await loadTestWallet("bob"); + const bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); let transaction = new Transaction({ sender: bob.address, receiver: bob.address, @@ -361,7 +352,7 @@ describe("ProxyNetworkProvider Tests", function () { }); const nonce = (await proxy.getAccount(bob.address)).nonce; transaction.nonce = nonce; - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); let hash = await proxy.sendTransaction(transaction); let transactionOnNetwork = await proxy.awaitTransactionCompleted(hash); assert.isTrue(transactionOnNetwork.status.isCompleted()); @@ -374,7 +365,7 @@ describe("ProxyNetworkProvider Tests", function () { data: new Uint8Array(Buffer.from("dummy@05")), }); transaction.nonce = nonce + 1n; - transaction.signature = await bob.signer.sign(transactionComputer.computeBytesForSigning(transaction)); + transaction.signature = bob.signTransaction(transaction); const condition = (txOnNetwork: TransactionOnNetwork) => !txOnNetwork.status.isSuccessful(); hash = await proxy.sendTransaction(transaction); diff --git a/src/proto/serializer.spec.ts b/src/proto/serializer.spec.ts index 6a8ccce84..729c22ec2 100644 --- a/src/proto/serializer.spec.ts +++ b/src/proto/serializer.spec.ts @@ -1,28 +1,31 @@ import { assert } from "chai"; +import { Account } from "../accounts"; import { Address, TokenTransfer, Transaction } from "../core"; -import { loadTestWallets, TestWallet } from "../testutils"; +import { getTestWalletsPath } from "../testutils"; import { ProtoSerializer } from "./serializer"; describe("serialize transactions", () => { - let wallets: Record; let serializer = new ProtoSerializer(); - + let alice: Account; + let bob: Account; + let carol: Account; before(async function () { - wallets = await loadTestWallets(); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); + bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); + carol = await Account.newFromPem(`${getTestWalletsPath()}/carol.pem`); }); it("with no data, no value", async () => { let transaction = new Transaction({ nonce: 89n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 50000n, chainID: "local-testnet", }); - const signer = wallets.alice.signer; - transaction.applySignature(await signer.sign(transaction.serializeForSigning())); + transaction.signature = alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -35,15 +38,14 @@ describe("serialize transactions", () => { let transaction = new Transaction({ nonce: 90n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 80000n, data: Buffer.from("hello"), chainID: "local-testnet", }); - const signer = wallets.alice.signer; - transaction.applySignature(await signer.sign(transaction.serializeForSigning())); + transaction.signature = alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -56,15 +58,14 @@ describe("serialize transactions", () => { let transaction = new Transaction({ nonce: 91n, value: TokenTransfer.newFromNativeAmount(10000000000000000000n).amount, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 100000n, data: Buffer.from("for the book"), chainID: "local-testnet", }); - const signer = wallets.alice.signer; - transaction.applySignature(await signer.sign(transaction.serializeForSigning())); + transaction.signature = alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -77,15 +78,14 @@ describe("serialize transactions", () => { let transaction = new Transaction({ nonce: 92n, value: 123456789000000000000000000000n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 100000n, data: Buffer.from("for the spaceship"), chainID: "local-testnet", }); - const signer = wallets.alice.signer; - transaction.applySignature(await signer.sign(transaction.serializeForSigning())); + transaction.signature = alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -98,20 +98,15 @@ describe("serialize transactions", () => { let transaction = new Transaction({ nonce: 0n, value: 0n, - sender: wallets.alice.address, - receiver: wallets.bob.address, + sender: alice.address, + receiver: bob.address, gasLimit: 80000n, data: Buffer.from("hello"), chainID: "local-testnet", version: 1, }); - transaction.applySignature( - Buffer.from( - "dfa3e9f2fdec60dcb353bac3b3435b4a2ff251e7e98eaf8620f46c731fc70c8ba5615fd4e208b05e75fe0f7dc44b7a99567e29f94fcd91efac7e67b182cd2a04", - "hex", - ), - ); + transaction.signature = alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -132,8 +127,7 @@ describe("serialize transactions", () => { chainID: "T", }); - const signer = wallets.carol.signer; - transaction.applySignature(await signer.sign(transaction.serializeForSigning())); + transaction.signature = carol.signTransaction(transaction); const buffer = serializer.serializeTransaction(transaction); assert.equal( diff --git a/src/relayed/relayedTransactionsFactory.spec.ts b/src/relayed/relayedTransactionsFactory.spec.ts index 3535b8a77..9f23543b7 100644 --- a/src/relayed/relayedTransactionsFactory.spec.ts +++ b/src/relayed/relayedTransactionsFactory.spec.ts @@ -1,16 +1,20 @@ import { assert } from "chai"; -import { Address, Transaction, TransactionComputer, TransactionsFactoryConfig } from "../core"; -import { TestWallet, loadTestWallets } from "../testutils"; +import { Account } from "../accounts"; +import { Address, Transaction, TransactionsFactoryConfig } from "../core"; +import { getTestWalletsPath } from "../testutils"; import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; describe("test relayed transactions factory", function () { const config = new TransactionsFactoryConfig({ chainID: "T" }); const factory = new RelayedTransactionsFactory({ config: config }); - const transactionComputer = new TransactionComputer(); - let alice: TestWallet, bob: TestWallet, carol: TestWallet, grace: TestWallet, frank: TestWallet; + let alice: Account, bob: Account, carol: Account, grace: Account, frank: Account; before(async function () { - ({ alice, bob, carol, grace, frank } = await loadTestWallets()); + alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); + bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); + carol = await Account.newFromPem(`${getTestWalletsPath()}/carol.pem`); + grace = await Account.newFromPem(`${getTestWalletsPath()}/grace.pem`); + frank = await Account.newFromPem(`${getTestWalletsPath()}/frank.pem`); }); it("should throw exception when creating relayed v1 transaction with invalid inner transaction", async function () { @@ -46,16 +50,14 @@ describe("test relayed transactions factory", function () { nonce: 198n, }); - const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); - innerTransaction.signature = await bob.signer.sign(serializedInnerTransaction); + innerTransaction.signature = bob.signTransaction(innerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction(alice.getAddress(), { + const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 2627n; - const serializedRelayedTransaction = transactionComputer.computeBytesForSigning(relayedTransaction); - relayedTransaction.signature = await alice.signer.sign(serializedRelayedTransaction); + relayedTransaction.signature = alice.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -79,16 +81,14 @@ describe("test relayed transactions factory", function () { value: 1000000000000000000n, }); - const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); - innerTransaction.signature = await carol.signer.sign(serializedInnerTransaction); + innerTransaction.signature = carol.signTransaction(innerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction(frank.getAddress(), { + const relayedTransaction = factory.createRelayedV1Transaction(frank.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 715n; - const serializedRelayedTransaction = transactionComputer.computeBytesForSigning(relayedTransaction); - relayedTransaction.signature = await frank.signer.sign(serializedRelayedTransaction); + relayedTransaction.signature = frank.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -112,16 +112,14 @@ describe("test relayed transactions factory", function () { value: 1999999000000000000000000n, }); - const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); - innerTransaction.signature = await carol.signer.sign(serializedInnerTransaction); + innerTransaction.signature = carol.signTransaction(innerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction(frank.getAddress(), { + const relayedTransaction = factory.createRelayedV1Transaction(frank.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 715n; - const serializedRelayedTransaction = transactionComputer.computeBytesForSigning(relayedTransaction); - relayedTransaction.signature = await frank.signer.sign(serializedRelayedTransaction); + relayedTransaction.signature = frank.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -146,17 +144,15 @@ describe("test relayed transactions factory", function () { guardian: grace.address, }); - const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); - innerTransaction.signature = await bob.signer.sign(serializedInnerTransaction); - innerTransaction.guardianSignature = await grace.signer.sign(serializedInnerTransaction); + innerTransaction.signature = bob.signTransaction(innerTransaction); + innerTransaction.guardianSignature = grace.signTransaction(innerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction(alice.getAddress(), { + const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 2627n; - const serializedRelayedTransaction = transactionComputer.computeBytesForSigning(relayedTransaction); - relayedTransaction.signature = await alice.signer.sign(serializedRelayedTransaction); + relayedTransaction.signature = alice.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -181,20 +177,18 @@ describe("test relayed transactions factory", function () { guardian: grace.address, }); - const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); - innerTransaction.signature = await bob.signer.sign(serializedInnerTransaction); - innerTransaction.guardianSignature = await grace.signer.sign(serializedInnerTransaction); + innerTransaction.signature = bob.signTransaction(innerTransaction); + innerTransaction.guardianSignature = grace.signTransaction(innerTransaction); - const relayedTransaction = factory.createRelayedV1Transaction(alice.getAddress(), { + const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 2627n; relayedTransaction.options = 2; relayedTransaction.guardian = frank.address; - const serializedRelayedTransaction = transactionComputer.computeBytesForSigning(relayedTransaction); - relayedTransaction.signature = await alice.signer.sign(serializedRelayedTransaction); - relayedTransaction.guardianSignature = await frank.signer.sign(serializedRelayedTransaction); + relayedTransaction.signature = alice.signTransaction(relayedTransaction); + relayedTransaction.guardianSignature = frank.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -215,7 +209,7 @@ describe("test relayed transactions factory", function () { }); assert.throws(() => { - factory.createRelayedV2Transaction(carol.getAddress(), { + factory.createRelayedV2Transaction(carol.address, { innerTransaction: innerTransaction, innerTransactionGasLimit: 50000n, }), @@ -225,7 +219,7 @@ describe("test relayed transactions factory", function () { innerTransaction.gasLimit = 0n; assert.throws(() => { - factory.createRelayedV2Transaction(carol.getAddress(), { + factory.createRelayedV2Transaction(carol.address, { innerTransaction: innerTransaction, innerTransactionGasLimit: 50000n, }), @@ -245,17 +239,15 @@ describe("test relayed transactions factory", function () { options: 0, }); - const serializedInnerTransaction = transactionComputer.computeBytesForSigning(innerTransaction); - innerTransaction.signature = await bob.signer.sign(serializedInnerTransaction); + innerTransaction.signature = bob.signTransaction(innerTransaction); - const relayedTransaction = factory.createRelayedV2Transaction(alice.getAddress(), { + const relayedTransaction = factory.createRelayedV2Transaction(alice.address, { innerTransaction: innerTransaction, innerTransactionGasLimit: 60000000n, }); relayedTransaction.nonce = 37n; - const serializedRelayedTransaction = transactionComputer.computeBytesForSigning(relayedTransaction); - relayedTransaction.signature = await alice.signer.sign(serializedRelayedTransaction); + relayedTransaction.signature = alice.signTransaction(relayedTransaction); assert.equal(relayedTransaction.version, 2); assert.equal(relayedTransaction.options, 0); diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index 9a6f16ad7..a97e895a6 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -1,14 +1,14 @@ import * as fs from "fs"; import { PathLike } from "fs"; +import { resolve } from "path"; import { AbiRegistry, Code, SmartContract, TypedValue } from "../abi"; +import { Account } from "../accounts"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionWatcher } from "../core/transactionWatcher"; import { getAxios } from "../core/utils"; -import { TestWallet } from "./wallets"; export async function prepareDeployment(obj: { - deployer: TestWallet; + deployer: Account; contract: SmartContract; codePath: string; initArguments: TypedValue[]; @@ -26,13 +26,12 @@ export async function prepareDeployment(obj: { deployer: deployer.address, }); - const computer = new TransactionComputer(); - let nonce = deployer.account.getNonceThenIncrement(); + let nonce = deployer.getNonceThenIncrement(); let contractAddress = SmartContract.computeAddress(deployer.address, nonce); transaction.nonce = nonce; transaction.sender = deployer.address; contract.setAddress(contractAddress); - transaction.signature = await deployer.signer.sign(computer.computeBytesForSigning(transaction)); + transaction.signature = deployer.signTransaction(transaction); return transaction; } @@ -99,8 +98,8 @@ export function b64ToHex(value: string): string { return Buffer.from(value, "base64").toString("hex"); } -export function importJsonBig(value: string): string { - return Buffer.from(value, "base64").toString("hex"); +export function getTestWalletsPath(): string { + return resolve(__dirname, "..", "testdata", "testwallets"); } export const stringifyBigIntJSON = (jsonString: any): any => { From ff2520ee2c4a9862cdea9773940e0f4c127ef942 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 30 Jan 2025 16:04:18 +0200 Subject: [PATCH 165/214] Fix tests --- src/abi/smartContract.spec.ts | 9 ++------- src/accounts/account.spec.ts | 2 +- src/core/transaction.spec.ts | 15 +++++++-------- src/wallet/userKeys.ts | 2 +- 4 files changed, 11 insertions(+), 17 deletions(-) diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index c74182628..60525a061 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -94,9 +94,7 @@ describe("test contract", () => { address: new Address("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"), }); - provider.mockUpdateAccount(alice.address, (account) => { - account.nonce = 42n; - }); + alice.nonce = 42n; let callTransactionOne = contract.call({ func: new ContractFunction("helloEarth"), @@ -169,10 +167,7 @@ describe("test contract", () => { caller: alice.address, }); - provider.mockUpdateAccount(alice.address, (account) => { - account.nonce = 42n; - }); - + alice.nonce = 42n; deployTransaction.nonce = alice.nonce; assert.equal(deployTransaction.data.toString(), "upgradeContract@01020304@0100"); diff --git a/src/accounts/account.spec.ts b/src/accounts/account.spec.ts index 853663098..901372cb2 100644 --- a/src/accounts/account.spec.ts +++ b/src/accounts/account.spec.ts @@ -19,7 +19,7 @@ describe("test account methods", function () { }); it("should create account from keystore", async function () { - const account = Account.newFromKeystore(`${testWallets}/withDummyMnemonic.json`, "password"); + const account = Account.newFromKeystore(`${getTestWalletsPath()}/withDummyMnemonic.json`, "password"); assert.equal( account.secretKey.valueOf().toString("hex"), diff --git a/src/core/transaction.spec.ts b/src/core/transaction.spec.ts index 40f48a4d8..c67366a4f 100644 --- a/src/core/transaction.spec.ts +++ b/src/core/transaction.spec.ts @@ -123,8 +123,8 @@ describe("test transaction", async () => { it("should sign transaction (with usernames)", async () => { const transaction = new Transaction({ chainID: "T", - sender: alice.address, - receiver: bob.address, + sender: carol.address, + receiver: alice.address, gasLimit: 50000n, value: 1000000000000000000n, version: 2, @@ -133,7 +133,7 @@ describe("test transaction", async () => { receiverUsername: "alice", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = carol.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -343,7 +343,7 @@ describe("test transaction", async () => { chainID: "T", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = carol.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -608,7 +608,7 @@ describe("test transaction", async () => { options: 1, }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.sign(transactionComputer.computeHashForSigning(transaction)); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -719,9 +719,9 @@ describe("test transaction", async () => { transactionComputer.applyOptionsForHashSigning(transaction); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.sign(transactionComputer.computeHashForSigning(transaction)); - const userVerifier = new UserVerifier(new UserPublicKey(alice.address.getPublicKey())); + const userVerifier = new UserVerifier(alice.publicKey); const isSignedByAlice = userVerifier.verify( transactionComputer.computeBytesForVerifying(transaction), transaction.signature, @@ -732,7 +732,6 @@ describe("test transaction", async () => { transactionComputer.computeBytesForVerifying(transaction), transaction.signature, ); - assert.equal(isSignedByAlice, true); assert.equal(isSignedByBob, false); }); diff --git a/src/wallet/userKeys.ts b/src/wallet/userKeys.ts index 203e6dfab..801e58bfc 100644 --- a/src/wallet/userKeys.ts +++ b/src/wallet/userKeys.ts @@ -45,7 +45,7 @@ export class UserSecretKey { return new UserSecretKey(secretKey); } - sign(message: Buffer | Uint8Array): Uint8Array { + sign(message: Uint8Array): Uint8Array { const signature = ed.sync.sign(new Uint8Array(message), new Uint8Array(this.buffer)); return signature; } From 206d6caf5ba5c9f73aee87e5735f38dd3ad34541 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 30 Jan 2025 16:34:51 +0200 Subject: [PATCH 166/214] Fix integration tests --- src/abi/interaction.local.net.spec.ts | 42 +++++--------- src/abi/smartContract.local.net.spec.ts | 56 ++++++++----------- .../smartContractResults.local.net.spec.ts | 13 ++--- 3 files changed, 42 insertions(+), 69 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 7169a5170..95c4122d0 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -38,17 +38,17 @@ describe("test smart contract interactor", function () { }); const bytecode = await promises.readFile("src/testdata/answer.wasm"); + alice.nonce = (await provider.getAccount(alice.address)).nonce; const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = BigInt(alice.nonce.valueOf()); + deployTransaction.nonce = alice.getNonceThenIncrement(); deployTransaction.signature = alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - alice.incrementNonce(); const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { @@ -85,11 +85,9 @@ describe("test smart contract interactor", function () { function: "getUltimateAnswer", gasLimit: 3000000n, }); - transaction.nonce = BigInt(alice.nonce.valueOf()); + transaction.nonce = alice.getNonceThenIncrement(); transaction.signature = alice.signTransaction(transaction); - alice.incrementNonce(); - await provider.sendTransaction(transaction); // Execute, and wait for execution @@ -98,11 +96,9 @@ describe("test smart contract interactor", function () { function: "getUltimateAnswer", gasLimit: 3000000n, }); - transaction.nonce = BigInt(alice.nonce.valueOf()); + transaction.nonce = alice.getNonceThenIncrement(); transaction.signature = alice.signTransaction(transaction); - alice.incrementNonce(); - const executeTxHash = await provider.sendTransaction(transaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(executeTxHash); const executeResponse = queryController.parseExecute(transactionOnNetwork); @@ -124,7 +120,7 @@ describe("test smart contract interactor", function () { }); let network = await provider.getNetworkConfig(); - + alice.nonce = (await provider.getAccount(alice.address)).nonce; // Deploy the contract let deployTransaction = await prepareDeployment({ contract: contract, @@ -266,17 +262,17 @@ describe("test smart contract interactor", function () { const parser = new SmartContractTransactionsOutcomeParser({ abi: abiRegistry }); const bytecode = await promises.readFile("src/testdata/counter.wasm"); + alice.nonce = (await provider.getAccount(alice.address)).nonce; const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = BigInt(alice.nonce.valueOf()); + deployTransaction.nonce = alice.getNonceThenIncrement(); deployTransaction.signature = alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - alice.incrementNonce(); const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { @@ -300,12 +296,10 @@ describe("test smart contract interactor", function () { function: "increment", gasLimit: 3000000n, }); - incrementTransaction.nonce = BigInt(alice.nonce.valueOf()); + incrementTransaction.nonce = alice.getNonceThenIncrement(); incrementTransaction.signature = alice.signTransaction(incrementTransaction); - alice.incrementNonce(); - // Query "get()" const query = queryController.createQuery({ contract: contractAddress, @@ -327,11 +321,9 @@ describe("test smart contract interactor", function () { function: "decrement", gasLimit: 3000000n, }); - decrementTransaction.nonce = alice.nonce; + decrementTransaction.nonce = alice.getNonceThenIncrement(); decrementTransaction.signature = alice.signTransaction(decrementTransaction); - alice.incrementNonce(); - await provider.sendTransaction(decrementTransaction); decrementTransaction.nonce = alice.nonce; @@ -347,6 +339,7 @@ describe("test smart contract interactor", function () { let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); let parser = new SmartContractTransactionsOutcomeParser({ abi: abiRegistry }); + alice.nonce = (await provider.getAccount(alice.address)).nonce; let network = await provider.getNetworkConfig(); @@ -363,12 +356,11 @@ describe("test smart contract interactor", function () { bytecode: bytecode, gasLimit: 100000000n, }); - deployTransaction.nonce = alice.nonce; + deployTransaction.nonce = alice.getNonceThenIncrement(); deployTransaction.signature = alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - alice.incrementNonce(); const transactionCompletionAwaiter = new TransactionWatcher({ getTransaction: async (hash: string) => { @@ -388,11 +380,9 @@ describe("test smart contract interactor", function () { arguments: ["lucky", "EGLD", 1, null, null, 1, null, null], gasLimit: 30000000n, }); - startTransaction.nonce = alice.nonce; + startTransaction.nonce = alice.getNonceThenIncrement(); startTransaction.signature = alice.signTransaction(startTransaction); - alice.incrementNonce(); - const startTxHash = await provider.sendTransaction(startTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(startTxHash); let response = parser.parseExecute({ transactionOnNetwork }); @@ -406,11 +396,9 @@ describe("test smart contract interactor", function () { arguments: ["lucky"], gasLimit: 5000000n, }); - lotteryStatusTransaction.nonce = alice.nonce; + lotteryStatusTransaction.nonce = alice.getNonceThenIncrement(); lotteryStatusTransaction.signature = alice.signTransaction(lotteryStatusTransaction); - alice.incrementNonce(); - const statusTxHash = await provider.sendTransaction(lotteryStatusTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(statusTxHash); response = parser.parseExecute({ transactionOnNetwork }); @@ -425,11 +413,9 @@ describe("test smart contract interactor", function () { arguments: ["lucky"], gasLimit: 5000000n, }); - lotteryInfoTransaction.nonce = alice.nonce; + lotteryInfoTransaction.nonce = alice.getNonceThenIncrement(); lotteryInfoTransaction.signature = alice.signTransaction(lotteryInfoTransaction); - alice.incrementNonce(); - const infoTxHash = await provider.sendTransaction(lotteryInfoTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(infoTxHash); response = parser.parseExecute({ transactionOnNetwork }); diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index cec28ed12..2deb81da5 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -54,49 +54,49 @@ describe("test on local testnet", function () { const factory = new SmartContractTransactionsFactory({ config: config }); const bytecode = await promises.readFile("src/testdata/counter.wasm"); + alice.nonce = (await provider.getAccount(alice.address)).nonce; const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 4000000n, }); - deployTransaction.nonce = BigInt(alice.nonce.valueOf()); + deployTransaction.nonce = alice.getNonceThenIncrement(); deployTransaction.signature = alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - alice.incrementNonce(); const smartContractCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 4000000n, }); - smartContractCallTransaction.nonce = alice.nonce; + smartContractCallTransaction.nonce = alice.getNonceThenIncrement(); smartContractCallTransaction.signature = alice.signTransaction(smartContractCallTransaction); - alice.incrementNonce(); - const simulateOne = factory.createTransactionForExecute(alice.address, { function: "increment", contract: contractAddress, gasLimit: 200000n, }); - - simulateOne.nonce = alice.nonce; + simulateOne.nonce = alice.getNonceThenIncrement(); simulateOne.signature = alice.signTransaction(simulateOne); - alice.incrementNonce(); - const simulateTwo = factory.createTransactionForExecute(alice.address, { function: "foobar", contract: contractAddress, gasLimit: 700000n, }); - - simulateTwo.nonce = alice.nonce; + simulateTwo.nonce = alice.getNonceThenIncrement(); simulateTwo.signature = alice.signTransaction(simulateTwo); - alice.incrementNonce(); + const simulateThree = factory.createTransactionForExecute(alice.address, { + function: "foobar", + contract: contractAddress, + gasLimit: 700000n, + }); + simulateThree.nonce = alice.getNonceThenIncrement(); + simulateThree.signature = alice.signTransaction(simulateThree); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); @@ -128,39 +128,35 @@ describe("test on local testnet", function () { const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); + alice.nonce = (await provider.getAccount(alice.address)).nonce; const bytecode = await promises.readFile("src/testdata/counter.wasm"); const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = alice.nonce; + deployTransaction.nonce = alice.getNonceThenIncrement(); deployTransaction.signature = alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - alice.incrementNonce(); const firstScCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, }); - firstScCallTransaction.nonce = alice.nonce; + firstScCallTransaction.nonce = alice.getNonceThenIncrement(); firstScCallTransaction.signature = alice.signTransaction(firstScCallTransaction); - alice.incrementNonce(); - const secondScCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, }); - secondScCallTransaction.nonce = alice.nonce; + secondScCallTransaction.nonce = alice.getNonceThenIncrement(); secondScCallTransaction.signature = alice.signTransaction(secondScCallTransaction); - alice.incrementNonce(); - // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); const firstScCallHash = await provider.sendTransaction(firstScCallTransaction); @@ -198,6 +194,7 @@ describe("test on local testnet", function () { const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); + alice.nonce = (await provider.getAccount(alice.address)).nonce; const bytecode = await promises.readFile("src/testdata/erc20.wasm"); const deployTransaction = factory.createTransactionForDeploy(alice.address, { @@ -205,11 +202,10 @@ describe("test on local testnet", function () { gasLimit: 50000000n, arguments: [new U32Value(10000)], }); - deployTransaction.nonce = alice.nonce; + deployTransaction.nonce = alice.getNonceThenIncrement(); deployTransaction.signature = alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - alice.incrementNonce(); const transactionMintBob = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -217,22 +213,18 @@ describe("test on local testnet", function () { gasLimit: 9000000n, arguments: [new AddressValue(bob.address), new U32Value(1000)], }); - transactionMintBob.nonce = alice.nonce; + transactionMintBob.nonce = alice.getNonceThenIncrement(); transactionMintBob.signature = alice.signTransaction(transactionMintBob); - alice.incrementNonce(); - const transactionMintCarol = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "transferToken", gasLimit: 9000000n, arguments: [new AddressValue(carol.address), new U32Value(1500)], }); - transactionMintCarol.nonce = alice.nonce; + transactionMintCarol.nonce = alice.getNonceThenIncrement(); transactionMintCarol.signature = alice.signTransaction(transactionMintCarol); - alice.incrementNonce(); - // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); const mintBobTxHash = await provider.sendTransaction(transactionMintBob); @@ -289,6 +281,7 @@ describe("test on local testnet", function () { TransactionWatcher.DefaultTimeout = 50000; let network = await provider.getNetworkConfig(); + alice.nonce = (await provider.getAccount(alice.address)).nonce; const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config }); @@ -299,12 +292,11 @@ describe("test on local testnet", function () { bytecode: bytecode, gasLimit: 50000000n, }); - deployTransaction.nonce = alice.nonce; + deployTransaction.nonce = alice.getNonceThenIncrement(); deployTransaction.signature = alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - alice.incrementNonce(); const startTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -322,11 +314,9 @@ describe("test on local testnet", function () { OptionalValue.newMissing(), ], }); - startTransaction.nonce = alice.nonce; + startTransaction.nonce = alice.getNonceThenIncrement(); startTransaction.signature = alice.signTransaction(startTransaction); - alice.incrementNonce(); - // Broadcast & execute const deployTx = await provider.sendTransaction(deployTransaction); const startTx = await provider.sendTransaction(startTransaction); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index e78bfd1f3..1361cafac 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -33,6 +33,7 @@ describe("fetch transactions from local testnet", function () { TransactionWatcher.DefaultTimeout = 50000; let network = await provider.getNetworkConfig(); + alice.nonce = (await provider.getAccount(alice.address)).nonce; // Deploy let contract = new SmartContract({}); @@ -54,11 +55,9 @@ describe("fetch transactions from local testnet", function () { caller: alice.address, }); - transactionIncrement.nonce = alice.nonce; + transactionIncrement.nonce = alice.getNonceThenIncrement(); transactionIncrement.signature = alice.signTransaction(transactionIncrement); - alice.incrementNonce(); - // Broadcast & execute const txHashDeploy = await provider.sendTransaction(transactionDeploy); const txHashIncrement = await provider.sendTransaction(transactionIncrement); @@ -88,27 +87,25 @@ describe("fetch transactions from local testnet", function () { const factory = new SmartContractTransactionsFactory({ config: config }); const bytecode = await promises.readFile("src/testdata/counter.wasm"); + alice.nonce = (await provider.getAccount(alice.address)).nonce; const deployTransaction = factory.createTransactionForDeploy(alice.address, { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = alice.nonce; + deployTransaction.nonce = alice.getNonceThenIncrement(); deployTransaction.signature = alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - alice.incrementNonce(); const smartContractCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, }); - smartContractCallTransaction.nonce = alice.nonce; + smartContractCallTransaction.nonce = alice.getNonceThenIncrement(); smartContractCallTransaction.signature = alice.signTransaction(smartContractCallTransaction); - alice.incrementNonce(); - // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); const callTxHash = await provider.sendTransaction(smartContractCallTransaction); From fe68e65e77f7b4c958749b08fd6b109f1763eba4 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Feb 2025 11:42:03 +0200 Subject: [PATCH 167/214] Fix integration tests --- src/abi/interaction.local.net.spec.ts | 33 ++++++++------- src/abi/interaction.spec.ts | 20 ++++----- src/abi/smartContract.local.net.spec.ts | 41 ++++++++++--------- src/abi/smartContract.spec.ts | 8 ++-- .../smartContractResults.local.net.spec.ts | 6 +-- src/accounts/account.spec.ts | 4 +- src/accounts/account.ts | 4 +- src/core/transaction.spec.ts | 24 +++++------ src/entrypoints/entrypoints.spec.ts | 4 +- .../accountAwaiter.dev.net.spec.ts | 2 +- .../apiNetworkProvider.dev.net.spec.ts | 10 ++--- .../proxyNetworkProvider.dev.net.spec.ts | 10 ++--- src/proto/serializer.spec.ts | 12 +++--- .../relayedTransactionsFactory.spec.ts | 30 +++++++------- src/testutils/utils.ts | 2 +- 15 files changed, 107 insertions(+), 103 deletions(-) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index 95c4122d0..bd805c004 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -44,9 +44,9 @@ describe("test smart contract interactor", function () { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = alice.getNonceThenIncrement(); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); @@ -57,6 +57,7 @@ describe("test smart contract interactor", function () { }); const deployTxHash = await provider.sendTransaction(deployTransaction); + alice.incrementNonce(); const queryController = new SmartContractController({ chainID: "localnet", @@ -86,7 +87,7 @@ describe("test smart contract interactor", function () { gasLimit: 3000000n, }); transaction.nonce = alice.getNonceThenIncrement(); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); await provider.sendTransaction(transaction); @@ -97,7 +98,7 @@ describe("test smart contract interactor", function () { gasLimit: 3000000n, }); transaction.nonce = alice.getNonceThenIncrement(); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); const executeTxHash = await provider.sendTransaction(transaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(executeTxHash); @@ -268,9 +269,9 @@ describe("test smart contract interactor", function () { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = alice.getNonceThenIncrement(); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); @@ -281,6 +282,7 @@ describe("test smart contract interactor", function () { }); const deployTxHash = await provider.sendTransaction(deployTransaction); + alice.incrementNonce(); let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); const deployResponse = parser.parseDeploy({ transactionOnNetwork }); assert.isTrue(deployResponse.returnCode == "ok"); @@ -298,7 +300,7 @@ describe("test smart contract interactor", function () { }); incrementTransaction.nonce = alice.getNonceThenIncrement(); - incrementTransaction.signature = alice.signTransaction(incrementTransaction); + incrementTransaction.signature = await alice.signTransaction(incrementTransaction); // Query "get()" const query = queryController.createQuery({ @@ -322,12 +324,12 @@ describe("test smart contract interactor", function () { gasLimit: 3000000n, }); decrementTransaction.nonce = alice.getNonceThenIncrement(); - decrementTransaction.signature = alice.signTransaction(decrementTransaction); + decrementTransaction.signature = await alice.signTransaction(decrementTransaction); await provider.sendTransaction(decrementTransaction); decrementTransaction.nonce = alice.nonce; - decrementTransaction.signature = alice.signTransaction(decrementTransaction); + decrementTransaction.signature = await alice.signTransaction(decrementTransaction); const decrementTxHash = await provider.sendTransaction(decrementTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(decrementTxHash); @@ -356,9 +358,9 @@ describe("test smart contract interactor", function () { bytecode: bytecode, gasLimit: 100000000n, }); - deployTransaction.nonce = alice.getNonceThenIncrement(); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); @@ -369,6 +371,7 @@ describe("test smart contract interactor", function () { }); const deployTxHash = await provider.sendTransaction(deployTransaction); + alice.incrementNonce(); let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); const deployResponse = parser.parseDeploy({ transactionOnNetwork }); assert.isTrue(deployResponse.returnCode == "ok"); @@ -381,7 +384,7 @@ describe("test smart contract interactor", function () { gasLimit: 30000000n, }); startTransaction.nonce = alice.getNonceThenIncrement(); - startTransaction.signature = alice.signTransaction(startTransaction); + startTransaction.signature = await alice.signTransaction(startTransaction); const startTxHash = await provider.sendTransaction(startTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(startTxHash); @@ -397,7 +400,7 @@ describe("test smart contract interactor", function () { gasLimit: 5000000n, }); lotteryStatusTransaction.nonce = alice.getNonceThenIncrement(); - lotteryStatusTransaction.signature = alice.signTransaction(lotteryStatusTransaction); + lotteryStatusTransaction.signature = await alice.signTransaction(lotteryStatusTransaction); const statusTxHash = await provider.sendTransaction(lotteryStatusTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(statusTxHash); @@ -414,7 +417,7 @@ describe("test smart contract interactor", function () { gasLimit: 5000000n, }); lotteryInfoTransaction.nonce = alice.getNonceThenIncrement(); - lotteryInfoTransaction.signature = alice.signTransaction(lotteryInfoTransaction); + lotteryInfoTransaction.signature = await alice.signTransaction(lotteryInfoTransaction); const infoTxHash = await provider.sendTransaction(lotteryInfoTransaction); transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(infoTxHash); @@ -440,6 +443,6 @@ describe("test smart contract interactor", function () { const transaction = options.transaction; const wallet = options.wallet; - transaction.signature = wallet.signTransaction(transaction); + transaction.signature = await wallet.signTransaction(transaction); } }); diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 9c2e2c59a..d00d31b18 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -243,7 +243,7 @@ describe("test smart contract interactor", function () { // Execute, do not wait for execution let transaction = interaction.withSender(alice.address).withNonce(0n).buildTransaction(); transaction.sender = alice.address; - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); let hash = await provider.sendTransaction(transaction); assert.equal(transaction.nonce, 0n); assert.equal(transaction.data.toString(), "getUltimateAnswer"); @@ -251,7 +251,7 @@ describe("test smart contract interactor", function () { transaction = interaction.withNonce(1n).buildTransaction(); transaction.sender = alice.address; - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); hash = await provider.sendTransaction(transaction); assert.equal(transaction.nonce, 1n); assert.equal(hash, "ad513ce7c5d371d30e48f073326899766736eac1ac231d847d45bc3facbcb496"); @@ -259,7 +259,7 @@ describe("test smart contract interactor", function () { // Execute, and wait for execution transaction = interaction.withNonce(2n).buildTransaction(); transaction.sender = alice.address; - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs", "getUltimateAnswer"); hash = await provider.sendTransaction(transaction); let responseExecute = await controller.awaitCompletedExecute(hash); @@ -308,7 +308,7 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - incrementTransaction.signature = alice.signTransaction(incrementTransaction); + incrementTransaction.signature = await alice.signTransaction(incrementTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@08", "increment"); let hash = await provider.sendTransaction(incrementTransaction); let responseExecute = await controller.awaitCompletedExecute(hash); @@ -322,16 +322,16 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - decrementTransaction.signature = alice.signTransaction(decrementTransaction); + decrementTransaction.signature = await alice.signTransaction(decrementTransaction); await provider.sendTransaction(decrementTransaction); // Decrement #2 decrementTransaction = decrementInteraction.withNonce(16n).buildTransaction(); - decrementTransaction.signature = alice.signTransaction(decrementTransaction); + decrementTransaction.signature = await alice.signTransaction(decrementTransaction); await provider.sendTransaction(decrementTransaction); // Decrement #3 decrementTransaction = decrementInteraction.withNonce(17n).buildTransaction(); - decrementTransaction.signature = alice.signTransaction(decrementTransaction); + decrementTransaction.signature = await alice.signTransaction(decrementTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@05", "decrement"); hash = await provider.sendTransaction(decrementTransaction); responseExecute = await controller.awaitCompletedExecute(hash); @@ -372,7 +372,7 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - startTransaction.signature = alice.signTransaction(startTransaction); + startTransaction.signature = await alice.signTransaction(startTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b", "start"); let hash = await provider.sendTransaction(startTransaction); @@ -389,7 +389,7 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - statusTransaction.signature = alice.signTransaction(statusTransaction); + statusTransaction.signature = await alice.signTransaction(statusTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@01", "status"); hash = await provider.sendTransaction(startTransaction); @@ -407,7 +407,7 @@ describe("test smart contract interactor", function () { .withChainID("mock") .buildTransaction(); - getLotteryInfoTransaction.signature = alice.signTransaction(getLotteryInfoTransaction); + getLotteryInfoTransaction.signature = await alice.signTransaction(getLotteryInfoTransaction); provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult( "@6f6b@0000000b6c75636b792d746f6b656e000000010100000000000000005fc2b9dbffffffff00000001640000000a140ec80fa7ee88000000", "getLotteryInfo", diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 2deb81da5..24482aa2b 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -60,9 +60,9 @@ describe("test on local testnet", function () { bytecode: bytecode, gasLimit: 4000000n, }); - deployTransaction.nonce = alice.getNonceThenIncrement(); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); @@ -71,8 +71,9 @@ describe("test on local testnet", function () { function: "increment", gasLimit: 4000000n, }); + alice.incrementNonce(); smartContractCallTransaction.nonce = alice.getNonceThenIncrement(); - smartContractCallTransaction.signature = alice.signTransaction(smartContractCallTransaction); + smartContractCallTransaction.signature = await alice.signTransaction(smartContractCallTransaction); const simulateOne = factory.createTransactionForExecute(alice.address, { function: "increment", @@ -80,7 +81,7 @@ describe("test on local testnet", function () { gasLimit: 200000n, }); simulateOne.nonce = alice.getNonceThenIncrement(); - simulateOne.signature = alice.signTransaction(simulateOne); + simulateOne.signature = await alice.signTransaction(simulateOne); const simulateTwo = factory.createTransactionForExecute(alice.address, { function: "foobar", @@ -88,7 +89,7 @@ describe("test on local testnet", function () { gasLimit: 700000n, }); simulateTwo.nonce = alice.getNonceThenIncrement(); - simulateTwo.signature = alice.signTransaction(simulateTwo); + simulateTwo.signature = await alice.signTransaction(simulateTwo); const simulateThree = factory.createTransactionForExecute(alice.address, { function: "foobar", @@ -96,7 +97,7 @@ describe("test on local testnet", function () { gasLimit: 700000n, }); simulateThree.nonce = alice.getNonceThenIncrement(); - simulateThree.signature = alice.signTransaction(simulateThree); + simulateThree.signature = await alice.signTransaction(simulateThree); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); @@ -135,19 +136,19 @@ describe("test on local testnet", function () { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = alice.getNonceThenIncrement(); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - + alice.incrementNonce(); const firstScCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", gasLimit: 3000000n, }); firstScCallTransaction.nonce = alice.getNonceThenIncrement(); - firstScCallTransaction.signature = alice.signTransaction(firstScCallTransaction); + firstScCallTransaction.signature = await alice.signTransaction(firstScCallTransaction); const secondScCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -155,7 +156,7 @@ describe("test on local testnet", function () { gasLimit: 3000000n, }); secondScCallTransaction.nonce = alice.getNonceThenIncrement(); - secondScCallTransaction.signature = alice.signTransaction(secondScCallTransaction); + secondScCallTransaction.signature = await alice.signTransaction(secondScCallTransaction); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); @@ -202,11 +203,11 @@ describe("test on local testnet", function () { gasLimit: 50000000n, arguments: [new U32Value(10000)], }); - deployTransaction.nonce = alice.getNonceThenIncrement(); - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.nonce = alice.nonce; + deployTransaction.signature = await alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - + alice.incrementNonce(); const transactionMintBob = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "transferToken", @@ -214,7 +215,7 @@ describe("test on local testnet", function () { arguments: [new AddressValue(bob.address), new U32Value(1000)], }); transactionMintBob.nonce = alice.getNonceThenIncrement(); - transactionMintBob.signature = alice.signTransaction(transactionMintBob); + transactionMintBob.signature = await alice.signTransaction(transactionMintBob); const transactionMintCarol = factory.createTransactionForExecute(alice.address, { contract: contractAddress, @@ -223,7 +224,7 @@ describe("test on local testnet", function () { arguments: [new AddressValue(carol.address), new U32Value(1500)], }); transactionMintCarol.nonce = alice.getNonceThenIncrement(); - transactionMintCarol.signature = alice.signTransaction(transactionMintCarol); + transactionMintCarol.signature = await alice.signTransaction(transactionMintCarol); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); @@ -292,12 +293,12 @@ describe("test on local testnet", function () { bytecode: bytecode, gasLimit: 50000000n, }); - deployTransaction.nonce = alice.getNonceThenIncrement(); + deployTransaction.nonce = alice.nonce; - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - + alice.incrementNonce(); const startTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "start", @@ -315,7 +316,7 @@ describe("test on local testnet", function () { ], }); startTransaction.nonce = alice.getNonceThenIncrement(); - startTransaction.signature = alice.signTransaction(startTransaction); + startTransaction.signature = await alice.signTransaction(startTransaction); // Broadcast & execute const deployTx = await provider.sendTransaction(deployTransaction); diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index 60525a061..c53bee3e7 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -66,7 +66,7 @@ describe("test contract", () => { ); // Sign the transaction - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); @@ -124,8 +124,8 @@ describe("test contract", () => { assert.equal(callTransactionTwo.gasLimit, 1500000n); // Sign transactions, broadcast them - callTransactionOne.signature = alice.signTransaction(callTransactionOne); - callTransactionTwo.signature = alice.signTransaction(callTransactionTwo); + callTransactionOne.signature = await alice.signTransaction(callTransactionOne); + callTransactionTwo.signature = await alice.signTransaction(callTransactionTwo); let hashOne = await provider.sendTransaction(callTransactionOne); let hashTwo = await provider.sendTransaction(callTransactionTwo); @@ -175,7 +175,7 @@ describe("test contract", () => { assert.equal(deployTransaction.nonce, 42n); // Sign the transaction - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); // Now let's broadcast the deploy transaction, and wait for its execution. let hash = await provider.sendTransaction(deployTransaction); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 1361cafac..feba9f846 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -56,7 +56,7 @@ describe("fetch transactions from local testnet", function () { }); transactionIncrement.nonce = alice.getNonceThenIncrement(); - transactionIncrement.signature = alice.signTransaction(transactionIncrement); + transactionIncrement.signature = await alice.signTransaction(transactionIncrement); // Broadcast & execute const txHashDeploy = await provider.sendTransaction(transactionDeploy); @@ -94,7 +94,7 @@ describe("fetch transactions from local testnet", function () { gasLimit: 3000000n, }); deployTransaction.nonce = alice.getNonceThenIncrement(); - deployTransaction.signature = alice.signTransaction(deployTransaction); + deployTransaction.signature = await alice.signTransaction(deployTransaction); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); @@ -104,7 +104,7 @@ describe("fetch transactions from local testnet", function () { gasLimit: 3000000n, }); smartContractCallTransaction.nonce = alice.getNonceThenIncrement(); - smartContractCallTransaction.signature = alice.signTransaction(smartContractCallTransaction); + smartContractCallTransaction.signature = await alice.signTransaction(smartContractCallTransaction); // Broadcast & execute const deployTxHash = await provider.sendTransaction(deployTransaction); diff --git a/src/accounts/account.spec.ts b/src/accounts/account.spec.ts index 901372cb2..b216f5eaa 100644 --- a/src/accounts/account.spec.ts +++ b/src/accounts/account.spec.ts @@ -70,7 +70,7 @@ describe("test account methods", function () { }); const account = Account.newFromMnemonic(DUMMY_MNEMONIC); - transaction.signature = account.signTransaction(transaction); + transaction.signature = await account.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -84,7 +84,7 @@ describe("test account methods", function () { }); const account = Account.newFromMnemonic(DUMMY_MNEMONIC); - message.signature = account.signMessage(message); + message.signature = await account.signMessage(message); assert.equal( Buffer.from(message.signature).toString("hex"), diff --git a/src/accounts/account.ts b/src/accounts/account.ts index 507fca1c1..2a8941534 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -100,13 +100,13 @@ export class Account implements IAccount { return this.publicKey.verify(data, signature); } - signTransaction(transaction: Transaction): Uint8Array { + async signTransaction(transaction: Transaction): Promise { const transactionComputer = new TransactionComputer(); const serializedTransaction = transactionComputer.computeBytesForSigning(transaction); return this.secretKey.sign(serializedTransaction); } - signMessage(message: Message): Uint8Array { + async signMessage(message: Message): Promise { const messageComputer = new MessageComputer(); const serializedMessage = messageComputer.computeBytesForSigning(message); return this.secretKey.sign(serializedMessage); diff --git a/src/core/transaction.spec.ts b/src/core/transaction.spec.ts index c67366a4f..438498377 100644 --- a/src/core/transaction.spec.ts +++ b/src/core/transaction.spec.ts @@ -84,7 +84,7 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -108,7 +108,7 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -133,7 +133,7 @@ describe("test transaction", async () => { receiverUsername: "alice", }); - transaction.signature = carol.signTransaction(transaction); + transaction.signature = await carol.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -218,7 +218,7 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -242,7 +242,7 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -267,7 +267,7 @@ describe("test transaction", async () => { version: 1, }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -290,7 +290,7 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -316,7 +316,7 @@ describe("test transaction", async () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -343,7 +343,7 @@ describe("test transaction", async () => { chainID: "T", }); - transaction.signature = carol.signTransaction(transaction); + transaction.signature = await carol.signTransaction(transaction); assert.equal( Buffer.from(transaction.signature).toString("hex"), @@ -370,7 +370,7 @@ describe("test transaction", async () => { guardian: Address.newFromBech32("erd1x23lzn8483xs2su4fak0r0dqx6w38enpmmqf2yrkylwq7mfnvyhsxqw57y"), }); transaction.guardianSignature = new Uint8Array(64); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); const serializer = new ProtoSerializer(); const buffer = serializer.serializeTransaction(transaction); @@ -590,7 +590,7 @@ describe("test transaction", async () => { version: 2, options: 2, }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); transaction.guardianSignature = transaction.signature; assert.isTrue(transaction.isGuardedTransaction()); }); @@ -690,7 +690,7 @@ describe("test transaction", async () => { nonce: 7n, }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); const userVerifier = new UserVerifier(new UserPublicKey(alice.address.getPublicKey())); const isSignedByAlice = userVerifier.verify( diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index cc1174acc..efaf9ba4b 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -2,7 +2,7 @@ import { assert } from "chai"; import { readFileSync } from "fs"; import path from "path"; import { Account } from "../accounts/account"; -import { Address, TransactionComputer } from "../core"; +import { Address } from "../core"; import { loadAbiRegistry } from "../testutils"; import { DevnetEntrypoint } from "./entrypoints"; @@ -98,7 +98,7 @@ describe("TestEntrypoint", () => { ); const innerTransactionGasLimit = transaction.gasLimit; transaction.gasLimit = BigInt(0); - transaction.signature = sender.signTransaction(transaction); + transaction.signature = await sender.signTransaction(transaction); const relayedController = entrypoint.createRelayedController(); const relayedTransaction = await relayedController.createRelayedV2Transaction( diff --git a/src/networkProviders/accountAwaiter.dev.net.spec.ts b/src/networkProviders/accountAwaiter.dev.net.spec.ts index 0569de466..f382b2527 100644 --- a/src/networkProviders/accountAwaiter.dev.net.spec.ts +++ b/src/networkProviders/accountAwaiter.dev.net.spec.ts @@ -58,7 +58,7 @@ describe("AccountAwaiter Tests", () => { value, }); transaction.nonce = (await api.getAccount(aliceAddress)).nonce; - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); const initialBalance = (await api.getAccount(frank)).balance; diff --git a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts index 60efbd683..4e7183a82 100644 --- a/src/networkProviders/apiNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/apiNetworkProvider.dev.net.spec.ts @@ -289,7 +289,7 @@ describe("ApiNetworkProvider Tests", function () { let txOnNetwork = await apiProvider.simulateTransaction(transaction); assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); txOnNetwork = await apiProvider.simulateTransaction(transaction, true); transaction = new Transaction({ @@ -313,7 +313,7 @@ describe("ApiNetworkProvider Tests", function () { assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); assert.deepEqual(txOnNetwork.smartContractResults[0].data, "@6f6b"); - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); txOnNetwork = await apiProvider.simulateTransaction(transaction, true); assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); @@ -336,7 +336,7 @@ describe("ApiNetworkProvider Tests", function () { data: new Uint8Array(Buffer.from("test transaction")), }); transaction.nonce = (await apiProvider.getAccount(bob.address)).nonce; - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); const response = await apiProvider.estimateTransactionCost(transaction); assert.equal(response.gasLimit, 74000); }); @@ -352,7 +352,7 @@ describe("ApiNetworkProvider Tests", function () { }); const nonce = (await apiProvider.getAccount(bob.address)).nonce; transaction.nonce = nonce; - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); let hash = await apiProvider.sendTransaction(transaction); let transactionOnNetwork = await apiProvider.awaitTransactionCompleted(hash); assert.isTrue(transactionOnNetwork.status.isCompleted()); @@ -365,7 +365,7 @@ describe("ApiNetworkProvider Tests", function () { data: new Uint8Array(Buffer.from("dummy@05")), }); transaction.nonce = nonce + 1n; - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); const condition = (txOnNetwork: TransactionOnNetwork) => !txOnNetwork.status.isSuccessful(); hash = await apiProvider.sendTransaction(transaction); diff --git a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts index de66a18ac..39322cb17 100644 --- a/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts +++ b/src/networkProviders/proxyNetworkProvider.dev.net.spec.ts @@ -289,7 +289,7 @@ describe("ProxyNetworkProvider Tests", function () { let txOnNetwork = await proxy.simulateTransaction(transaction); assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); txOnNetwork = await proxy.simulateTransaction(transaction); transaction = new Transaction({ @@ -313,7 +313,7 @@ describe("ProxyNetworkProvider Tests", function () { assert.equal(txOnNetwork.smartContractResults[0].receiver.toBech32(), bob.address.toBech32()); assert.equal(txOnNetwork.smartContractResults[0].data, "@6f6b"); - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); txOnNetwork = await proxy.simulateTransaction(transaction); assert.deepEqual(txOnNetwork.status, new TransactionStatus("success")); @@ -336,7 +336,7 @@ describe("ProxyNetworkProvider Tests", function () { data: new Uint8Array(Buffer.from("test transaction")), }); transaction.nonce = (await proxy.getAccount(bob.address)).nonce; - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); const response = await proxy.estimateTransactionCost(transaction); assert.equal(response.gasLimit, 74000); }); @@ -352,7 +352,7 @@ describe("ProxyNetworkProvider Tests", function () { }); const nonce = (await proxy.getAccount(bob.address)).nonce; transaction.nonce = nonce; - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); let hash = await proxy.sendTransaction(transaction); let transactionOnNetwork = await proxy.awaitTransactionCompleted(hash); assert.isTrue(transactionOnNetwork.status.isCompleted()); @@ -365,7 +365,7 @@ describe("ProxyNetworkProvider Tests", function () { data: new Uint8Array(Buffer.from("dummy@05")), }); transaction.nonce = nonce + 1n; - transaction.signature = bob.signTransaction(transaction); + transaction.signature = await bob.signTransaction(transaction); const condition = (txOnNetwork: TransactionOnNetwork) => !txOnNetwork.status.isSuccessful(); hash = await proxy.sendTransaction(transaction); diff --git a/src/proto/serializer.spec.ts b/src/proto/serializer.spec.ts index 729c22ec2..5f28d2c58 100644 --- a/src/proto/serializer.spec.ts +++ b/src/proto/serializer.spec.ts @@ -25,7 +25,7 @@ describe("serialize transactions", () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -45,7 +45,7 @@ describe("serialize transactions", () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -65,7 +65,7 @@ describe("serialize transactions", () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -85,7 +85,7 @@ describe("serialize transactions", () => { chainID: "local-testnet", }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -106,7 +106,7 @@ describe("serialize transactions", () => { version: 1, }); - transaction.signature = alice.signTransaction(transaction); + transaction.signature = await alice.signTransaction(transaction); let buffer = serializer.serializeTransaction(transaction); assert.equal( @@ -127,7 +127,7 @@ describe("serialize transactions", () => { chainID: "T", }); - transaction.signature = carol.signTransaction(transaction); + transaction.signature = await carol.signTransaction(transaction); const buffer = serializer.serializeTransaction(transaction); assert.equal( diff --git a/src/relayed/relayedTransactionsFactory.spec.ts b/src/relayed/relayedTransactionsFactory.spec.ts index 9f23543b7..9757de44b 100644 --- a/src/relayed/relayedTransactionsFactory.spec.ts +++ b/src/relayed/relayedTransactionsFactory.spec.ts @@ -50,14 +50,14 @@ describe("test relayed transactions factory", function () { nonce: 198n, }); - innerTransaction.signature = bob.signTransaction(innerTransaction); + innerTransaction.signature = await bob.signTransaction(innerTransaction); const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 2627n; - relayedTransaction.signature = alice.signTransaction(relayedTransaction); + relayedTransaction.signature = await alice.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -81,14 +81,14 @@ describe("test relayed transactions factory", function () { value: 1000000000000000000n, }); - innerTransaction.signature = carol.signTransaction(innerTransaction); + innerTransaction.signature = await carol.signTransaction(innerTransaction); const relayedTransaction = factory.createRelayedV1Transaction(frank.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 715n; - relayedTransaction.signature = frank.signTransaction(relayedTransaction); + relayedTransaction.signature = await frank.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -112,14 +112,14 @@ describe("test relayed transactions factory", function () { value: 1999999000000000000000000n, }); - innerTransaction.signature = carol.signTransaction(innerTransaction); + innerTransaction.signature = await carol.signTransaction(innerTransaction); const relayedTransaction = factory.createRelayedV1Transaction(frank.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 715n; - relayedTransaction.signature = frank.signTransaction(relayedTransaction); + relayedTransaction.signature = await frank.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -144,15 +144,15 @@ describe("test relayed transactions factory", function () { guardian: grace.address, }); - innerTransaction.signature = bob.signTransaction(innerTransaction); - innerTransaction.guardianSignature = grace.signTransaction(innerTransaction); + innerTransaction.signature = await bob.signTransaction(innerTransaction); + innerTransaction.guardianSignature = await grace.signTransaction(innerTransaction); const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { innerTransaction: innerTransaction, }); relayedTransaction.nonce = 2627n; - relayedTransaction.signature = alice.signTransaction(relayedTransaction); + relayedTransaction.signature = await alice.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -177,8 +177,8 @@ describe("test relayed transactions factory", function () { guardian: grace.address, }); - innerTransaction.signature = bob.signTransaction(innerTransaction); - innerTransaction.guardianSignature = grace.signTransaction(innerTransaction); + innerTransaction.signature = await bob.signTransaction(innerTransaction); + innerTransaction.guardianSignature = await grace.signTransaction(innerTransaction); const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { innerTransaction: innerTransaction, @@ -187,8 +187,8 @@ describe("test relayed transactions factory", function () { relayedTransaction.options = 2; relayedTransaction.guardian = frank.address; - relayedTransaction.signature = alice.signTransaction(relayedTransaction); - relayedTransaction.guardianSignature = frank.signTransaction(relayedTransaction); + relayedTransaction.signature = await alice.signTransaction(relayedTransaction); + relayedTransaction.guardianSignature = await frank.signTransaction(relayedTransaction); assert.equal( Buffer.from(relayedTransaction.data).toString(), @@ -239,7 +239,7 @@ describe("test relayed transactions factory", function () { options: 0, }); - innerTransaction.signature = bob.signTransaction(innerTransaction); + innerTransaction.signature = await bob.signTransaction(innerTransaction); const relayedTransaction = factory.createRelayedV2Transaction(alice.address, { innerTransaction: innerTransaction, @@ -247,7 +247,7 @@ describe("test relayed transactions factory", function () { }); relayedTransaction.nonce = 37n; - relayedTransaction.signature = alice.signTransaction(relayedTransaction); + relayedTransaction.signature = await alice.signTransaction(relayedTransaction); assert.equal(relayedTransaction.version, 2); assert.equal(relayedTransaction.options, 0); diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index a97e895a6..e91531f5c 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -31,7 +31,7 @@ export async function prepareDeployment(obj: { transaction.nonce = nonce; transaction.sender = deployer.address; contract.setAddress(contractAddress); - transaction.signature = deployer.signTransaction(transaction); + transaction.signature = await deployer.signTransaction(transaction); return transaction; } From 4fa62b5d5891abea848657707a16a0bb3660eeb9 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Feb 2025 11:42:37 +0200 Subject: [PATCH 168/214] Fix integration tests --- src/abi/smartContractResults.local.net.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index feba9f846..299b006a2 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -93,8 +93,9 @@ describe("fetch transactions from local testnet", function () { bytecode: bytecode, gasLimit: 3000000n, }); - deployTransaction.nonce = alice.getNonceThenIncrement(); + deployTransaction.nonce = alice.nonce; deployTransaction.signature = await alice.signTransaction(deployTransaction); + alice.incrementNonce(); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); From 16999cb793549f48c16ea8d7af5f828d1998c1cd Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Feb 2025 11:47:21 +0200 Subject: [PATCH 169/214] Fix unit test --- src/core/message.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/message.spec.ts b/src/core/message.spec.ts index 2cb0776e2..85642ac80 100644 --- a/src/core/message.spec.ts +++ b/src/core/message.spec.ts @@ -36,7 +36,7 @@ describe("test message", () => { address: alice.address, }); - message.signature = alice.signMessage(message); + message.signature = await alice.signMessage(message); assert.equal( Buffer.from(message.signature).toString("hex"), From f69cd4bc32472d1ff7f2dd676307c465b8ff53a3 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Feb 2025 12:00:11 +0200 Subject: [PATCH 170/214] Fix smart contract result integration test --- src/abi/smartContractResults.local.net.spec.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index 299b006a2..e8a3411ef 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -95,10 +95,9 @@ describe("fetch transactions from local testnet", function () { }); deployTransaction.nonce = alice.nonce; deployTransaction.signature = await alice.signTransaction(deployTransaction); - alice.incrementNonce(); const contractAddress = SmartContract.computeAddress(alice.address, alice.nonce); - + alice.incrementNonce(); const smartContractCallTransaction = factory.createTransactionForExecute(alice.address, { contract: contractAddress, function: "increment", From 7a98194efba9b720947e7927478661d6c39d6127 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Feb 2025 14:47:43 +0200 Subject: [PATCH 171/214] Add verifyMessage and verifyTransaction on account --- src/accounts/account.spec.ts | 38 ++++++++++++++++++++++ src/accounts/account.ts | 14 +++++++- src/accounts/interfaces.ts | 5 +++ src/core/message.spec.ts | 9 ++---- src/core/transaction.spec.ts | 25 +++----------- src/entrypoints/entrypoints.ts | 20 ++++-------- src/wallet/crypto/pubkeyDecryptor.ts | 23 ++++++------- src/wallet/crypto/pubkeyEncrypt.spec.ts | 43 +++++++++++++++++-------- src/wallet/userKeys.ts | 2 +- src/wallet/userVerifier.ts | 2 +- src/wallet/users.spec.ts | 17 +++++----- src/wallet/usersBenchmark.spec.ts | 4 +-- 12 files changed, 123 insertions(+), 79 deletions(-) diff --git a/src/accounts/account.spec.ts b/src/accounts/account.spec.ts index b216f5eaa..17459e667 100644 --- a/src/accounts/account.spec.ts +++ b/src/accounts/account.spec.ts @@ -91,4 +91,42 @@ describe("test account methods", function () { "561bc58f1dc6b10de208b2d2c22c9a474ea5e8cabb59c3d3ce06bbda21cc46454aa71a85d5a60442bd7784effa2e062fcb8fb421c521f898abf7f5ec165e5d0f", ); }); + + it("should verify message", async function () { + const message = new Message({ + data: new Uint8Array(Buffer.from("hello")), + }); + + const account = Account.newFromMnemonic(DUMMY_MNEMONIC); + message.signature = await account.signMessage(message); + const isVerified = await account.verifyMessage(message, message.signature); + + assert.isTrue(isVerified); + }); + + it("should sign and verify transaction", async function () { + const transaction = new Transaction({ + nonce: 89n, + value: 0n, + receiver: Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"), + sender: Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"), + gasPrice: 1000000000n, + gasLimit: 50000n, + data: new Uint8Array(), + chainID: "local-testnet", + version: 1, + options: 0, + }); + + const account = Account.newFromMnemonic(DUMMY_MNEMONIC); + transaction.signature = await account.signTransaction(transaction); + + assert.equal( + Buffer.from(transaction.signature).toString("hex"), + "b56769014f2bdc5cf9fc4a05356807d71fcf8775c819b0f1b0964625b679c918ffa64862313bfef86f99b38cb84fcdb16fa33ad6eb565276616723405cd8f109", + ); + + const isVerified = await account.verifyTransaction(transaction, transaction.signature); + assert.isTrue(isVerified); + }); }); diff --git a/src/accounts/account.ts b/src/accounts/account.ts index 2a8941534..8d2fc8b1d 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -96,7 +96,7 @@ export class Account implements IAccount { return this.secretKey.sign(data); } - verify(data: Uint8Array, signature: Uint8Array): boolean { + async verify(data: Uint8Array, signature: Uint8Array): Promise { return this.publicKey.verify(data, signature); } @@ -106,12 +106,24 @@ export class Account implements IAccount { return this.secretKey.sign(serializedTransaction); } + async verifyTransaction(transaction: Transaction, signature: Uint8Array): Promise { + const transactionComputer = new TransactionComputer(); + const serializedTransaction = transactionComputer.computeBytesForVerifying(transaction); + return this.publicKey.verify(serializedTransaction, signature); + } + async signMessage(message: Message): Promise { const messageComputer = new MessageComputer(); const serializedMessage = messageComputer.computeBytesForSigning(message); return this.secretKey.sign(serializedMessage); } + async verifyMessage(message: Message, signature: Uint8Array): Promise { + const messageComputer = new MessageComputer(); + const serializedMessage = messageComputer.computeBytesForVerifying(message); + return this.publicKey.verify(serializedMessage, signature); + } + getNonceThenIncrement(): bigint { let nonce = this.nonce; this.nonce = this.nonce + 1n; diff --git a/src/accounts/interfaces.ts b/src/accounts/interfaces.ts index f4bb10c53..5c7b3ba8c 100644 --- a/src/accounts/interfaces.ts +++ b/src/accounts/interfaces.ts @@ -1,7 +1,12 @@ +import { Message, Transaction } from "../core"; import { Address } from "../core/address"; export interface IAccount { readonly address: Address; sign(data: Uint8Array): Promise; + signTransaction(transaction: Transaction): Promise; + verifyTransaction(transaction: Transaction, signature: Uint8Array): Promise; + signMessage(message: Message): Promise; + verifyMessage(message: Message, signature: Uint8Array): Promise; } diff --git a/src/core/message.spec.ts b/src/core/message.spec.ts index 85642ac80..d6f71addf 100644 --- a/src/core/message.spec.ts +++ b/src/core/message.spec.ts @@ -1,7 +1,6 @@ import { assert } from "chai"; import { Account } from "../accounts"; import { getTestWalletsPath } from "../testutils/utils"; -import { UserVerifier } from "../wallet"; import { DEFAULT_MESSAGE_VERSION, SDK_JS_SIGNER, UNKNOWN_SIGNER } from "./constants"; import { Message, MessageComputer } from "./message"; @@ -60,12 +59,8 @@ describe("test message", () => { assert.deepEqual(unpackedMessage.version, message.version); assert.deepEqual(unpackedMessage.signer, message.signer); - const verifier = UserVerifier.fromAddress(alice.address); - const isValid = verifier.verify( - Buffer.from(messageComputer.computeBytesForVerifying(unpackedMessage)), - Buffer.from(unpackedMessage.signature!), - ); - assert.equal(isValid, true); + const isValid = await alice.verifyMessage(unpackedMessage, Buffer.from(unpackedMessage.signature!)); + assert.isTrue(isValid); }); it("should unpack legacy message", async () => { diff --git a/src/core/transaction.spec.ts b/src/core/transaction.spec.ts index 438498377..c607de45c 100644 --- a/src/core/transaction.spec.ts +++ b/src/core/transaction.spec.ts @@ -3,7 +3,6 @@ import { assert } from "chai"; import { Account } from "../accounts"; import { ProtoSerializer } from "../proto"; import { getTestWalletsPath } from "../testutils/utils"; -import { UserPublicKey, UserVerifier } from "../wallet"; import { Address } from "./address"; import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, TRANSACTION_OPTIONS_DEFAULT } from "./constants"; import { INetworkConfig } from "./interface"; @@ -692,17 +691,9 @@ describe("test transaction", async () => { transaction.signature = await alice.signTransaction(transaction); - const userVerifier = new UserVerifier(new UserPublicKey(alice.address.getPublicKey())); - const isSignedByAlice = userVerifier.verify( - transactionComputer.computeBytesForVerifying(transaction), - transaction.signature, - ); + const isSignedByAlice = await alice.verifyTransaction(transaction, transaction.signature); - const wrongVerifier = new UserVerifier(new UserPublicKey(bob.address.getPublicKey())); - const isSignedByBob = wrongVerifier.verify( - transactionComputer.computeBytesForVerifying(transaction), - transaction.signature, - ); + const isSignedByBob = await bob.verifyTransaction(transaction, transaction.signature); assert.equal(isSignedByAlice, true); assert.equal(isSignedByBob, false); @@ -721,17 +712,9 @@ describe("test transaction", async () => { transaction.signature = await alice.sign(transactionComputer.computeHashForSigning(transaction)); - const userVerifier = new UserVerifier(alice.publicKey); - const isSignedByAlice = userVerifier.verify( - transactionComputer.computeBytesForVerifying(transaction), - transaction.signature, - ); + const isSignedByAlice = await alice.verifyTransaction(transaction, transaction.signature); - const wrongVerifier = new UserVerifier(new UserPublicKey(bob.address.getPublicKey())); - const isSignedByBob = wrongVerifier.verify( - transactionComputer.computeBytesForVerifying(transaction), - transaction.signature, - ); + const isSignedByBob = await bob.verifyTransaction(transaction, transaction.signature); assert.equal(isSignedByAlice, true); assert.equal(isSignedByBob, false); }); diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 141546b1a..dee790bac 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -4,9 +4,8 @@ import { Account } from "../accounts"; import { IAccount } from "../accounts/interfaces"; import { Address } from "../core/address"; import { ErrInvalidNetworkProviderKind } from "../core/errors"; -import { Message, MessageComputer } from "../core/message"; +import { Message } from "../core/message"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { TransactionWatcher } from "../core/transactionWatcher"; @@ -20,7 +19,7 @@ import { SmartContractController } from "../smartContracts/smartContractControll import { TokenManagementController, TokenManagementTransactionsFactory } from "../tokenManagement"; import { TransferTransactionsFactory } from "../transfers"; import { TransfersController } from "../transfers/transfersControllers"; -import { UserSecretKey, UserVerifier } from "../wallet"; +import { UserSecretKey } from "../wallet"; import { DevnetEntrypointConfig, MainnetEntrypointConfig, TestnetEntrypointConfig } from "./config"; class NetworkEntrypoint { @@ -49,17 +48,14 @@ class NetworkEntrypoint { } async signTransaction(transaction: Transaction, account: IAccount): Promise { - const txComputer = new TransactionComputer(); - transaction.signature = await account.sign(txComputer.computeBytesForSigning(transaction)); + transaction.signature = await account.signTransaction(transaction); } - verifyTransactionSignature(transaction: Transaction): boolean { - const verifier = UserVerifier.fromAddress(transaction.sender); - const txComputer = new TransactionComputer(); - return verifier.verify(txComputer.computeBytesForVerifying(transaction), transaction.signature); + async verifyTransactionSignature(transaction: Transaction, account: IAccount): Promise { + return await account.verifyTransaction(transaction, transaction.signature); } - verifyMessageSignature(message: Message): boolean { + async verifyMessageSignature(message: Message, account: IAccount): Promise { if (!message.address) { throw new Error("`address` property of Message is not set"); } @@ -68,9 +64,7 @@ class NetworkEntrypoint { throw new Error("`signature` property of Message is not set"); } - const verifier = UserVerifier.fromAddress(message.address); - const messageComputer = new MessageComputer(); - return verifier.verify(messageComputer.computeBytesForVerifying(message), message.signature); + return await account.verifyMessage(message, message.signature); } async recallAccountNonce(address: Address): Promise { diff --git a/src/wallet/crypto/pubkeyDecryptor.ts b/src/wallet/crypto/pubkeyDecryptor.ts index e9b6d7a00..b70a58915 100644 --- a/src/wallet/crypto/pubkeyDecryptor.ts +++ b/src/wallet/crypto/pubkeyDecryptor.ts @@ -1,25 +1,26 @@ import crypto from "crypto"; -import nacl from "tweetnacl"; import ed2curve from "ed2curve"; -import { X25519EncryptedData } from "./x25519EncryptedData"; +import nacl from "tweetnacl"; import { UserPublicKey, UserSecretKey } from "../userKeys"; +import { X25519EncryptedData } from "./x25519EncryptedData"; export class PubkeyDecryptor { - static decrypt(data: X25519EncryptedData, decryptorSecretKey: UserSecretKey): Buffer { - const ciphertext = Buffer.from(data.ciphertext, 'hex'); - const edhPubKey = Buffer.from(data.identities.ephemeralPubKey, 'hex'); - const originatorPubKeyBuffer = Buffer.from(data.identities.originatorPubKey, 'hex'); + static async decrypt(data: X25519EncryptedData, decryptorSecretKey: UserSecretKey): Promise { + const ciphertext = Buffer.from(data.ciphertext, "hex"); + const edhPubKey = Buffer.from(data.identities.ephemeralPubKey, "hex"); + const originatorPubKeyBuffer = Buffer.from(data.identities.originatorPubKey, "hex"); const originatorPubKey = new UserPublicKey(originatorPubKeyBuffer); - const authMessage = crypto.createHash('sha256').update( - Buffer.concat([ciphertext, edhPubKey]) - ).digest(); + const authMessage = crypto + .createHash("sha256") + .update(Buffer.concat([ciphertext, edhPubKey])) + .digest(); - if (!originatorPubKey.verify(authMessage, Buffer.from(data.mac, 'hex'))) { + if (!(await originatorPubKey.verify(authMessage, Buffer.from(data.mac, "hex")))) { throw new Error("Invalid authentication for encrypted message originator"); } - const nonce = Buffer.from(data.nonce, 'hex'); + const nonce = Buffer.from(data.nonce, "hex"); const x25519Secret = ed2curve.convertSecretKey(decryptorSecretKey.valueOf()); const x25519EdhPubKey = ed2curve.convertPublicKey(edhPubKey); if (x25519EdhPubKey === null) { diff --git a/src/wallet/crypto/pubkeyEncrypt.spec.ts b/src/wallet/crypto/pubkeyEncrypt.spec.ts index 804a35f5b..f550cd2f2 100644 --- a/src/wallet/crypto/pubkeyEncrypt.spec.ts +++ b/src/wallet/crypto/pubkeyEncrypt.spec.ts @@ -22,24 +22,39 @@ describe("test address", () => { ); }); - it("encrypts/decrypts", () => { - const decryptedData = PubkeyDecryptor.decrypt(encryptedDataOfAliceForBob, new UserSecretKey(bob.secretKey)); + it("encrypts/decrypts", async function () { + const decryptedData = await PubkeyDecryptor.decrypt( + encryptedDataOfAliceForBob, + new UserSecretKey(bob.secretKey), + ); assert.equal(sensitiveData.toString("hex"), decryptedData.toString("hex")); }); - it("fails for different originator", () => { - encryptedDataOfAliceForBob.identities.originatorPubKey = carol.address.hex(); - assert.throws( - () => PubkeyDecryptor.decrypt(encryptedDataOfAliceForBob, new UserSecretKey(bob.secretKey)), - "Invalid authentication for encrypted message originator", - ); + it("fails for different originator", async function () { + encryptedDataOfAliceForBob.identities.originatorPubKey = carol.address.toHex(); + + try { + await PubkeyDecryptor.decrypt(encryptedDataOfAliceForBob, new UserSecretKey(bob.secretKey)); + assert.fail("Invalid authentication for encrypted message originator"); + } catch (error) { + assert( + error.message.includes("Invalid authentication for encrypted message originator"), + `Unexpected error message: ${error.message}`, + ); + } }); - it("fails for different DH public key", () => { - encryptedDataOfAliceForBob.identities.ephemeralPubKey = carol.address.hex(); - assert.throws( - () => PubkeyDecryptor.decrypt(encryptedDataOfAliceForBob, new UserSecretKey(bob.secretKey)), - "Invalid authentication for encrypted message originator", - ); + it("fails for different DH public key", async function () { + encryptedDataOfAliceForBob.identities.ephemeralPubKey = carol.address.toHex(); + + try { + await PubkeyDecryptor.decrypt(encryptedDataOfAliceForBob, new UserSecretKey(bob.secretKey)); + assert.fail("Expected an error but none was thrown"); + } catch (error) { + assert( + error.message.includes("Invalid authentication for encrypted message originator"), + `Unexpected error message: ${error.message}`, + ); + } }); }); diff --git a/src/wallet/userKeys.ts b/src/wallet/userKeys.ts index 801e58bfc..0a0259cec 100644 --- a/src/wallet/userKeys.ts +++ b/src/wallet/userKeys.ts @@ -68,7 +68,7 @@ export class UserPublicKey { this.buffer = Buffer.from(buffer); } - verify(data: Buffer | Uint8Array, signature: Buffer | Uint8Array): boolean { + async verify(data: Buffer | Uint8Array, signature: Buffer | Uint8Array): Promise { try { const ok = ed.sync.verify(new Uint8Array(signature), new Uint8Array(data), new Uint8Array(this.buffer)); return ok; diff --git a/src/wallet/userVerifier.ts b/src/wallet/userVerifier.ts index c13035ce3..00426ca47 100644 --- a/src/wallet/userVerifier.ts +++ b/src/wallet/userVerifier.ts @@ -22,7 +22,7 @@ export class UserVerifier { * @param signature the signature to be verified * @returns true if the signature is valid, false otherwise */ - verify(data: Buffer | Uint8Array, signature: Buffer | Uint8Array): boolean { + async verify(data: Buffer | Uint8Array, signature: Buffer | Uint8Array): Promise { return this.publicKey.verify(data, signature); } } diff --git a/src/wallet/users.spec.ts b/src/wallet/users.spec.ts index c4578b03d..b24138326 100644 --- a/src/wallet/users.spec.ts +++ b/src/wallet/users.spec.ts @@ -1,5 +1,6 @@ import { assert } from "chai"; import path from "path"; +import { Account } from "../accounts"; import { Address, ErrBadMnemonicEntropy, ErrInvariantFailed, Message, Transaction } from "../core"; import { DummyMnemonicOf12Words, @@ -290,7 +291,7 @@ describe("test user wallets", () => { }); it("should sign transactions", async () => { - let signer = new UserSigner( + let signer = new Account( UserSecretKey.fromString("1a927e2af5306a9bb2ea777f73e06ecc0ac9aaa72fb4ea3fecf659451394cccf"), ); let verifier = new UserVerifier( @@ -323,7 +324,7 @@ describe("test user wallets", () => { Buffer.from(signature).toString("hex"), "a5db62c6186612d44094f83576aa6a664299315fb6e42d0c17a40e9cd33efa9a9df8b76943aeac7dceaff3d78a16a7414c914f03f7a88e786c2cf939eb111c06", ); - assert.isTrue(verifier.verify(serialized, signature)); + assert.isTrue(await verifier.verify(serialized, signature)); // Without data field transaction = new Transaction({ @@ -393,7 +394,7 @@ describe("test user wallets", () => { Buffer.from(guardianSignature).toString("hex"), "5695fde5d9c77a94bb320438fbebe3bbd60b7cc4d633fb38e42bb65f83d253cbb82cc5ae40d701a7f0b839a5231320ca356018ced949885baae473e469ec770e", ); - assert.isTrue(verifier.verify(serialized, signature)); + assert.isTrue(await verifier.verify(serialized, signature)); // Without data field transaction = new Transaction({ @@ -425,7 +426,7 @@ describe("test user wallets", () => { Buffer.from(guardianSignature).toString("hex"), "ea3b83adcc468b0c7d3613fca5f429a9764d5710137c34c27e15d06e625326724ccfa758968507acadb14345d19389ba6004a4f0a6c527799c01713e10cf650b", ); - assert.isTrue(verifier.verify(serialized, signature)); + assert.isTrue(await verifier.verify(serialized, signature)); }); it("should sign transactions using PEM files", async () => { @@ -469,10 +470,10 @@ describe("test user wallets", () => { const signature = await signer.sign(message.data); assert.deepEqual(await signer.sign(message.data), await signer.sign(Uint8Array.from(message.data))); - assert.isTrue(verifier.verify(message.data, signature)); - assert.isTrue(verifier.verify(Uint8Array.from(message.data), Uint8Array.from(signature))); - assert.isFalse(verifier.verify(Buffer.from("hello"), signature)); - assert.isFalse(verifier.verify(new TextEncoder().encode("hello"), signature)); + assert.isTrue(await verifier.verify(message.data, signature)); + assert.isTrue(await verifier.verify(Uint8Array.from(message.data), Uint8Array.from(signature))); + assert.isFalse(await verifier.verify(Buffer.from("hello"), signature)); + assert.isFalse(await verifier.verify(new TextEncoder().encode("hello"), signature)); }); it("should create UserSigner from wallet", async function () { diff --git a/src/wallet/usersBenchmark.spec.ts b/src/wallet/usersBenchmark.spec.ts index 5eafc86f1..5d053ef90 100644 --- a/src/wallet/usersBenchmark.spec.ts +++ b/src/wallet/usersBenchmark.spec.ts @@ -36,7 +36,7 @@ describe("behchmark sign and verify", () => { console.time("verify (good)"); for (let i = 0; i < n; i++) { - const ok = publicKeys[i].verify(messages[i], goodSignatures[i]); + const ok = await publicKeys[i].verify(messages[i], goodSignatures[i]); assert.isTrue(ok); } @@ -45,7 +45,7 @@ describe("behchmark sign and verify", () => { console.time("verify (bad)"); for (let i = 0; i < n; i++) { - const ok = publicKeys[i].verify(messages[messages.length - i - 1], goodSignatures[i]); + const ok = await publicKeys[i].verify(messages[messages.length - i - 1], goodSignatures[i]); assert.isFalse(ok); } From 4f315d6e2dc1b43ec377f3237504620070494942 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Feb 2025 15:44:59 +0200 Subject: [PATCH 172/214] Update methods to follow specs --- src/accounts/account.spec.ts | 4 ++-- src/accounts/account.ts | 4 ++-- src/accounts/interfaces.ts | 4 ++-- src/core/message.spec.ts | 2 +- src/core/transaction.spec.ts | 8 ++++---- src/entrypoints/entrypoints.ts | 4 ++-- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/accounts/account.spec.ts b/src/accounts/account.spec.ts index 17459e667..cf4e1cfd2 100644 --- a/src/accounts/account.spec.ts +++ b/src/accounts/account.spec.ts @@ -99,7 +99,7 @@ describe("test account methods", function () { const account = Account.newFromMnemonic(DUMMY_MNEMONIC); message.signature = await account.signMessage(message); - const isVerified = await account.verifyMessage(message, message.signature); + const isVerified = await account.verifyMessageSignature(message, message.signature); assert.isTrue(isVerified); }); @@ -126,7 +126,7 @@ describe("test account methods", function () { "b56769014f2bdc5cf9fc4a05356807d71fcf8775c819b0f1b0964625b679c918ffa64862313bfef86f99b38cb84fcdb16fa33ad6eb565276616723405cd8f109", ); - const isVerified = await account.verifyTransaction(transaction, transaction.signature); + const isVerified = await account.verifyTransactionSignature(transaction, transaction.signature); assert.isTrue(isVerified); }); }); diff --git a/src/accounts/account.ts b/src/accounts/account.ts index 8d2fc8b1d..0c1716fa4 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -106,7 +106,7 @@ export class Account implements IAccount { return this.secretKey.sign(serializedTransaction); } - async verifyTransaction(transaction: Transaction, signature: Uint8Array): Promise { + async verifyTransactionSignature(transaction: Transaction, signature: Uint8Array): Promise { const transactionComputer = new TransactionComputer(); const serializedTransaction = transactionComputer.computeBytesForVerifying(transaction); return this.publicKey.verify(serializedTransaction, signature); @@ -118,7 +118,7 @@ export class Account implements IAccount { return this.secretKey.sign(serializedMessage); } - async verifyMessage(message: Message, signature: Uint8Array): Promise { + async verifyMessageSignature(message: Message, signature: Uint8Array): Promise { const messageComputer = new MessageComputer(); const serializedMessage = messageComputer.computeBytesForVerifying(message); return this.publicKey.verify(serializedMessage, signature); diff --git a/src/accounts/interfaces.ts b/src/accounts/interfaces.ts index 5c7b3ba8c..a10b9e943 100644 --- a/src/accounts/interfaces.ts +++ b/src/accounts/interfaces.ts @@ -6,7 +6,7 @@ export interface IAccount { sign(data: Uint8Array): Promise; signTransaction(transaction: Transaction): Promise; - verifyTransaction(transaction: Transaction, signature: Uint8Array): Promise; + verifyTransactionSignature(transaction: Transaction, signature: Uint8Array): Promise; signMessage(message: Message): Promise; - verifyMessage(message: Message, signature: Uint8Array): Promise; + verifyMessageSignature(message: Message, signature: Uint8Array): Promise; } diff --git a/src/core/message.spec.ts b/src/core/message.spec.ts index d6f71addf..8f81c3466 100644 --- a/src/core/message.spec.ts +++ b/src/core/message.spec.ts @@ -59,7 +59,7 @@ describe("test message", () => { assert.deepEqual(unpackedMessage.version, message.version); assert.deepEqual(unpackedMessage.signer, message.signer); - const isValid = await alice.verifyMessage(unpackedMessage, Buffer.from(unpackedMessage.signature!)); + const isValid = await alice.verifyMessageSignature(unpackedMessage, Buffer.from(unpackedMessage.signature!)); assert.isTrue(isValid); }); diff --git a/src/core/transaction.spec.ts b/src/core/transaction.spec.ts index c607de45c..d6d8ffcd2 100644 --- a/src/core/transaction.spec.ts +++ b/src/core/transaction.spec.ts @@ -691,9 +691,9 @@ describe("test transaction", async () => { transaction.signature = await alice.signTransaction(transaction); - const isSignedByAlice = await alice.verifyTransaction(transaction, transaction.signature); + const isSignedByAlice = await alice.verifyTransactionSignature(transaction, transaction.signature); - const isSignedByBob = await bob.verifyTransaction(transaction, transaction.signature); + const isSignedByBob = await bob.verifyTransactionSignature(transaction, transaction.signature); assert.equal(isSignedByAlice, true); assert.equal(isSignedByBob, false); @@ -712,9 +712,9 @@ describe("test transaction", async () => { transaction.signature = await alice.sign(transactionComputer.computeHashForSigning(transaction)); - const isSignedByAlice = await alice.verifyTransaction(transaction, transaction.signature); + const isSignedByAlice = await alice.verifyTransactionSignature(transaction, transaction.signature); - const isSignedByBob = await bob.verifyTransaction(transaction, transaction.signature); + const isSignedByBob = await bob.verifyTransactionSignature(transaction, transaction.signature); assert.equal(isSignedByAlice, true); assert.equal(isSignedByBob, false); }); diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index dee790bac..d15f3302e 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -52,7 +52,7 @@ class NetworkEntrypoint { } async verifyTransactionSignature(transaction: Transaction, account: IAccount): Promise { - return await account.verifyTransaction(transaction, transaction.signature); + return await account.verifyTransactionSignature(transaction, transaction.signature); } async verifyMessageSignature(message: Message, account: IAccount): Promise { @@ -64,7 +64,7 @@ class NetworkEntrypoint { throw new Error("`signature` property of Message is not set"); } - return await account.verifyMessage(message, message.signature); + return await account.verifyMessageSignature(message, message.signature); } async recallAccountNonce(address: Address): Promise { From 5a7411a3dbf14bc049e22ae24e8e800da52d6e0c Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 24 Feb 2025 13:56:57 +0200 Subject: [PATCH 173/214] Add relayer and guardian on controllers functions --- src/accountManagement/accountController.ts | 21 ++- src/delegation/delegationController.ts | 79 ++++++++++++ src/entrypoints/entrypoints.spec.ts | 39 +++++- src/smartContracts/smartContractController.ts | 13 ++ .../tokenManagementController.ts | 121 ++++++++++++++++++ src/transfers/transfersControllers.ts | 13 ++ 6 files changed, 283 insertions(+), 3 deletions(-) diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index f7a67eef6..89a353257 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -1,4 +1,5 @@ import { IAccount } from "../accounts/interfaces"; +import { Address } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; @@ -20,9 +21,13 @@ export class AccountController { sender: IAccount, nonce: bigint, options: SaveKeyValueInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSavingKeyValue(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -33,27 +38,39 @@ export class AccountController { sender: IAccount, nonce: bigint, options: SetGuardianInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingGuardian(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; } - async createTransactionForGuardingAccount(sender: IAccount, nonce: bigint): Promise { + async createTransactionForGuardingAccount(sender: IAccount, nonce: bigint, + guardian: Address = Address.empty(), + relayer: Address = Address.empty()): Promise { const transaction = this.factory.createTransactionForGuardingAccount(sender.address); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; } - async createTransactionForUnguardingAccount(sender: IAccount, nonce: bigint): Promise { + async createTransactionForUnguardingAccount(sender: IAccount, nonce: bigint, + guardian: Address = Address.empty(), + relayer: Address = Address.empty()): Promise { const transaction = this.factory.createTransactionForUnguardingAccount(sender.address); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index 1d21ce731..c5c0ac660 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -1,4 +1,5 @@ import { IAccount } from "../accounts/interfaces"; +import { Address } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; @@ -28,9 +29,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.NewDelegationContractInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForNewDelegationContract(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -50,9 +55,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.AddNodesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForAddingNodes(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -63,9 +72,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageNodesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForRemovingNodes(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -76,9 +89,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageNodesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForStakingNodes(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -89,9 +106,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageNodesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUnbondingNodes(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -102,9 +123,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageNodesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUnstakingNodes(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -115,9 +140,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.UnjailingNodesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUnjailingNodes(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -128,9 +157,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ChangeServiceFee, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForChangingServiceFee(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -141,9 +174,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ModifyDelegationCapInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForModifyingDelegationCap(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -154,9 +191,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageDelegationContractInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingAutomaticActivation(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -167,9 +208,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageDelegationContractInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUnsettingAutomaticActivation(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -180,12 +225,16 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageDelegationContractInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingCapCheckOnRedelegateRewards( sender.address, options, ); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -196,12 +245,16 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageDelegationContractInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUnsettingCapCheckOnRedelegateRewards( sender.address, options, ); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -212,9 +265,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.SetContractMetadataInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingMetadata(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -225,9 +282,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.DelegateActionsInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForDelegating(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -238,9 +299,14 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageDelegationContractInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() + ): Promise { const transaction = this.factory.createTransactionForClaimingRewards(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -251,9 +317,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageDelegationContractInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForRedelegatingRewards(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -264,9 +334,13 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.DelegateActionsInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUndelegating(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -277,10 +351,15 @@ export class DelegationController { sender: IAccount, nonce: bigint, options: resources.ManageDelegationContractInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForWithdrawing(sender.address, options); transaction.nonce = nonce; + transaction.guardian = guardian; + transaction.relayer = relayer; + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index efaf9ba4b..87489ec09 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -9,7 +9,7 @@ import { DevnetEntrypoint } from "./entrypoints"; describe("TestEntrypoint", () => { const entrypoint = new DevnetEntrypoint(); - before(async function () {}); + before(async function () { }); it("native transfer", async () => { const controller = entrypoint.createTransfersController(); @@ -32,6 +32,43 @@ describe("TestEntrypoint", () => { ); }); + it("native transfer with guardian and relayer", async () => { + const controller = entrypoint.createTransfersController(); + const filePath = path.join("src", "testdata", "testwallets"); + const sender = await Account.newFromPem(path.join(filePath, "alice.pem")); + const grace = await Account.newFromPem(path.join(filePath, "grace.pem")); + sender.nonce = 77777n; + + const transaction = await controller.createTransactionForTransfer( + sender, + BigInt(sender.getNonceThenIncrement().valueOf()), + { + receiver: sender.address, + nativeAmount: BigInt(0), + data: Buffer.from("hello"), + }, + grace.address, + grace.address + ); + assert.deepEqual( + transaction.guardian, + grace.address, + ); + assert.deepEqual( + transaction.relayer, + grace.address, + ); + assert.deepEqual( + transaction.guardianSignature, + new Uint8Array(), + ); + + assert.deepEqual( + transaction.relayerSignature, + new Uint8Array(), + ); + }); + it("contract flow", async function () { this.timeout(30000); const abi = await loadAbiRegistry("src/testdata/adder.abi.json"); diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index 01a8327b1..3408a5353 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -1,5 +1,6 @@ import { AbiRegistry, ArgSerializer, isTyped, NativeSerializer } from "../abi"; import { IAccount } from "../accounts/interfaces"; +import { Address } from "../core"; import { Err, ErrSmartContractQuery } from "../core/errors"; import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../core/smartContractQuery"; import { Transaction } from "../core/transaction"; @@ -36,9 +37,13 @@ export class SmartContractController { sender: IAccount, nonce: bigint, options: resources.ContractDeployInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForDeploy(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -58,9 +63,13 @@ export class SmartContractController { sender: IAccount, nonce: bigint, options: resources.ContractUpgradeInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUpgrade(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -71,9 +80,13 @@ export class SmartContractController { sender: IAccount, nonce: bigint, options: resources.ContractExecuteInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForExecute(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index a3a3bfd77..2e5789f54 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -1,4 +1,5 @@ import { IAccount } from "../accounts/interfaces"; +import { Address } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; @@ -28,9 +29,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.IssueFungibleInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForIssuingFungible(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -50,9 +55,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.IssueSemiFungibleInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForIssuingSemiFungible(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -72,9 +81,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.IssueNonFungibleInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForIssuingNonFungible(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -94,9 +107,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.RegisterMetaESDTInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForRegisteringMetaESDT(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -116,9 +133,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.RegisterRolesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForRegisteringAndSettingRoles(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -138,9 +159,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.BurnRoleGloballyInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingBurnRoleGlobally(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -160,9 +185,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.BurnRoleGloballyInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUnsettingBurnRoleGlobally(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -182,9 +211,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.FungibleSpecialRoleInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnFungibleToken(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -204,12 +237,16 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.SemiFungibleSpecialRoleInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnSemiFungibleToken( sender.address, options, ); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -229,12 +266,16 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.SpecialRoleInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnNonFungibleToken( sender.address, options, ); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -254,9 +295,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.MintInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForCreatingNFT(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -276,9 +321,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.PausingInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForPausing(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -298,9 +347,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.PausingInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUnpausing(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -320,9 +373,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.ManagementInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForFreezing(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -342,9 +399,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.ManagementInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUnfreezing(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -364,9 +425,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.ManagementInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForWiping(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -386,9 +451,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.LocalMintInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForLocalMint(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -408,9 +477,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.LocalBurnInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForLocalBurning(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -430,9 +503,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.UpdateAttributesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUpdatingAttributes(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -452,9 +529,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.UpdateQuantityInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForAddingQuantity(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -474,9 +555,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.UpdateQuantityInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForBurningQuantity(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -496,9 +581,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.ModifyRoyaltiesInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForModifyingRoyalties(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -518,9 +607,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.SetNewUriInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForSettingNewUris(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -540,9 +633,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.SetNewUriInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -562,9 +659,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.SetNewUriInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -584,9 +685,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.SetNewUriInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForMetadataRecreate(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -606,9 +711,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.SetNewUriInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForChangingTokenToDynamic(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -628,9 +737,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.UpdateTokenIDInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForUpdatingTokenId(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -646,9 +759,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.RegisteringDynamicTokenInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForRegisteringDynamicToken(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -668,9 +785,13 @@ export class TokenManagementController { sender: IAccount, nonce: bigint, options: resources.RegisteringDynamicTokenInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForRegisteringDynamicAndSettingRoles(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index cb9316be0..117ce1b62 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -1,4 +1,5 @@ import { IAccount } from "../accounts/interfaces"; +import { Address } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; @@ -18,9 +19,13 @@ export class TransfersController { sender: IAccount, nonce: bigint, options: resources.NativeTokenTransferInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForNativeTokenTransfer(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -31,9 +36,13 @@ export class TransfersController { sender: IAccount, nonce: bigint, options: resources.CustomTokenTransferInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForESDTTokenTransfer(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -44,9 +53,13 @@ export class TransfersController { sender: IAccount, nonce: bigint, options: resources.CreateTransferTransactionInput, + guardian: Address = Address.empty(), + relayer: Address = Address.empty() ): Promise { const transaction = this.factory.createTransactionForTransfer(sender.address, options); + transaction.guardian = guardian; + transaction.relayer = relayer; transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); From cbf14be7a714a5d924351ff6d525e6cd79bd272d Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 24 Feb 2025 15:32:50 +0200 Subject: [PATCH 174/214] Apply formatters --- src/accountManagement/accountController.ts | 18 ++++-- src/delegation/delegationController.ts | 39 ++++++------ src/entrypoints/entrypoints.spec.ts | 22 ++----- src/networkProviders/config.ts | 8 +-- src/networkProviders/networkProviderConfig.ts | 2 +- src/networkProviders/serialization.spec.ts | 3 +- src/smartContracts/smartContractController.ts | 6 +- .../tokenManagementController.ts | 60 +++++++++---------- src/transfers/transfersControllers.ts | 6 +- 9 files changed, 78 insertions(+), 86 deletions(-) diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index 89a353257..128350dd6 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -22,7 +22,7 @@ export class AccountController { nonce: bigint, options: SaveKeyValueInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSavingKeyValue(sender.address, options); @@ -39,7 +39,7 @@ export class AccountController { nonce: bigint, options: SetGuardianInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingGuardian(sender.address, options); @@ -51,9 +51,12 @@ export class AccountController { return transaction; } - async createTransactionForGuardingAccount(sender: IAccount, nonce: bigint, + async createTransactionForGuardingAccount( + sender: IAccount, + nonce: bigint, guardian: Address = Address.empty(), - relayer: Address = Address.empty()): Promise { + relayer: Address = Address.empty(), + ): Promise { const transaction = this.factory.createTransactionForGuardingAccount(sender.address); transaction.guardian = guardian; @@ -64,9 +67,12 @@ export class AccountController { return transaction; } - async createTransactionForUnguardingAccount(sender: IAccount, nonce: bigint, + async createTransactionForUnguardingAccount( + sender: IAccount, + nonce: bigint, guardian: Address = Address.empty(), - relayer: Address = Address.empty()): Promise { + relayer: Address = Address.empty(), + ): Promise { const transaction = this.factory.createTransactionForUnguardingAccount(sender.address); transaction.guardian = guardian; diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index c5c0ac660..fc8555e24 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -30,7 +30,7 @@ export class DelegationController { nonce: bigint, options: resources.NewDelegationContractInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForNewDelegationContract(sender.address, options); @@ -56,7 +56,7 @@ export class DelegationController { nonce: bigint, options: resources.AddNodesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForAddingNodes(sender.address, options); @@ -73,7 +73,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageNodesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForRemovingNodes(sender.address, options); @@ -90,7 +90,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageNodesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForStakingNodes(sender.address, options); @@ -107,7 +107,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageNodesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUnbondingNodes(sender.address, options); @@ -124,7 +124,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageNodesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUnstakingNodes(sender.address, options); @@ -141,7 +141,7 @@ export class DelegationController { nonce: bigint, options: resources.UnjailingNodesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUnjailingNodes(sender.address, options); @@ -158,7 +158,7 @@ export class DelegationController { nonce: bigint, options: resources.ChangeServiceFee, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForChangingServiceFee(sender.address, options); @@ -175,7 +175,7 @@ export class DelegationController { nonce: bigint, options: resources.ModifyDelegationCapInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForModifyingDelegationCap(sender.address, options); @@ -192,7 +192,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageDelegationContractInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingAutomaticActivation(sender.address, options); @@ -209,7 +209,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageDelegationContractInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUnsettingAutomaticActivation(sender.address, options); @@ -226,7 +226,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageDelegationContractInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingCapCheckOnRedelegateRewards( sender.address, @@ -246,7 +246,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageDelegationContractInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUnsettingCapCheckOnRedelegateRewards( sender.address, @@ -266,7 +266,7 @@ export class DelegationController { nonce: bigint, options: resources.SetContractMetadataInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingMetadata(sender.address, options); @@ -283,7 +283,7 @@ export class DelegationController { nonce: bigint, options: resources.DelegateActionsInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForDelegating(sender.address, options); @@ -300,8 +300,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageDelegationContractInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() - + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForClaimingRewards(sender.address, options); @@ -318,7 +317,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageDelegationContractInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForRedelegatingRewards(sender.address, options); @@ -335,7 +334,7 @@ export class DelegationController { nonce: bigint, options: resources.DelegateActionsInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUndelegating(sender.address, options); @@ -352,7 +351,7 @@ export class DelegationController { nonce: bigint, options: resources.ManageDelegationContractInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForWithdrawing(sender.address, options); diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 87489ec09..6b65ee610 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -9,7 +9,7 @@ import { DevnetEntrypoint } from "./entrypoints"; describe("TestEntrypoint", () => { const entrypoint = new DevnetEntrypoint(); - before(async function () { }); + before(async function () {}); it("native transfer", async () => { const controller = entrypoint.createTransfersController(); @@ -48,25 +48,13 @@ describe("TestEntrypoint", () => { data: Buffer.from("hello"), }, grace.address, - grace.address - ); - assert.deepEqual( - transaction.guardian, - grace.address, - ); - assert.deepEqual( - transaction.relayer, grace.address, ); - assert.deepEqual( - transaction.guardianSignature, - new Uint8Array(), - ); + assert.deepEqual(transaction.guardian, grace.address); + assert.deepEqual(transaction.relayer, grace.address); + assert.deepEqual(transaction.guardianSignature, new Uint8Array()); - assert.deepEqual( - transaction.relayerSignature, - new Uint8Array(), - ); + assert.deepEqual(transaction.relayerSignature, new Uint8Array()); }); it("contract flow", async function () { diff --git a/src/networkProviders/config.ts b/src/networkProviders/config.ts index 8239bfda9..c43ac48bd 100644 --- a/src/networkProviders/config.ts +++ b/src/networkProviders/config.ts @@ -1,6 +1,6 @@ import { IPagination } from "./interface"; -const JSONbig = require("json-bigint")({ constructorAction: 'ignore' }); +const JSONbig = require("json-bigint")({ constructorAction: "ignore" }); export const defaultAxiosConfig = { timeout: 5000, @@ -8,11 +8,11 @@ export const defaultAxiosConfig = { transformResponse: [ function (data: any) { return JSONbig.parse(data); - } - ] + }, + ], }; export const defaultPagination: IPagination = { from: 0, - size: 100 + size: 100, }; diff --git a/src/networkProviders/networkProviderConfig.ts b/src/networkProviders/networkProviderConfig.ts index b66bffbcc..6d1260e43 100644 --- a/src/networkProviders/networkProviderConfig.ts +++ b/src/networkProviders/networkProviderConfig.ts @@ -1,4 +1,4 @@ -import { AxiosRequestConfig } from 'axios'; +import { AxiosRequestConfig } from "axios"; export interface NetworkProviderConfig extends AxiosRequestConfig { clientName?: string; diff --git a/src/networkProviders/serialization.spec.ts b/src/networkProviders/serialization.spec.ts index 6ffc83096..217a0e071 100644 --- a/src/networkProviders/serialization.spec.ts +++ b/src/networkProviders/serialization.spec.ts @@ -8,9 +8,8 @@ describe("test JSON serialization", function () { }); it("should deserialize", async function () { - const JSONbig = require("json-bigint")({ constructorAction: 'ignore' }); + const JSONbig = require("json-bigint")({ constructorAction: "ignore" }); const data = `{"Costum":{"foo_constructor":1}}`; JSONbig.parse(data); }); }); - diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index 3408a5353..253ff3405 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -38,7 +38,7 @@ export class SmartContractController { nonce: bigint, options: resources.ContractDeployInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForDeploy(sender.address, options); @@ -64,7 +64,7 @@ export class SmartContractController { nonce: bigint, options: resources.ContractUpgradeInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUpgrade(sender.address, options); @@ -81,7 +81,7 @@ export class SmartContractController { nonce: bigint, options: resources.ContractExecuteInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForExecute(sender.address, options); diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index 2e5789f54..63d32b01d 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -30,7 +30,7 @@ export class TokenManagementController { nonce: bigint, options: resources.IssueFungibleInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForIssuingFungible(sender.address, options); @@ -56,7 +56,7 @@ export class TokenManagementController { nonce: bigint, options: resources.IssueSemiFungibleInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForIssuingSemiFungible(sender.address, options); @@ -82,7 +82,7 @@ export class TokenManagementController { nonce: bigint, options: resources.IssueNonFungibleInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForIssuingNonFungible(sender.address, options); @@ -108,7 +108,7 @@ export class TokenManagementController { nonce: bigint, options: resources.RegisterMetaESDTInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForRegisteringMetaESDT(sender.address, options); @@ -134,7 +134,7 @@ export class TokenManagementController { nonce: bigint, options: resources.RegisterRolesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForRegisteringAndSettingRoles(sender.address, options); @@ -160,7 +160,7 @@ export class TokenManagementController { nonce: bigint, options: resources.BurnRoleGloballyInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingBurnRoleGlobally(sender.address, options); @@ -186,7 +186,7 @@ export class TokenManagementController { nonce: bigint, options: resources.BurnRoleGloballyInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUnsettingBurnRoleGlobally(sender.address, options); @@ -212,7 +212,7 @@ export class TokenManagementController { nonce: bigint, options: resources.FungibleSpecialRoleInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnFungibleToken(sender.address, options); @@ -238,7 +238,7 @@ export class TokenManagementController { nonce: bigint, options: resources.SemiFungibleSpecialRoleInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnSemiFungibleToken( sender.address, @@ -267,7 +267,7 @@ export class TokenManagementController { nonce: bigint, options: resources.SpecialRoleInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnNonFungibleToken( sender.address, @@ -296,7 +296,7 @@ export class TokenManagementController { nonce: bigint, options: resources.MintInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForCreatingNFT(sender.address, options); @@ -322,7 +322,7 @@ export class TokenManagementController { nonce: bigint, options: resources.PausingInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForPausing(sender.address, options); @@ -348,7 +348,7 @@ export class TokenManagementController { nonce: bigint, options: resources.PausingInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUnpausing(sender.address, options); @@ -374,7 +374,7 @@ export class TokenManagementController { nonce: bigint, options: resources.ManagementInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForFreezing(sender.address, options); @@ -400,7 +400,7 @@ export class TokenManagementController { nonce: bigint, options: resources.ManagementInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUnfreezing(sender.address, options); @@ -426,7 +426,7 @@ export class TokenManagementController { nonce: bigint, options: resources.ManagementInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForWiping(sender.address, options); @@ -452,7 +452,7 @@ export class TokenManagementController { nonce: bigint, options: resources.LocalMintInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForLocalMint(sender.address, options); @@ -478,7 +478,7 @@ export class TokenManagementController { nonce: bigint, options: resources.LocalBurnInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForLocalBurning(sender.address, options); @@ -504,7 +504,7 @@ export class TokenManagementController { nonce: bigint, options: resources.UpdateAttributesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUpdatingAttributes(sender.address, options); @@ -530,7 +530,7 @@ export class TokenManagementController { nonce: bigint, options: resources.UpdateQuantityInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForAddingQuantity(sender.address, options); @@ -556,7 +556,7 @@ export class TokenManagementController { nonce: bigint, options: resources.UpdateQuantityInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForBurningQuantity(sender.address, options); @@ -582,7 +582,7 @@ export class TokenManagementController { nonce: bigint, options: resources.ModifyRoyaltiesInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForModifyingRoyalties(sender.address, options); @@ -608,7 +608,7 @@ export class TokenManagementController { nonce: bigint, options: resources.SetNewUriInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForSettingNewUris(sender.address, options); @@ -634,7 +634,7 @@ export class TokenManagementController { nonce: bigint, options: resources.SetNewUriInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); @@ -660,7 +660,7 @@ export class TokenManagementController { nonce: bigint, options: resources.SetNewUriInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); @@ -686,7 +686,7 @@ export class TokenManagementController { nonce: bigint, options: resources.SetNewUriInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForMetadataRecreate(sender.address, options); @@ -712,7 +712,7 @@ export class TokenManagementController { nonce: bigint, options: resources.SetNewUriInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForChangingTokenToDynamic(sender.address, options); @@ -738,7 +738,7 @@ export class TokenManagementController { nonce: bigint, options: resources.UpdateTokenIDInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForUpdatingTokenId(sender.address, options); @@ -760,7 +760,7 @@ export class TokenManagementController { nonce: bigint, options: resources.RegisteringDynamicTokenInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForRegisteringDynamicToken(sender.address, options); @@ -786,7 +786,7 @@ export class TokenManagementController { nonce: bigint, options: resources.RegisteringDynamicTokenInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForRegisteringDynamicAndSettingRoles(sender.address, options); diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index 117ce1b62..4d752871c 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -20,7 +20,7 @@ export class TransfersController { nonce: bigint, options: resources.NativeTokenTransferInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForNativeTokenTransfer(sender.address, options); @@ -37,7 +37,7 @@ export class TransfersController { nonce: bigint, options: resources.CustomTokenTransferInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForESDTTokenTransfer(sender.address, options); @@ -54,7 +54,7 @@ export class TransfersController { nonce: bigint, options: resources.CreateTransferTransactionInput, guardian: Address = Address.empty(), - relayer: Address = Address.empty() + relayer: Address = Address.empty(), ): Promise { const transaction = this.factory.createTransactionForTransfer(sender.address, options); From a9c5847e623f5a8a006d0020a42262e71e4e293d Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 24 Feb 2025 16:27:26 +0200 Subject: [PATCH 175/214] Increase timeout --- src/entrypoints/entrypoints.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 6b65ee610..8905552b2 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -58,7 +58,7 @@ describe("TestEntrypoint", () => { }); it("contract flow", async function () { - this.timeout(30000); + this.timeout(40000); const abi = await loadAbiRegistry("src/testdata/adder.abi.json"); const filePath = path.join("src", "testdata", "testwallets", "alice.pem"); const sender = await Account.newFromPem(filePath); From 077e9907a7ec2848dec0695a026b28e6124b66eb Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 25 Feb 2025 11:18:00 +0200 Subject: [PATCH 176/214] Update controllers input parameters --- src/accountManagement/accountController.ts | 31 +-- src/delegation/delegationController.ts | 152 +++++------ src/entrypoints/entrypoints.spec.ts | 4 +- src/smartContracts/smartContractController.ts | 24 +- .../tokenManagementController.ts | 240 +++++++----------- src/transfers/transfersControllers.ts | 24 +- 6 files changed, 179 insertions(+), 296 deletions(-) diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index 128350dd6..1c1950020 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -20,14 +20,12 @@ export class AccountController { async createTransactionForSavingKeyValue( sender: IAccount, nonce: bigint, - options: SaveKeyValueInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: SaveKeyValueInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSavingKeyValue(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -37,14 +35,12 @@ export class AccountController { async createTransactionForSettingGuardian( sender: IAccount, nonce: bigint, - options: SetGuardianInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: SetGuardianInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingGuardian(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -54,13 +50,11 @@ export class AccountController { async createTransactionForGuardingAccount( sender: IAccount, nonce: bigint, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForGuardingAccount(sender.address); - - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -70,13 +64,12 @@ export class AccountController { async createTransactionForUnguardingAccount( sender: IAccount, nonce: bigint, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnguardingAccount(sender.address); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index fc8555e24..f0c0f0f3e 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -28,14 +28,12 @@ export class DelegationController { async createTransactionForNewDelegationContract( sender: IAccount, nonce: bigint, - options: resources.NewDelegationContractInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.NewDelegationContractInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForNewDelegationContract(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -54,14 +52,12 @@ export class DelegationController { async createTransactionForAddingNodes( sender: IAccount, nonce: bigint, - options: resources.AddNodesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.AddNodesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForAddingNodes(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -71,14 +67,12 @@ export class DelegationController { async createTransactionForRemovingNodes( sender: IAccount, nonce: bigint, - options: resources.ManageNodesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageNodesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForRemovingNodes(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -88,14 +82,12 @@ export class DelegationController { async createTransactionForStakingNodes( sender: IAccount, nonce: bigint, - options: resources.ManageNodesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageNodesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForStakingNodes(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -105,14 +97,12 @@ export class DelegationController { async createTransactionForUnbondingNodes( sender: IAccount, nonce: bigint, - options: resources.ManageNodesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageNodesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnbondingNodes(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -122,14 +112,12 @@ export class DelegationController { async createTransactionForUnstakingNodes( sender: IAccount, nonce: bigint, - options: resources.ManageNodesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageNodesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnstakingNodes(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -139,14 +127,12 @@ export class DelegationController { async createTransactionForUnjailingNodes( sender: IAccount, nonce: bigint, - options: resources.UnjailingNodesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.UnjailingNodesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnjailingNodes(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -156,14 +142,12 @@ export class DelegationController { async createTransactionForChangingServiceFee( sender: IAccount, nonce: bigint, - options: resources.ChangeServiceFee, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ChangeServiceFee & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForChangingServiceFee(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -173,14 +157,12 @@ export class DelegationController { async createTransactionForModifyingDelegationCap( sender: IAccount, nonce: bigint, - options: resources.ModifyDelegationCapInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ModifyDelegationCapInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForModifyingDelegationCap(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -190,14 +172,12 @@ export class DelegationController { async createTransactionForSettingAutomaticActivation( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingAutomaticActivation(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -207,14 +187,12 @@ export class DelegationController { async createTransactionForUnsettingAutomaticActivation( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnsettingAutomaticActivation(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -224,17 +202,15 @@ export class DelegationController { async createTransactionForSettingCapCheckOnRedelegateRewards( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingCapCheckOnRedelegateRewards( sender.address, options, ); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -244,17 +220,15 @@ export class DelegationController { async createTransactionForUnsettingCapCheckOnRedelegateRewards( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnsettingCapCheckOnRedelegateRewards( sender.address, options, ); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -264,14 +238,12 @@ export class DelegationController { async createTransactionForSettingMetadata( sender: IAccount, nonce: bigint, - options: resources.SetContractMetadataInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.SetContractMetadataInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingMetadata(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -281,14 +253,12 @@ export class DelegationController { async createTransactionForDelegating( sender: IAccount, nonce: bigint, - options: resources.DelegateActionsInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.DelegateActionsInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForDelegating(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -298,14 +268,12 @@ export class DelegationController { async createTransactionForClaimingRewards( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForClaimingRewards(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -315,14 +283,12 @@ export class DelegationController { async createTransactionForRedelegatingRewards( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForRedelegatingRewards(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -332,14 +298,12 @@ export class DelegationController { async createTransactionForUndelegating( sender: IAccount, nonce: bigint, - options: resources.DelegateActionsInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.DelegateActionsInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUndelegating(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -349,15 +313,13 @@ export class DelegationController { async createTransactionForWithdrawing( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForWithdrawing(sender.address, options); transaction.nonce = nonce; - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 8905552b2..11a245fb2 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -46,9 +46,9 @@ describe("TestEntrypoint", () => { receiver: sender.address, nativeAmount: BigInt(0), data: Buffer.from("hello"), + guardian: grace.address, + relayer: grace.address, }, - grace.address, - grace.address, ); assert.deepEqual(transaction.guardian, grace.address); assert.deepEqual(transaction.relayer, grace.address); diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index 253ff3405..5a7be445d 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -36,14 +36,12 @@ export class SmartContractController { async createTransactionForDeploy( sender: IAccount, nonce: bigint, - options: resources.ContractDeployInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ContractDeployInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForDeploy(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -62,14 +60,12 @@ export class SmartContractController { async createTransactionForUpgrade( sender: IAccount, nonce: bigint, - options: resources.ContractUpgradeInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ContractUpgradeInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUpgrade(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -79,14 +75,12 @@ export class SmartContractController { async createTransactionForExecute( sender: IAccount, nonce: bigint, - options: resources.ContractExecuteInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ContractExecuteInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForExecute(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index 63d32b01d..e63821477 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -28,14 +28,12 @@ export class TokenManagementController { async createTransactionForIssuingFungible( sender: IAccount, nonce: bigint, - options: resources.IssueFungibleInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.IssueFungibleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForIssuingFungible(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -54,14 +52,12 @@ export class TokenManagementController { async createTransactionForIssuingSemiFungible( sender: IAccount, nonce: bigint, - options: resources.IssueSemiFungibleInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.IssueSemiFungibleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForIssuingSemiFungible(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -80,14 +76,12 @@ export class TokenManagementController { async createTransactionForIssuingNonFungible( sender: IAccount, nonce: bigint, - options: resources.IssueNonFungibleInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.IssueNonFungibleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForIssuingNonFungible(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -106,14 +100,12 @@ export class TokenManagementController { async createTransactionForRegisteringMetaEsdt( sender: IAccount, nonce: bigint, - options: resources.RegisterMetaESDTInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.RegisterMetaESDTInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForRegisteringMetaESDT(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -132,14 +124,12 @@ export class TokenManagementController { async createTransactionForRegisteringAndSettingRoles( sender: IAccount, nonce: bigint, - options: resources.RegisterRolesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.RegisterRolesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForRegisteringAndSettingRoles(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -158,14 +148,12 @@ export class TokenManagementController { async createTransactionForSetBurnRoleGlobally( sender: IAccount, nonce: bigint, - options: resources.BurnRoleGloballyInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.BurnRoleGloballyInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingBurnRoleGlobally(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -184,14 +172,12 @@ export class TokenManagementController { async createTransactionForUnsettingBurnRoleGlobally( sender: IAccount, nonce: bigint, - options: resources.BurnRoleGloballyInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.BurnRoleGloballyInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnsettingBurnRoleGlobally(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -210,14 +196,12 @@ export class TokenManagementController { async createTransactionForSettingSpecialRoleOnFungibleToken( sender: IAccount, nonce: bigint, - options: resources.FungibleSpecialRoleInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.FungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnFungibleToken(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -236,17 +220,15 @@ export class TokenManagementController { async createTransactionForSettingSpecialRoleOnSemiFungibleToken( sender: IAccount, nonce: bigint, - options: resources.SemiFungibleSpecialRoleInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.SemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnSemiFungibleToken( sender.address, options, ); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -265,17 +247,15 @@ export class TokenManagementController { async createTransactionForSettingSpecialRoleOnNonFungibleToken( sender: IAccount, nonce: bigint, - options: resources.SpecialRoleInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.SpecialRoleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnNonFungibleToken( sender.address, options, ); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -294,14 +274,12 @@ export class TokenManagementController { async createTransactionForCreatingNft( sender: IAccount, nonce: bigint, - options: resources.MintInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.MintInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForCreatingNFT(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -320,14 +298,12 @@ export class TokenManagementController { async createTransactionForPausing( sender: IAccount, nonce: bigint, - options: resources.PausingInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.PausingInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForPausing(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -346,14 +322,12 @@ export class TokenManagementController { async createTransactionForUnpausing( sender: IAccount, nonce: bigint, - options: resources.PausingInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.PausingInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnpausing(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -372,14 +346,12 @@ export class TokenManagementController { async createTransactionForFreezing( sender: IAccount, nonce: bigint, - options: resources.ManagementInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManagementInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForFreezing(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -398,14 +370,12 @@ export class TokenManagementController { async createTransactionForUnFreezing( sender: IAccount, nonce: bigint, - options: resources.ManagementInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManagementInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnfreezing(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -424,14 +394,12 @@ export class TokenManagementController { async createTransactionForWiping( sender: IAccount, nonce: bigint, - options: resources.ManagementInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ManagementInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForWiping(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -450,14 +418,12 @@ export class TokenManagementController { async createTransactionForLocaMinting( sender: IAccount, nonce: bigint, - options: resources.LocalMintInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.LocalMintInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForLocalMint(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -476,14 +442,12 @@ export class TokenManagementController { async createTransactionForLocalBurning( sender: IAccount, nonce: bigint, - options: resources.LocalBurnInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.LocalBurnInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForLocalBurning(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -502,14 +466,12 @@ export class TokenManagementController { async createTransactionForUpdatingAttributes( sender: IAccount, nonce: bigint, - options: resources.UpdateAttributesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.UpdateAttributesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUpdatingAttributes(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -528,14 +490,12 @@ export class TokenManagementController { async createTransactionForAddingQuantity( sender: IAccount, nonce: bigint, - options: resources.UpdateQuantityInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.UpdateQuantityInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForAddingQuantity(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -554,14 +514,12 @@ export class TokenManagementController { async createTransactionForBurningQuantity( sender: IAccount, nonce: bigint, - options: resources.UpdateQuantityInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.UpdateQuantityInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForBurningQuantity(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -580,14 +538,12 @@ export class TokenManagementController { async createTransactionForModifyingRoyalties( sender: IAccount, nonce: bigint, - options: resources.ModifyRoyaltiesInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.ModifyRoyaltiesInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForModifyingRoyalties(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -606,14 +562,12 @@ export class TokenManagementController { async createTransactionForSettingNewUris( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForSettingNewUris(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -632,14 +586,12 @@ export class TokenManagementController { async createTransactionForModifyingCreator( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -658,14 +610,12 @@ export class TokenManagementController { async createTransactionForUpdatingMetadata( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -684,14 +634,12 @@ export class TokenManagementController { async createTransactionForMetadataRecreate( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForMetadataRecreate(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -710,14 +658,12 @@ export class TokenManagementController { async createTransactionForChangingTokenToDynamic( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForChangingTokenToDynamic(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -736,14 +682,12 @@ export class TokenManagementController { async createTransactionForUpdatingTokenId( sender: IAccount, nonce: bigint, - options: resources.UpdateTokenIDInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.UpdateTokenIDInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUpdatingTokenId(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -758,14 +702,12 @@ export class TokenManagementController { async createTransactionForRegisteringDynamicToken( sender: IAccount, nonce: bigint, - options: resources.RegisteringDynamicTokenInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.RegisteringDynamicTokenInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForRegisteringDynamicToken(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -784,14 +726,12 @@ export class TokenManagementController { async createTransactionForRegisteringDynamicTokenAndSettingRoles( sender: IAccount, nonce: bigint, - options: resources.RegisteringDynamicTokenInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.RegisteringDynamicTokenInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForRegisteringDynamicAndSettingRoles(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index 4d752871c..55f5d446d 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -18,14 +18,12 @@ export class TransfersController { async createTransactionForNativeTokenTransfer( sender: IAccount, nonce: bigint, - options: resources.NativeTokenTransferInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.NativeTokenTransferInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForNativeTokenTransfer(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -35,14 +33,12 @@ export class TransfersController { async createTransactionForEsdtTokenTransfer( sender: IAccount, nonce: bigint, - options: resources.CustomTokenTransferInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.CustomTokenTransferInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForESDTTokenTransfer(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -52,14 +48,12 @@ export class TransfersController { async createTransactionForTransfer( sender: IAccount, nonce: bigint, - options: resources.CreateTransferTransactionInput, - guardian: Address = Address.empty(), - relayer: Address = Address.empty(), + options: resources.CreateTransferTransactionInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForTransfer(sender.address, options); - transaction.guardian = guardian; - transaction.relayer = relayer; + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); From b79a40508861b163d682e95c41b3b1a30086b86f Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 25 Feb 2025 11:41:25 +0200 Subject: [PATCH 177/214] Clean up transaction watcher --- src/core/transactionWatcher.ts | 52 +++++++--------------------------- 1 file changed, 10 insertions(+), 42 deletions(-) diff --git a/src/core/transactionWatcher.ts b/src/core/transactionWatcher.ts index 3442b117b..b53b77532 100644 --- a/src/core/transactionWatcher.ts +++ b/src/core/transactionWatcher.ts @@ -1,5 +1,4 @@ import { AsyncTimer } from "./asyncTimer"; -import { HEX_TRANSACTION_HASH_LENGTH } from "./constants"; import { Err, ErrExpectedTransactionEventsNotFound, @@ -14,13 +13,6 @@ import { TransactionStatus } from "./transactionStatus"; export type PredicateIsAwaitedStatus = (status: TransactionStatus) => boolean; -/** - * Internal interface: a transaction, as seen from the perspective of a {@link TransactionWatcher}. - */ -interface ITransaction { - getHash(): { hex(): string }; -} - /** * TransactionWatcher allows one to continuously watch (monitor), by means of polling, the status of a given transaction. */ @@ -64,11 +56,10 @@ export class TransactionWatcher { * Waits until the transaction reaches the "pending" status. * @param txHash The hex-encoded transaction hash */ - public async awaitPending(transactionOrTxHash: ITransaction | string): Promise { + public async awaitPending(txHash: string): Promise { const isPending = (transaction: TransactionOnNetwork) => transaction.status.isPending(); const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); + return await this.fetcher.getTransaction(txHash); }; const errorProvider = () => new ErrExpectedTransactionStatusNotReached(); @@ -79,24 +70,20 @@ export class TransactionWatcher { * Waits until the transaction is completely processed. * @param txHash The hex-encoded transaction hash */ - public async awaitCompleted(transactionOrTxHash: ITransaction | string): Promise { + public async awaitCompleted(txhash: string): Promise { const isCompleted = (transactionOnNetwork: TransactionOnNetwork) => { return transactionOnNetwork.status.isCompleted(); }; const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); + return await this.fetcher.getTransaction(txhash); }; const errorProvider = () => new ErrExpectedTransactionStatusNotReached(); return this.awaitConditionally(isCompleted, doFetch, errorProvider); } - public async awaitAllEvents( - transactionOrTxHash: ITransaction | string, - events: string[], - ): Promise { + public async awaitAllEvents(txHash: string, events: string[]): Promise { const foundAllEvents = (transactionOnNetwork: TransactionOnNetwork) => { const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map( (event) => event.identifier, @@ -106,18 +93,14 @@ export class TransactionWatcher { }; const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); + return await this.fetcher.getTransaction(txHash); }; const errorProvider = () => new ErrExpectedTransactionEventsNotFound(); return this.awaitConditionally(foundAllEvents, doFetch, errorProvider); } - public async awaitAnyEvent( - transactionOrTxHash: ITransaction | string, - events: string[], - ): Promise { + public async awaitAnyEvent(txHash: string, events: string[]): Promise { const foundAnyEvent = (transactionOnNetwork: TransactionOnNetwork) => { const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map( (event) => event.identifier, @@ -127,8 +110,7 @@ export class TransactionWatcher { }; const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); + return await this.fetcher.getTransaction(txHash); }; const errorProvider = () => new ErrExpectedTransactionEventsNotFound(); @@ -136,31 +118,17 @@ export class TransactionWatcher { } public async awaitOnCondition( - transactionOrTxHash: ITransaction | string, + txHash: string, condition: (data: TransactionOnNetwork) => boolean, ): Promise { const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); + return await this.fetcher.getTransaction(txHash); }; const errorProvider = () => new ErrExpectedTransactionStatusNotReached(); return this.awaitConditionally(condition, doFetch, errorProvider); } - private transactionOrTxHashToTxHash(transactionOrTxHash: ITransaction | string): string { - const hash = - typeof transactionOrTxHash === "string" ? transactionOrTxHash : transactionOrTxHash.getHash().hex(); - - if (hash.length !== HEX_TRANSACTION_HASH_LENGTH) { - throw new Err( - `Invalid transaction hash length. The length of a hex encoded hash should be ${HEX_TRANSACTION_HASH_LENGTH}.`, - ); - } - - return hash; - } - protected async awaitConditionally( isSatisfied: (data: TData) => boolean, doFetch: () => Promise, From 7eb2cb9216adb53a08250c51b6b5f87f70ebc89e Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 25 Feb 2025 11:45:48 +0200 Subject: [PATCH 178/214] Fix contract flow test --- src/entrypoints/entrypoints.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 11a245fb2..84dda3135 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -6,7 +6,7 @@ import { Address } from "../core"; import { loadAbiRegistry } from "../testutils"; import { DevnetEntrypoint } from "./entrypoints"; -describe("TestEntrypoint", () => { +describe("TestEntrypoint", function () { const entrypoint = new DevnetEntrypoint(); before(async function () {}); @@ -58,7 +58,7 @@ describe("TestEntrypoint", () => { }); it("contract flow", async function () { - this.timeout(40000); + this.timeout(30000); const abi = await loadAbiRegistry("src/testdata/adder.abi.json"); const filePath = path.join("src", "testdata", "testwallets", "alice.pem"); const sender = await Account.newFromPem(filePath); From cfa32ee50ba496b87c123cba9707368a67435572 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 25 Feb 2025 11:56:34 +0200 Subject: [PATCH 179/214] Change wallet for contract deploy --- src/entrypoints/entrypoints.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 84dda3135..742bb3cd8 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -60,7 +60,7 @@ describe("TestEntrypoint", function () { it("contract flow", async function () { this.timeout(30000); const abi = await loadAbiRegistry("src/testdata/adder.abi.json"); - const filePath = path.join("src", "testdata", "testwallets", "alice.pem"); + const filePath = path.join("src", "testdata", "testwallets", "grace.pem"); const sender = await Account.newFromPem(filePath); sender.nonce = await entrypoint.recallAccountNonce(sender.address); From 3c1f03d853d608dd9917164c631ab8c474b0a819 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 25 Feb 2025 13:15:58 +0200 Subject: [PATCH 180/214] Fix tests --- src/abi/interaction.spec.ts | 11 +++----- src/abi/smartContract.local.net.spec.ts | 27 +++++++------------ src/abi/smartContract.spec.ts | 26 +++++++++--------- .../smartContractResults.local.net.spec.ts | 20 +++++++------- src/core/transactionWatcher.ts | 6 ++--- src/testutils/utils.ts | 6 ----- 6 files changed, 40 insertions(+), 56 deletions(-) diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index d00d31b18..40a3c361b 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -6,7 +6,7 @@ import { SmartContractQueryResponse } from "../core/smartContractQuery"; import { Token, TokenTransfer } from "../core/tokens"; import { Transaction } from "../core/transaction"; import { SmartContractController } from "../smartContracts"; -import { loadAbiRegistry, MockNetworkProvider, setupUnitTestWatcherTimeouts } from "../testutils"; +import { loadAbiRegistry, MockNetworkProvider } from "../testutils"; import { getTestWalletsPath } from "../testutils/utils"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; @@ -204,8 +204,7 @@ describe("test smart contract interactor", function () { }); it("should interact with 'answer'", async function () { - setupUnitTestWatcherTimeouts(); - + this.timeout(30000); let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry }); @@ -270,8 +269,7 @@ describe("test smart contract interactor", function () { }); it("should interact with 'counter'", async function () { - setupUnitTestWatcherTimeouts(); - + this.timeout(30000); let abi = await loadAbiRegistry("src/testdata/counter.abi.json"); let contract = new SmartContract({ address: dummyAddress, abi: abi }); let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abi }); @@ -339,8 +337,7 @@ describe("test smart contract interactor", function () { }); it("should interact with 'lottery-esdt'", async function () { - setupUnitTestWatcherTimeouts(); - + this.timeout(30000); let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry }); diff --git a/src/abi/smartContract.local.net.spec.ts b/src/abi/smartContract.local.net.spec.ts index 24482aa2b..9e97bbfb6 100644 --- a/src/abi/smartContract.local.net.spec.ts +++ b/src/abi/smartContract.local.net.spec.ts @@ -34,20 +34,23 @@ describe("test on local testnet", function () { bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); carol = await Account.newFromPem(`${getTestWalletsPath()}/carol.pem`); - watcher = new TransactionWatcher({ - getTransaction: async (hash: string) => { - return await provider.getTransaction(hash); + watcher = new TransactionWatcher( + { + getTransaction: async (hash: string) => { + return await provider.getTransaction(hash); + }, }, - }); + { + pollingIntervalMilliseconds: 5000, + timeoutMilliseconds: 50000, + }, + ); parser = new SmartContractTransactionsOutcomeParser(); }); it("counter: should deploy, then simulate transactions using SmartContractTransactionsFactory", async function () { this.timeout(60000); - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - let network = await provider.getNetworkConfig(); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); @@ -121,9 +124,6 @@ describe("test on local testnet", function () { it("counter: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { this.timeout(80000); - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - let network = await provider.getNetworkConfig(); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); @@ -187,9 +187,6 @@ describe("test on local testnet", function () { it("erc20: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { this.timeout(60000); - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - let network = await provider.getNetworkConfig(); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); @@ -277,10 +274,6 @@ describe("test on local testnet", function () { it("lottery: should deploy, call and query contract using SmartContractTransactionsFactory", async function () { this.timeout(60000); - - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - let network = await provider.getNetworkConfig(); alice.nonce = (await provider.getAccount(alice.address)).nonce; diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index c53bee3e7..e2a10d45e 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -4,13 +4,7 @@ import { Address } from "../core/address"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionStatus } from "../core/transactionStatus"; import { TransactionWatcher } from "../core/transactionWatcher"; -import { - getTestWalletsPath, - MarkCompleted, - MockNetworkProvider, - setupUnitTestWatcherTimeouts, - Wait, -} from "../testutils"; +import { getTestWalletsPath, MarkCompleted, MockNetworkProvider, Wait } from "../testutils"; import { Code } from "./code"; import { ContractFunction } from "./function"; import { SmartContract } from "./smartContract"; @@ -41,8 +35,10 @@ describe("test contract", () => { }); it("should deploy", async () => { - setupUnitTestWatcherTimeouts(); - let watcher = new TransactionWatcher(provider); + let watcher = new TransactionWatcher(provider, { + pollingIntervalMilliseconds: 42, + timeoutMilliseconds: 42 * 42, + }); let contract = new SmartContract(); let deployTransaction = contract.deploy({ @@ -87,8 +83,10 @@ describe("test contract", () => { }); it("should call", async () => { - setupUnitTestWatcherTimeouts(); - let watcher = new TransactionWatcher(provider); + let watcher = new TransactionWatcher(provider, { + pollingIntervalMilliseconds: 42, + timeoutMilliseconds: 42 * 42, + }); let contract = new SmartContract({ address: new Address("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3"), @@ -154,8 +152,10 @@ describe("test contract", () => { }); it("should upgrade", async () => { - setupUnitTestWatcherTimeouts(); - let watcher = new TransactionWatcher(provider); + let watcher = new TransactionWatcher(provider, { + pollingIntervalMilliseconds: 42, + timeoutMilliseconds: 42 * 42, + }); let contract = new SmartContract(); contract.setAddress(Address.newFromBech32("erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q")); diff --git a/src/abi/smartContractResults.local.net.spec.ts b/src/abi/smartContractResults.local.net.spec.ts index e8a3411ef..b66dbbd51 100644 --- a/src/abi/smartContractResults.local.net.spec.ts +++ b/src/abi/smartContractResults.local.net.spec.ts @@ -17,11 +17,17 @@ describe("fetch transactions from local testnet", function () { before(async function () { alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); - watcher = new TransactionWatcher({ - getTransaction: async (hash: string) => { - return await provider.getTransaction(hash); + watcher = new TransactionWatcher( + { + getTransaction: async (hash: string) => { + return await provider.getTransaction(hash); + }, }, - }); + { + pollingIntervalMilliseconds: 5000, + timeoutMilliseconds: 50000, + }, + ); parser = new SmartContractTransactionsOutcomeParser(); }); @@ -29,9 +35,6 @@ describe("fetch transactions from local testnet", function () { it("counter smart contract", async function () { this.timeout(60000); - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - let network = await provider.getNetworkConfig(); alice.nonce = (await provider.getAccount(alice.address)).nonce; @@ -78,9 +81,6 @@ describe("fetch transactions from local testnet", function () { it("interact with counter smart contract using SmartContractTransactionsFactory", async function () { this.timeout(60000); - TransactionWatcher.DefaultPollingInterval = 5000; - TransactionWatcher.DefaultTimeout = 50000; - let network = await provider.getNetworkConfig(); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); diff --git a/src/core/transactionWatcher.ts b/src/core/transactionWatcher.ts index b53b77532..08defcb89 100644 --- a/src/core/transactionWatcher.ts +++ b/src/core/transactionWatcher.ts @@ -17,9 +17,9 @@ export type PredicateIsAwaitedStatus = (status: TransactionStatus) => boolean; * TransactionWatcher allows one to continuously watch (monitor), by means of polling, the status of a given transaction. */ export class TransactionWatcher { - static DefaultPollingInterval: number = 6000; - static DefaultTimeout: number = TransactionWatcher.DefaultPollingInterval * 15; - static DefaultPatience: number = 0; + private static DefaultPollingInterval: number = 6000; + private static DefaultTimeout: number = TransactionWatcher.DefaultPollingInterval * 15; + private static DefaultPatience: number = 0; static NoopOnStatusReceived = (_: TransactionStatus) => {}; diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index e91531f5c..ce2f96c1a 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -4,7 +4,6 @@ import { resolve } from "path"; import { AbiRegistry, Code, SmartContract, TypedValue } from "../abi"; import { Account } from "../accounts"; import { Transaction } from "../core/transaction"; -import { TransactionWatcher } from "../core/transactionWatcher"; import { getAxios } from "../core/utils"; export async function prepareDeployment(obj: { @@ -81,11 +80,6 @@ export function isOnBrowserTests() { return isOnTests; } -export function setupUnitTestWatcherTimeouts() { - TransactionWatcher.DefaultPollingInterval = 42; - TransactionWatcher.DefaultTimeout = 42 * 42; -} - export function createAccountBalance(egld: number): bigint { return BigInt(egld.toString() + "0".repeat(18)); } From 592928c50054839130c157b9f6adc680ea49c4e8 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 25 Feb 2025 14:22:53 +0200 Subject: [PATCH 181/214] Fix accunt controller --- src/accountManagement/accountController.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index 1c1950020..e4cb9c455 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -50,10 +50,9 @@ export class AccountController { async createTransactionForGuardingAccount( sender: IAccount, nonce: bigint, - options: { guardian?: Address; relayer?: Address }, + options: { relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForGuardingAccount(sender.address); - transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); @@ -64,7 +63,7 @@ export class AccountController { async createTransactionForUnguardingAccount( sender: IAccount, nonce: bigint, - options: { guardian?: Address; relayer?: Address }, + options: { guardian: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnguardingAccount(sender.address); From 7324c6d3d9272fff177736c39fba7ed38f4acd57 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 25 Feb 2025 14:35:28 +0200 Subject: [PATCH 182/214] Bump version --- package-lock.json | 17 +++++++++-------- package.json | 2 +- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index 28ac6bdd1..73f49d64b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@multiversx/sdk-core", - "version": "13.17.1", + "version": "14.0.0-beta.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@multiversx/sdk-core", - "version": "13.17.1", + "version": "14.0.0-beta.0", "license": "MIT", "dependencies": { "@multiversx/sdk-transaction-decoder": "1.0.2", @@ -1779,10 +1779,11 @@ } }, "node_modules/elliptic": { - "version": "6.6.0", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.6.0.tgz", - "integrity": "sha512-dpwoQcLc/2WLQvJvLRHKZ+f9FgOdjnq11rurqwekGQygGPsYSK29OMMD2WalatiqQ+XGFDglTNixpPfI+lpaAA==", + "version": "6.6.1", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.6.1.tgz", + "integrity": "sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g==", "dev": true, + "license": "MIT", "dependencies": { "bn.js": "^4.11.9", "brorand": "^1.1.0", @@ -6586,9 +6587,9 @@ } }, "elliptic": { - "version": "6.6.0", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.6.0.tgz", - "integrity": "sha512-dpwoQcLc/2WLQvJvLRHKZ+f9FgOdjnq11rurqwekGQygGPsYSK29OMMD2WalatiqQ+XGFDglTNixpPfI+lpaAA==", + "version": "6.6.1", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.6.1.tgz", + "integrity": "sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g==", "dev": true, "requires": { "bn.js": "^4.11.9", diff --git a/package.json b/package.json index fa4d76b4a..42dee64ec 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@multiversx/sdk-core", - "version": "13.17.1", + "version": "14.0.0-beta.0", "description": "MultiversX SDK for JavaScript and TypeScript", "author": "MultiversX", "homepage": "https://multiversx.com", From cc5fb78cf84f79f643a485ccd2b9b873689d7c9b Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 26 Feb 2025 13:35:00 +0200 Subject: [PATCH 183/214] Remove relayed v1 and v2 --- src/entrypoints/entrypoints.spec.ts | 41 --- src/entrypoints/entrypoints.ts | 10 - src/relayed/index.ts | 2 - src/relayed/relayedController.ts | 48 ---- .../relayedTransactionsFactory.spec.ts | 260 ------------------ src/relayed/relayedTransactionsFactory.ts | 116 -------- src/relayed/resources.ts | 7 - 7 files changed, 484 deletions(-) delete mode 100644 src/relayed/index.ts delete mode 100644 src/relayed/relayedController.ts delete mode 100644 src/relayed/relayedTransactionsFactory.spec.ts delete mode 100644 src/relayed/relayedTransactionsFactory.ts delete mode 100644 src/relayed/resources.ts diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index 742bb3cd8..cd37de76f 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -103,47 +103,6 @@ describe("TestEntrypoint", function () { assert.equal(queryResult[0], 7); }); - it("create relayed transaction", async function () { - const transferController = entrypoint.createTransfersController(); - const filePath = path.join("src", "testdata", "testwallets", "alice.pem"); - const sender = await Account.newFromPem(filePath); - sender.nonce = 77777n; - - const bobPath = path.join("src", "testdata", "testwallets", "alice.pem"); - const relayer = await Account.newFromPem(bobPath); - relayer.nonce = 7n; - - const transaction = await transferController.createTransactionForTransfer( - sender, - BigInt(sender.getNonceThenIncrement().valueOf()), - { - receiver: sender.address, - data: Buffer.from("hello"), - }, - ); - const innerTransactionGasLimit = transaction.gasLimit; - transaction.gasLimit = BigInt(0); - transaction.signature = await sender.signTransaction(transaction); - - const relayedController = entrypoint.createRelayedController(); - const relayedTransaction = await relayedController.createRelayedV2Transaction( - relayer, - BigInt(relayer.getNonceThenIncrement().valueOf()), - { - innerTransaction: transaction, - innerTransactionGasLimit, - }, - ); - assert.equal(relayedTransaction.chainID, "D"); - assert.deepEqual( - Buffer.from(relayedTransaction.data), - Buffer.from( - "relayedTxV2@0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1@012fd1@68656c6c6f@c1eed3ac766d6b94aa53a1348d38eac8db60be0a1b2d0873247b61b8b25bbcb45bf9c1518227bcadd5044d4c027bdb935e0164243b2b2df9a5b250a10aca260e", - ), - ); - assert.equal(relayedTransaction.gasLimit, 442000n); - }); - it("create account", async () => { const account = await entrypoint.createAccount(); assert.isNotNull(account); diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index d15f3302e..73f1b95d6 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -12,8 +12,6 @@ import { TransactionWatcher } from "../core/transactionWatcher"; import { DelegationController, DelegationTransactionsFactory } from "../delegation"; import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { INetworkProvider } from "../networkProviders/interface"; -import { RelayedTransactionsFactory } from "../relayed"; -import { RelayedController } from "../relayed/relayedController"; import { SmartContractTransactionsFactory } from "../smartContracts"; import { SmartContractController } from "../smartContracts/smartContractController"; import { TokenManagementController, TokenManagementTransactionsFactory } from "../tokenManagement"; @@ -108,14 +106,6 @@ class NetworkEntrypoint { return new AccountTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: this.chainId }) }); } - createRelayedController(): RelayedController { - return new RelayedController({ chainID: this.chainId }); - } - - createRelayedTransactionsFactory(): RelayedTransactionsFactory { - return new RelayedTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: this.chainId }) }); - } - createSmartContractController(abi?: AbiRegistry): SmartContractController { return new SmartContractController({ chainID: this.chainId, networkProvider: this.networkProvider, abi }); } diff --git a/src/relayed/index.ts b/src/relayed/index.ts deleted file mode 100644 index fbf0c51f0..000000000 --- a/src/relayed/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./relayedController"; -export * from "./relayedTransactionsFactory"; diff --git a/src/relayed/relayedController.ts b/src/relayed/relayedController.ts deleted file mode 100644 index 43c9979d3..000000000 --- a/src/relayed/relayedController.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { IAccount } from "../accounts/interfaces"; -import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; -import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; -import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; -import { RelayedV1TransactionInput, RelayedV2TransactionInput } from "./resources"; - -export class RelayedController { - private factory: RelayedTransactionsFactory; - private txComputer: TransactionComputer; - - /** - * The transactions are created from the perspective of the relayer. - * The 'sender' represents the relayer. - */ - constructor(options: { chainID: string }) { - this.factory = new RelayedTransactionsFactory({ - config: new TransactionsFactoryConfig(options), - }); - this.txComputer = new TransactionComputer(); - } - - async createRelayedV1Transaction( - sender: IAccount, - nonce: bigint, - options: RelayedV1TransactionInput, - ): Promise { - const transaction = this.factory.createRelayedV1Transaction(sender.address, options); - - transaction.nonce = nonce; - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); - - return transaction; - } - - async createRelayedV2Transaction( - sender: IAccount, - nonce: bigint, - options: RelayedV2TransactionInput, - ): Promise { - const transaction = this.factory.createRelayedV2Transaction(sender.address, options); - - transaction.nonce = nonce; - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); - - return transaction; - } -} diff --git a/src/relayed/relayedTransactionsFactory.spec.ts b/src/relayed/relayedTransactionsFactory.spec.ts deleted file mode 100644 index 9757de44b..000000000 --- a/src/relayed/relayedTransactionsFactory.spec.ts +++ /dev/null @@ -1,260 +0,0 @@ -import { assert } from "chai"; -import { Account } from "../accounts"; -import { Address, Transaction, TransactionsFactoryConfig } from "../core"; -import { getTestWalletsPath } from "../testutils"; -import { RelayedTransactionsFactory } from "./relayedTransactionsFactory"; - -describe("test relayed transactions factory", function () { - const config = new TransactionsFactoryConfig({ chainID: "T" }); - const factory = new RelayedTransactionsFactory({ config: config }); - let alice: Account, bob: Account, carol: Account, grace: Account, frank: Account; - - before(async function () { - alice = await Account.newFromPem(`${getTestWalletsPath()}/alice.pem`); - bob = await Account.newFromPem(`${getTestWalletsPath()}/bob.pem`); - carol = await Account.newFromPem(`${getTestWalletsPath()}/carol.pem`); - grace = await Account.newFromPem(`${getTestWalletsPath()}/grace.pem`); - frank = await Account.newFromPem(`${getTestWalletsPath()}/frank.pem`); - }); - - it("should throw exception when creating relayed v1 transaction with invalid inner transaction", async function () { - let innerTransaction = new Transaction({ - sender: alice.address, - receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), - gasLimit: 10000000n, - data: Buffer.from("getContractConfig"), - chainID: config.chainID, - }); - - assert.throws(() => { - factory.createRelayedV1Transaction(bob.address, { innerTransaction: innerTransaction }), - "The inner transaction is not signed"; - }); - - innerTransaction.gasLimit = 0n; - innerTransaction.signature = Buffer.from("invalidsignature"); - - assert.throws(() => { - factory.createRelayedV1Transaction(bob.address, { innerTransaction: innerTransaction }), - "The gas limit is not set for the inner transaction"; - }); - }); - - it("should create relayed v1 transaction", async function () { - let innerTransaction = new Transaction({ - sender: bob.address, - receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), - gasLimit: 60000000n, - data: Buffer.from("getContractConfig"), - chainID: config.chainID, - nonce: 198n, - }); - - innerTransaction.signature = await bob.signTransaction(innerTransaction); - - const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { - innerTransaction: innerTransaction, - }); - relayedTransaction.nonce = 2627n; - - relayedTransaction.signature = await alice.signTransaction(relayedTransaction); - - assert.equal( - Buffer.from(relayedTransaction.data).toString(), - "relayedTx@7b226e6f6e6365223a3139382c2273656e646572223a2267456e574f65576d6d413063306a6b71764d354241707a61644b46574e534f69417643575163776d4750673d222c227265636569766572223a22414141414141414141414141415141414141414141414141414141414141414141414141414141432f2f383d222c2276616c7565223a302c226761735072696365223a313030303030303030302c226761734c696d6974223a36303030303030302c2264617461223a225a3256305132397564484a68593352446232356d6157633d222c227369676e6174757265223a2272525455544858677a4273496e4f6e454b6b7869642b354e66524d486e33534948314673746f577352434c434b3258514c41614f4e704449346531476173624c5150616130566f364144516d4f2b52446b6f364a43413d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a327d", - ); - assert.equal( - Buffer.from(relayedTransaction.signature).toString("hex"), - "128e7cdc14c2b9beee2f3ff7a7fa5d1f5ef31a654a0c92e223c90ab28265fa277d306f23a06536248cf9573e828017004fb639617fade4d68a37524aafca710d", - ); - }); - - it("should create relayed v1 transaction with usernames", async function () { - let innerTransaction = new Transaction({ - sender: carol.address, - receiver: alice.address, - gasLimit: 50000n, - chainID: config.chainID, - nonce: 208n, - senderUsername: "carol", - receiverUsername: "alice", - value: 1000000000000000000n, - }); - - innerTransaction.signature = await carol.signTransaction(innerTransaction); - - const relayedTransaction = factory.createRelayedV1Transaction(frank.address, { - innerTransaction: innerTransaction, - }); - relayedTransaction.nonce = 715n; - - relayedTransaction.signature = await frank.signTransaction(relayedTransaction); - - assert.equal( - Buffer.from(relayedTransaction.data).toString(), - "relayedTx@7b226e6f6e6365223a3230382c2273656e646572223a227371455656633553486b6c45344a717864556e59573068397a536249533141586f3534786f32634969626f3d222c227265636569766572223a2241546c484c76396f686e63616d433877673970645168386b77704742356a6949496f3349484b594e6165453d222c2276616c7565223a313030303030303030303030303030303030302c226761735072696365223a313030303030303030302c226761734c696d6974223a35303030302c2264617461223a22222c227369676e6174757265223a226a33427a6469554144325963517473576c65707663664a6f75657a48573063316b735a424a4d6339573167435450512b6870636759457858326f6f367a4b5654347464314b4b6f79783841526a346e336474576c44413d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a322c22736e64557365724e616d65223a22593246796232773d222c22726376557365724e616d65223a22595778705932553d227d", - ); - assert.equal( - Buffer.from(relayedTransaction.signature).toString("hex"), - "3787d640e5a579e7977a4a1bcdd435ad11855632fa4a414a06fbf8355692d1a58d76ef0adbdd6ccd6bd3c329f36bd53c180d4873ec1a6c558e659aeb9ab92d00", - ); - }); - - it("should create relayed v1 transaction with big value", async function () { - let innerTransaction = new Transaction({ - sender: carol.address, - receiver: alice.address, - gasLimit: 50000n, - chainID: config.chainID, - nonce: 208n, - senderUsername: "carol", - receiverUsername: "alice", - value: 1999999000000000000000000n, - }); - - innerTransaction.signature = await carol.signTransaction(innerTransaction); - - const relayedTransaction = factory.createRelayedV1Transaction(frank.address, { - innerTransaction: innerTransaction, - }); - relayedTransaction.nonce = 715n; - - relayedTransaction.signature = await frank.signTransaction(relayedTransaction); - - assert.equal( - Buffer.from(relayedTransaction.data).toString(), - "relayedTx@7b226e6f6e6365223a3230382c2273656e646572223a227371455656633553486b6c45344a717864556e59573068397a536249533141586f3534786f32634969626f3d222c227265636569766572223a2241546c484c76396f686e63616d433877673970645168386b77704742356a6949496f3349484b594e6165453d222c2276616c7565223a313939393939393030303030303030303030303030303030302c226761735072696365223a313030303030303030302c226761734c696d6974223a35303030302c2264617461223a22222c227369676e6174757265223a22594661677972512f726d614c7333766e7159307657553858415a7939354b4e31725738347a4f764b62376c7a3773576e2f566a546d68704378774d682b7261314e444832574d6f3965507648304f79427453776a44773d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a322c22736e64557365724e616d65223a22593246796232773d222c22726376557365724e616d65223a22595778705932553d227d", - ); - assert.equal( - Buffer.from(relayedTransaction.signature).toString("hex"), - "c0fb5cf8c0a413d6988ba35dc279c63f8849572c5f23b1cab36dcc50952dc3ed9da01068d6ac0cbde7e14167bfc2eca5164d5c2154c89eb313c9c596e3f8b801", - ); - }); - - it("should create relayed v1 transaction with guarded inner transaction", async function () { - let innerTransaction = new Transaction({ - sender: bob.address, - receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqpgq54tsxmej537z9leghvp69hfu4f8gg5eu396q83gnnz"), - gasLimit: 60000000n, - chainID: config.chainID, - data: Buffer.from("getContractConfig"), - nonce: 198n, - version: 2, - options: 2, - guardian: grace.address, - }); - - innerTransaction.signature = await bob.signTransaction(innerTransaction); - innerTransaction.guardianSignature = await grace.signTransaction(innerTransaction); - - const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { - innerTransaction: innerTransaction, - }); - relayedTransaction.nonce = 2627n; - - relayedTransaction.signature = await alice.signTransaction(relayedTransaction); - - assert.equal( - Buffer.from(relayedTransaction.data).toString(), - "relayedTx@7b226e6f6e6365223a3139382c2273656e646572223a2267456e574f65576d6d413063306a6b71764d354241707a61644b46574e534f69417643575163776d4750673d222c227265636569766572223a22414141414141414141414146414b565841323879704877692f79693741364c64504b704f68464d386958513d222c2276616c7565223a302c226761735072696365223a313030303030303030302c226761734c696d6974223a36303030303030302c2264617461223a225a3256305132397564484a68593352446232356d6157633d222c227369676e6174757265223a224b4b78324f33383655725135416b4f465258307578327933446a384853334b373038487174344668377161557669424550716c45614e746e6158706a6f2f333651476d4a456934784435457a6c6f4f677a634d4442773d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a322c226f7074696f6e73223a322c22677561726469616e223a22486f714c61306e655733766843716f56696c70715372744c5673774939535337586d7a563868477450684d3d222c22677561726469616e5369676e6174757265223a222b5431526f4833625a792f54423177342b6a365155477258645637457577553073753948646551626453515269463953757a686d634b705463526d58595252366c534c6652394931624d7134674730436538363741513d3d227d", - ); - assert.equal( - Buffer.from(relayedTransaction.signature).toString("hex"), - "39cff9d5100e290fbc7361cb6e2402261caf864257b4116f150e0c61e7869155dff8361fa5449431eb7a8ed847c01ba9b3b5ebafe5fac1a3d40c64829d827e00", - ); - }); - - it("should create guarded relayed v1 transaction with guarded inner transaction", async function () { - let innerTransaction = new Transaction({ - sender: bob.address, - receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqpgq54tsxmej537z9leghvp69hfu4f8gg5eu396q83gnnz"), - gasLimit: 60000000n, - chainID: config.chainID, - data: Buffer.from("addNumber"), - nonce: 198n, - version: 2, - options: 2, - guardian: grace.address, - }); - - innerTransaction.signature = await bob.signTransaction(innerTransaction); - innerTransaction.guardianSignature = await grace.signTransaction(innerTransaction); - - const relayedTransaction = factory.createRelayedV1Transaction(alice.address, { - innerTransaction: innerTransaction, - }); - relayedTransaction.nonce = 2627n; - relayedTransaction.options = 2; - relayedTransaction.guardian = frank.address; - - relayedTransaction.signature = await alice.signTransaction(relayedTransaction); - relayedTransaction.guardianSignature = await frank.signTransaction(relayedTransaction); - - assert.equal( - Buffer.from(relayedTransaction.data).toString(), - "relayedTx@7b226e6f6e6365223a3139382c2273656e646572223a2267456e574f65576d6d413063306a6b71764d354241707a61644b46574e534f69417643575163776d4750673d222c227265636569766572223a22414141414141414141414146414b565841323879704877692f79693741364c64504b704f68464d386958513d222c2276616c7565223a302c226761735072696365223a313030303030303030302c226761734c696d6974223a36303030303030302c2264617461223a225957526b546e5674596d5679222c227369676e6174757265223a223469724d4b4a656d724d375174344e7635487633544c44683775654779487045564c4371674a3677652f7a662b746a4933354975573452633458543451533433475333356158386c6a533834324a38426854645043673d3d222c22636861696e4944223a2256413d3d222c2276657273696f6e223a322c226f7074696f6e73223a322c22677561726469616e223a22486f714c61306e655733766843716f56696c70715372744c5673774939535337586d7a563868477450684d3d222c22677561726469616e5369676e6174757265223a2270424754394e674a78307539624c56796b654d78786a454865374269696c37764932324a46676f32787a6e2f496e3032463769546563356b44395045324f747065386c475335412b532f4a36417762576834446744673d3d227d", - ); - assert.equal( - Buffer.from(relayedTransaction.signature).toString("hex"), - "8ede1bbeed96b102344dffeac12c2592c62b7313cdeb132e8c8bf11d2b1d3bb8189d257a6dbcc99e222393d9b9ec77656c349dae97a32e68bdebd636066bf706", - ); - }); - - it("should throw exception when creating relayed v2 transaction with invalid inner transaction", async function () { - let innerTransaction = new Transaction({ - sender: bob.address, - receiver: bob.address, - gasLimit: 50000n, - chainID: config.chainID, - }); - - assert.throws(() => { - factory.createRelayedV2Transaction(carol.address, { - innerTransaction: innerTransaction, - innerTransactionGasLimit: 50000n, - }), - "The gas limit should not be set for the inner transaction"; - }); - - innerTransaction.gasLimit = 0n; - - assert.throws(() => { - factory.createRelayedV2Transaction(carol.address, { - innerTransaction: innerTransaction, - innerTransactionGasLimit: 50000n, - }), - "The inner transaction is not signed"; - }); - }); - - it("should create relayed v2 transaction", async function () { - let innerTransaction = new Transaction({ - sender: bob.address, - receiver: Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"), - gasLimit: 0n, - chainID: config.chainID, - data: Buffer.from("getContractConfig"), - nonce: 15n, - version: 2, - options: 0, - }); - - innerTransaction.signature = await bob.signTransaction(innerTransaction); - - const relayedTransaction = factory.createRelayedV2Transaction(alice.address, { - innerTransaction: innerTransaction, - innerTransactionGasLimit: 60000000n, - }); - relayedTransaction.nonce = 37n; - - relayedTransaction.signature = await alice.signTransaction(relayedTransaction); - - assert.equal(relayedTransaction.version, 2); - assert.equal(relayedTransaction.options, 0); - assert.equal(relayedTransaction.gasLimit.toString(), "60414500"); - assert.equal( - Buffer.from(relayedTransaction.data).toString(), - "relayedTxV2@000000000000000000010000000000000000000000000000000000000002ffff@0f@676574436f6e7472616374436f6e666967@fc3ed87a51ee659f937c1a1ed11c1ae677e99629fae9cc289461f033e6514d1a8cfad1144ae9c1b70f28554d196bd6ba1604240c1c1dc19c959e96c1c3b62d0c", - ); - }); -}); diff --git a/src/relayed/relayedTransactionsFactory.ts b/src/relayed/relayedTransactionsFactory.ts deleted file mode 100644 index 8e14eee1b..000000000 --- a/src/relayed/relayedTransactionsFactory.ts +++ /dev/null @@ -1,116 +0,0 @@ -import BigNumber from "bignumber.js"; -import { AddressValue, ArgSerializer, BytesValue, U64Value } from "../abi"; -import { Address } from "../core/address"; -import { ErrInvalidInnerTransaction } from "../core/errors"; -import { Transaction } from "../core/transaction"; - -const JSONbig = require("json-bigint"); - -interface IConfig { - chainID: string; - minGasLimit: bigint; - gasLimitPerByte: bigint; -} - -/** - * Use this class to create both RelayedV1 and RelayedV2 transactions. - */ -export class RelayedTransactionsFactory { - private readonly config: IConfig; - - constructor(options: { config: IConfig }) { - this.config = options.config; - } - - createRelayedV1Transaction(relayerAddress: Address, options: { innerTransaction: Transaction }): Transaction { - if (!options.innerTransaction.gasLimit) { - throw new ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction"); - } - - if (!options.innerTransaction.signature.length) { - throw new ErrInvalidInnerTransaction("The inner transaction is not signed"); - } - - const serializedTransaction = this.prepareInnerTransactionForRelayedV1(options.innerTransaction); - const data = `relayedTx@${Buffer.from(serializedTransaction).toString("hex")}`; - - const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); - const gasLimit = this.config.minGasLimit + additionalGasForDataLength + options.innerTransaction.gasLimit; - - return new Transaction({ - chainID: this.config.chainID, - sender: relayerAddress, - receiver: options.innerTransaction.sender, - gasLimit: gasLimit, - data: Buffer.from(data), - }); - } - - createRelayedV2Transaction( - relayerAddress: Address, - options: { - innerTransaction: Transaction; - innerTransactionGasLimit: bigint; - }, - ): Transaction { - if (options.innerTransaction.gasLimit) { - throw new ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction"); - } - - if (!options.innerTransaction.signature.length) { - throw new ErrInvalidInnerTransaction("The inner transaction is not signed"); - } - - const { argumentsString } = new ArgSerializer().valuesToString([ - new AddressValue(options.innerTransaction.receiver), - new U64Value(new BigNumber(options.innerTransaction.nonce.toString())), - new BytesValue(Buffer.from(options.innerTransaction.data)), - new BytesValue(Buffer.from(options.innerTransaction.signature)), - ]); - - const data = `relayedTxV2@${argumentsString}`; - - const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); - const gasLimit = options.innerTransactionGasLimit + this.config.minGasLimit + additionalGasForDataLength; - - return new Transaction({ - sender: relayerAddress, - receiver: options.innerTransaction.sender, - value: 0n, - gasLimit: gasLimit, - chainID: this.config.chainID, - data: Buffer.from(data), - version: options.innerTransaction.version, - options: options.innerTransaction.options, - }); - } - - private prepareInnerTransactionForRelayedV1(innerTransaction: Transaction): string { - const txObject = { - nonce: innerTransaction.nonce, - sender: innerTransaction.sender.getPublicKey().toString("base64"), - receiver: innerTransaction.receiver.getPublicKey().toString("base64"), - value: innerTransaction.value, - gasPrice: innerTransaction.gasPrice, - gasLimit: innerTransaction.gasLimit, - data: Buffer.from(innerTransaction.data).toString("base64"), - signature: Buffer.from(innerTransaction.signature).toString("base64"), - chainID: Buffer.from(innerTransaction.chainID).toString("base64"), - version: innerTransaction.version, - options: innerTransaction.options == 0 ? undefined : innerTransaction.options, - guardian: innerTransaction.guardian.isEmpty() - ? undefined - : innerTransaction.guardian.getPublicKey().toString("base64"), - guardianSignature: innerTransaction.guardianSignature.length - ? Buffer.from(innerTransaction.guardianSignature).toString("base64") - : undefined, - sndUserName: innerTransaction.senderUsername - ? Buffer.from(innerTransaction.senderUsername).toString("base64") - : undefined, - rcvUserName: innerTransaction.receiverUsername - ? Buffer.from(innerTransaction.receiverUsername).toString("base64") - : undefined, - }; - return JSONbig.stringify(txObject); - } -} diff --git a/src/relayed/resources.ts b/src/relayed/resources.ts deleted file mode 100644 index 62e4ecc9b..000000000 --- a/src/relayed/resources.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Transaction } from "../core/transaction"; - -export type RelayedV1TransactionInput = { innerTransaction: Transaction }; -export type RelayedV2TransactionInput = { - innerTransaction: Transaction; - innerTransactionGasLimit: bigint; -}; From e7971994ff459722e22926d7671f2d0f06bc3a40 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 26 Feb 2025 13:37:01 +0200 Subject: [PATCH 184/214] Commit missing files --- src/core/errors.ts | 27 --------------------------- src/index.ts | 1 - 2 files changed, 28 deletions(-) diff --git a/src/core/errors.ts b/src/core/errors.ts index 9eb4d610f..489d0ff1b 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -299,33 +299,6 @@ export class ErrNotImplemented extends Err { } } -/** - * Signals invalid arguments when using the relayed v1 builder - */ -export class ErrInvalidRelayedV1BuilderArguments extends Err { - public constructor() { - super("invalid arguments for relayed v1 builder"); - } -} - -/** - * Signals invalid arguments when using the relayed v2 builder - */ -export class ErrInvalidRelayedV2BuilderArguments extends Err { - public constructor() { - super("invalid arguments for relayed v2 builder"); - } -} - -/** - * Signals that Gas Limit isn't 0 for an inner tx when using relayed v2 builder - */ -export class ErrGasLimitShouldBe0ForInnerTransaction extends Err { - public constructor() { - super("gas limit must be 0 for the inner transaction for relayed v2"); - } -} - /** * Signals that the `isCompleted` property is missing on the transaction obect and is needed for the Transaction Watcher */ diff --git a/src/index.ts b/src/index.ts index 4229e47be..8226037c3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,7 +11,6 @@ export * from "./core"; export * from "./delegation"; export * from "./entrypoints"; export * from "./networkProviders"; -export * from "./relayed"; export * from "./tokenManagement"; export * from "./transactionsOutcomeParsers"; export * from "./transfers"; From 81d4df211f6e9bf3adcecaffcc6af35a2a6cb70c Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Mar 2025 14:39:00 +0200 Subject: [PATCH 185/214] Export missing files --- src/core/transaction.ts | 40 +++++++++++++++++++--------------- src/core/transactionWatcher.ts | 6 ++--- src/delegation/index.ts | 1 + src/index.ts | 1 + src/networkProviders/index.ts | 4 +++- src/smartContracts/index.ts | 1 + src/tokenManagement/index.ts | 1 + src/transfers/index.ts | 1 + 8 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/core/transaction.ts b/src/core/transaction.ts index a792173e6..8f27ab997 100644 --- a/src/core/transaction.ts +++ b/src/core/transaction.ts @@ -386,25 +386,29 @@ export class Transaction { * * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() */ - static newFromPlainObject(object: IPlainTransactionObject): Transaction { + static newFromPlainObject(plainObjectTransaction: IPlainTransactionObject): Transaction { const transaction = new Transaction({ - nonce: BigInt(object.nonce), - value: BigInt(object.value || ""), - receiver: Address.newFromBech32(object.receiver), - receiverUsername: Buffer.from(object.receiverUsername || "", "base64").toString(), - sender: Address.newFromBech32(object.sender), - senderUsername: Buffer.from(object.senderUsername || "", "base64").toString(), - guardian: object.guardian ? Address.newFromBech32(object.guardian) : Address.empty(), - relayer: object.relayer ? Address.newFromBech32(object.relayer) : Address.empty(), - gasPrice: BigInt(object.gasPrice), - gasLimit: BigInt(object.gasLimit), - data: Buffer.from(object.data || "", "base64"), - chainID: String(object.chainID), - version: Number(object.version), - options: object.options ? Number(object.options) : undefined, - signature: Buffer.from(object.signature || "", "hex"), - guardianSignature: Buffer.from(object.guardianSignature || "", "hex"), - relayerSignature: Buffer.from(object.relayerSignature || "", "hex"), + nonce: BigInt(plainObjectTransaction.nonce), + value: BigInt(plainObjectTransaction.value || ""), + receiver: Address.newFromBech32(plainObjectTransaction.receiver), + receiverUsername: Buffer.from(plainObjectTransaction.receiverUsername || "", "base64").toString(), + sender: Address.newFromBech32(plainObjectTransaction.sender), + senderUsername: Buffer.from(plainObjectTransaction.senderUsername || "", "base64").toString(), + guardian: plainObjectTransaction.guardian + ? Address.newFromBech32(plainObjectTransaction.guardian) + : Address.empty(), + relayer: plainObjectTransaction.relayer + ? Address.newFromBech32(plainObjectTransaction.relayer) + : Address.empty(), + gasPrice: BigInt(plainObjectTransaction.gasPrice), + gasLimit: BigInt(plainObjectTransaction.gasLimit), + data: Buffer.from(plainObjectTransaction.data || "", "base64"), + chainID: String(plainObjectTransaction.chainID), + version: Number(plainObjectTransaction.version), + options: plainObjectTransaction.options ? Number(plainObjectTransaction.options) : undefined, + signature: Buffer.from(plainObjectTransaction.signature || "", "hex"), + guardianSignature: Buffer.from(plainObjectTransaction.guardianSignature || "", "hex"), + relayerSignature: Buffer.from(plainObjectTransaction.relayerSignature || "", "hex"), }); return transaction; diff --git a/src/core/transactionWatcher.ts b/src/core/transactionWatcher.ts index 08defcb89..e6654a181 100644 --- a/src/core/transactionWatcher.ts +++ b/src/core/transactionWatcher.ts @@ -68,15 +68,15 @@ export class TransactionWatcher { /** * Waits until the transaction is completely processed. - * @param txHash The hex-encoded transaction hash + * @param txHash The transaction hash */ - public async awaitCompleted(txhash: string): Promise { + public async awaitCompleted(txHash: string): Promise { const isCompleted = (transactionOnNetwork: TransactionOnNetwork) => { return transactionOnNetwork.status.isCompleted(); }; const doFetch = async () => { - return await this.fetcher.getTransaction(txhash); + return await this.fetcher.getTransaction(txHash); }; const errorProvider = () => new ErrExpectedTransactionStatusNotReached(); diff --git a/src/delegation/index.ts b/src/delegation/index.ts index 955224312..648988539 100644 --- a/src/delegation/index.ts +++ b/src/delegation/index.ts @@ -1,3 +1,4 @@ export * from "./delegationController"; export * from "./delegationTransactionsFactory"; export * from "./delegationTransactionsOutcomeParser"; +export * from "./resources"; diff --git a/src/index.ts b/src/index.ts index 8226037c3..b9e1ef27e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ export * from "./core"; export * from "./delegation"; export * from "./entrypoints"; export * from "./networkProviders"; +export * from "./smartContracts"; export * from "./tokenManagement"; export * from "./transactionsOutcomeParsers"; export * from "./transfers"; diff --git a/src/networkProviders/index.ts b/src/networkProviders/index.ts index 4a9558add..6684078f4 100644 --- a/src/networkProviders/index.ts +++ b/src/networkProviders/index.ts @@ -1,7 +1,7 @@ export { ApiNetworkProvider } from "./apiNetworkProvider"; +export * from "./interface"; export { ProxyNetworkProvider } from "./proxyNetworkProvider"; -export { AccountOnNetwork } from "./accounts"; export { ContractQueryResponse } from "./contractQueryResponse"; export { ContractResultItem, ContractResults } from "./contractResults"; export { TransactionReceipt } from "./transactionReceipt"; @@ -9,5 +9,7 @@ export { TransactionReceipt } from "./transactionReceipt"; export { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; export { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; +export * from "./accounts"; export { NetworkConfig } from "./networkConfig"; export { NetworkStatus } from "./networkStatus"; +export * from "./resources"; diff --git a/src/smartContracts/index.ts b/src/smartContracts/index.ts index 29233d303..9a036eb4d 100644 --- a/src/smartContracts/index.ts +++ b/src/smartContracts/index.ts @@ -1,3 +1,4 @@ +export * from "./resources"; export * from "./smartContractController"; export * from "./smartContractTransactionsFactory"; export * from "./smartContractTransactionsOutcomeParser"; diff --git a/src/tokenManagement/index.ts b/src/tokenManagement/index.ts index c5b0ff043..ff3c75dee 100644 --- a/src/tokenManagement/index.ts +++ b/src/tokenManagement/index.ts @@ -1,3 +1,4 @@ +export * from "./resources"; export * from "./tokenManagementController"; export * from "./tokenManagementTransactionsFactory"; export * from "./tokenManagementTransactionsOutcomeParser"; diff --git a/src/transfers/index.ts b/src/transfers/index.ts index 1542bb8ce..279375198 100644 --- a/src/transfers/index.ts +++ b/src/transfers/index.ts @@ -1,2 +1,3 @@ +export * from "./resources"; export * from "./transfersControllers"; export * from "./transferTransactionsFactory"; From 6f06d7a13bba092e9f13e6ad50890b8b3f10e9fa Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Mar 2025 14:54:33 +0200 Subject: [PATCH 186/214] Update to use new methods and not deprecated ones --- src/abi/nativeSerializer.spec.ts | 2 +- .../accountTransactionsFactory.spec.ts | 6 +++--- src/accountManagement/index.ts | 1 + src/core/address.spec.ts | 14 +++++++------- src/core/errors.ts | 8 ++++---- src/networkProviders/index.ts | 1 + src/smartContracts/smartContractController.spec.ts | 2 +- .../smartContractTransactionsOutcomeParser.spec.ts | 6 +++--- src/tokenManagement/resources.ts | 2 +- .../transactionEventsParser.spec.ts | 6 +++--- src/transfers/transferTransactionsFactory.spec.ts | 4 ++-- 11 files changed, 27 insertions(+), 25 deletions(-) diff --git a/src/abi/nativeSerializer.spec.ts b/src/abi/nativeSerializer.spec.ts index 985860192..535c95cc0 100644 --- a/src/abi/nativeSerializer.spec.ts +++ b/src/abi/nativeSerializer.spec.ts @@ -288,7 +288,7 @@ describe("test native serializer", () => { const compositeType = new CompositeType(new AddressType(), new U64Type()); const optionalCompositeType = new OptionalType(compositeType); const addressBech32 = "erd1dc3yzxxeq69wvf583gw0h67td226gu2ahpk3k50qdgzzym8npltq7ndgha"; - const address = Address.fromBech32(addressBech32); + const address = Address.newFromBech32(addressBech32); const compositeValue = CompositeValue.fromItems(new AddressValue(address), new U64Value(42)); const optionalCompositeValue = new OptionalValue(optionalCompositeType, compositeValue); diff --git a/src/accountManagement/accountTransactionsFactory.spec.ts b/src/accountManagement/accountTransactionsFactory.spec.ts index 3067a0112..2bee04226 100644 --- a/src/accountManagement/accountTransactionsFactory.spec.ts +++ b/src/accountManagement/accountTransactionsFactory.spec.ts @@ -7,7 +7,7 @@ describe("test account transactions factory", function () { const factory = new AccountTransactionsFactory({ config: config }); it("should create 'Transaction' for saving key value", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const keyValuePairs = new Map([[Buffer.from("key0"), Buffer.from("value0")]]); const transaction = factory.createTransactionForSavingKeyValue(sender, { @@ -56,7 +56,7 @@ describe("test account transactions factory", function () { }); it("should create 'Transaction' for guarding account", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const transaction = factory.createTransactionForGuardingAccount(sender); @@ -75,7 +75,7 @@ describe("test account transactions factory", function () { }); it("should create 'Transaction' for unguarding account", async function () { - const sender = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const sender = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const transaction = factory.createTransactionForUnguardingAccount(sender); diff --git a/src/accountManagement/index.ts b/src/accountManagement/index.ts index 87098af89..9049c3d2b 100644 --- a/src/accountManagement/index.ts +++ b/src/accountManagement/index.ts @@ -1,2 +1,3 @@ export * from "./accountController"; export * from "./accountTransactionsFactory"; +export * from "./resources"; diff --git a/src/core/address.spec.ts b/src/core/address.spec.ts index bfb2dccf1..e44da62f5 100644 --- a/src/core/address.spec.ts +++ b/src/core/address.spec.ts @@ -73,19 +73,19 @@ describe("test address", () => { it("should check whether isSmartContract", () => { assert.isFalse( - Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th").isSmartContract(), + Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th").isSmartContract(), ); assert.isTrue( - Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqplllst77y4l").isSmartContract(), + Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqplllst77y4l").isSmartContract(), ); assert.isTrue( - Address.fromBech32("erd1qqqqqqqqqqqqqpgqxwakt2g7u9atsnr03gqcgmhcv38pt7mkd94q6shuwt").isSmartContract(), + Address.newFromBech32("erd1qqqqqqqqqqqqqpgqxwakt2g7u9atsnr03gqcgmhcv38pt7mkd94q6shuwt").isSmartContract(), ); }); it("should contract address", () => { const addressComputer = new AddressComputer(); - const deployer = Address.fromBech32("erd1j0hxzs7dcyxw08c4k2nv9tfcaxmqy8rj59meq505w92064x0h40qcxh3ap"); + const deployer = Address.newFromBech32("erd1j0hxzs7dcyxw08c4k2nv9tfcaxmqy8rj59meq505w92064x0h40qcxh3ap"); let contractAddress = addressComputer.computeContractAddress(deployer, 0n); assert.equal(contractAddress.toHex(), "00000000000000000500bb652200ed1f994200ab6699462cab4b1af7b11ebd5e"); @@ -99,15 +99,15 @@ describe("test address", () => { it("should get address shard", () => { const addressComputer = new AddressComputer(); - let address = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + let address = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); let shard = addressComputer.getShardOfAddress(address); assert.equal(shard, 1); - address = Address.fromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); + address = Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); shard = addressComputer.getShardOfAddress(address); assert.equal(shard, 0); - address = Address.fromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"); + address = Address.newFromBech32("erd1k2s324ww2g0yj38qn2ch2jwctdy8mnfxep94q9arncc6xecg3xaq6mjse8"); shard = addressComputer.getShardOfAddress(address); assert.equal(shard, 2); }); diff --git a/src/core/errors.ts b/src/core/errors.ts index 489d0ff1b..ad58812d4 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -101,7 +101,7 @@ export class ErrAddressEmpty extends Err { } /** - * Signals an invalid value for {@link GasLimit} objects. + * Signals an invalid value for gasLimmit objects. */ export class ErrNotEnoughGas extends Err { public constructor(value: number) { @@ -110,7 +110,7 @@ export class ErrNotEnoughGas extends Err { } /** - * Signals an invalid value for {@link Nonce} objects. + * Signals an invalid value for nince objects. */ export class ErrNonceInvalid extends Err { public constructor(value: number) { @@ -119,7 +119,7 @@ export class ErrNonceInvalid extends Err { } /** - * Signals an invalid value for {@link TransactionVersion} objects. + * Signals an invalid value for transaction version objects. */ export class ErrTransactionVersionInvalid extends Err { public constructor(value: number) { @@ -128,7 +128,7 @@ export class ErrTransactionVersionInvalid extends Err { } /** - * Signals an invalid value for {@link TransactionOptions} objects. + * Signals an invalid value for transaction options objects. */ export class ErrTransactionOptionsInvalid extends Err { public constructor(value: number) { diff --git a/src/networkProviders/index.ts b/src/networkProviders/index.ts index 6684078f4..502cddf47 100644 --- a/src/networkProviders/index.ts +++ b/src/networkProviders/index.ts @@ -11,5 +11,6 @@ export { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } f export * from "./accounts"; export { NetworkConfig } from "./networkConfig"; +export { NetworkProviderConfig } from "./networkProviderConfig"; export { NetworkStatus } from "./networkStatus"; export * from "./resources"; diff --git a/src/smartContracts/smartContractController.spec.ts b/src/smartContracts/smartContractController.spec.ts index 59010660b..eadf1fb16 100644 --- a/src/smartContracts/smartContractController.spec.ts +++ b/src/smartContracts/smartContractController.spec.ts @@ -171,7 +171,7 @@ describe("test smart contract queries controller", () => { ); const query = { - contract: Address.fromBech32("erd1qqqqqqqqqqqqqpgqvc7gdl0p4s97guh498wgz75k8sav6sjfjlwqh679jy"), + contract: Address.newFromBech32("erd1qqqqqqqqqqqqqpgqvc7gdl0p4s97guh498wgz75k8sav6sjfjlwqh679jy"), function: "bar", arguments: [], }; diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index 90528b854..e4298cbc2 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -7,8 +7,8 @@ import { SmartContractTransactionsOutcomeParser } from "./smartContractTransacti describe("test smart contract transactions outcome parser", () => { it("parses deploy outcome", async function () { - const contract = Address.fromBech32("erd1qqqqqqqqqqqqqpgqqacl85rd0gl2q8wggl8pwcyzcr4fflc5d8ssve45cj"); - const deployer = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const contract = Address.newFromBech32("erd1qqqqqqqqqqqqqpgqqacl85rd0gl2q8wggl8pwcyzcr4fflc5d8ssve45cj"); + const deployer = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const codeHash = Buffer.from("abba", "hex"); const parser = new SmartContractTransactionsOutcomeParser(); @@ -44,7 +44,7 @@ describe("test smart contract transactions outcome parser", () => { }); it("parses deploy outcome (with error)", async function () { - const deployer = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const deployer = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); const parser = new SmartContractTransactionsOutcomeParser(); diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 18f7ce457..7ab41bedc 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -102,7 +102,7 @@ export type ManageMetadataInput = { export type RegisteringDynamicTokenInput = { tokenName: string; tokenTicker: string; tokenType: TokenType }; -type TokenType = "NFT" | "SFT" | "META" | "FNG"; +export type TokenType = "NFT" | "SFT" | "META" | "FNG"; export type SpecialRoleOutput = { userAddress: Address; diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts index 2fb33ed8e..52a48853d 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts @@ -65,7 +65,7 @@ describe("test transaction events parser", () => { assert.deepEqual(parsed, [ { - dest_address: Address.fromBech32("erd1wfkv9495dhtt6a9yepxsyu2mlpw2ua333j4cr0qfulpxr4q5nfnshgyqun"), + dest_address: Address.newFromBech32("erd1wfkv9495dhtt6a9yepxsyu2mlpw2ua333j4cr0qfulpxr4q5nfnshgyqun"), tokens: [ { token_identifier: "WEGLD-01e49d", @@ -119,7 +119,7 @@ describe("test transaction events parser", () => { name: "SendTransferExecuteEgld", fields: [ { - to: Address.fromBech32( + to: Address.newFromBech32( "erd1qqqqqqqqqqqqqpgq6qr0w0zzyysklfneh32eqp2cf383zc89d8sstnkl60", ), egld_amount: new BigNumber("0"), @@ -129,7 +129,7 @@ describe("test transaction events parser", () => { }, ], }, - signers: [Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th")], + signers: [Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th")], }, }, ]); diff --git a/src/transfers/transferTransactionsFactory.spec.ts b/src/transfers/transferTransactionsFactory.spec.ts index b9342535d..348d61602 100644 --- a/src/transfers/transferTransactionsFactory.spec.ts +++ b/src/transfers/transferTransactionsFactory.spec.ts @@ -10,8 +10,8 @@ describe("test transfer transactions factory", function () { config: config, }); - const alice = Address.fromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); - const bob = Address.fromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); + const alice = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); + const bob = Address.newFromBech32("erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx"); it("should throw error, no token transfer provided", async () => { let transfers: any = []; From 32d9ae98237512265aceb4f6d3e4a7d60648c3e3 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Mar 2025 15:11:00 +0200 Subject: [PATCH 187/214] Export Guardian --- src/delegation/delegationTransactionsOutcomeParser.spec.ts | 2 +- src/networkProviders/accounts.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/delegation/delegationTransactionsOutcomeParser.spec.ts b/src/delegation/delegationTransactionsOutcomeParser.spec.ts index 99067b286..cd88c5edf 100644 --- a/src/delegation/delegationTransactionsOutcomeParser.spec.ts +++ b/src/delegation/delegationTransactionsOutcomeParser.spec.ts @@ -8,7 +8,7 @@ describe("test delegation transactions outcome parser", () => { const parser = new DelegationTransactionsOutcomeParser(); it("should test parseCreateNewDelegationContract ", () => { - const contractAddress = Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqy8lllls62y8s5"); + const contractAddress = Address.newFromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqy8lllls62y8s5"); let encodedTopics = [ "Q8M8GTdWSAAA", "Q8M8GTdWSAAA", diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index fb6beca51..c6f0ae90b 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -110,7 +110,7 @@ export class GuardianData { } } -class Guardian { +export class Guardian { activationEpoch: number = 0; address: Address = Address.empty(); serviceUID: string = ""; From 43c5164c424c06fbb9706228f769edb88f5b8017 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Mar 2025 15:14:17 +0200 Subject: [PATCH 188/214] Export error obj --- src/abi/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/abi/index.ts b/src/abi/index.ts index c07177226..04ff81463 100644 --- a/src/abi/index.ts +++ b/src/abi/index.ts @@ -1,4 +1,5 @@ export * from "./argSerializer"; +export * from "./argumentErrorContext"; export * from "./code"; export * from "./codec"; export * from "./codeMetadata"; From 7099806c35094d7f8399613a03bd474449f11792 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Mar 2025 15:45:07 +0200 Subject: [PATCH 189/214] code review follow up --- src/core/errors.ts | 4 ++-- src/core/tokens.ts | 2 ++ src/tokenManagement/resources.ts | 3 +-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/core/errors.ts b/src/core/errors.ts index ad58812d4..83d7d4510 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -101,7 +101,7 @@ export class ErrAddressEmpty extends Err { } /** - * Signals an invalid value for gasLimmit objects. + * Signals an invalid value for gasLimit objects. */ export class ErrNotEnoughGas extends Err { public constructor(value: number) { @@ -110,7 +110,7 @@ export class ErrNotEnoughGas extends Err { } /** - * Signals an invalid value for nince objects. + * Signals an invalid value for nonce objects. */ export class ErrNonceInvalid extends Err { public constructor(value: number) { diff --git a/src/core/tokens.ts b/src/core/tokens.ts index 11c670ba4..759fdce9b 100644 --- a/src/core/tokens.ts +++ b/src/core/tokens.ts @@ -18,6 +18,8 @@ interface ILegacyTokenTransferOptions { numDecimals?: number; } +export type TokenType = "NFT" | "SFT" | "META" | "FNG"; + export class Token { readonly identifier: string; readonly nonce: bigint; diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 7ab41bedc..bb3bf6c8b 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -1,3 +1,4 @@ +import { TokenType } from "../core"; import { Address } from "../core/address"; export type IssueFungibleInput = IssueInput & { initialSupply: bigint; numDecimals: bigint }; @@ -102,8 +103,6 @@ export type ManageMetadataInput = { export type RegisteringDynamicTokenInput = { tokenName: string; tokenTicker: string; tokenType: TokenType }; -export type TokenType = "NFT" | "SFT" | "META" | "FNG"; - export type SpecialRoleOutput = { userAddress: Address; tokenIdentifier: string; From b6182101355d54343990650d35396880f1d654a3 Mon Sep 17 00:00:00 2001 From: danielailie Date: Mon, 3 Mar 2025 16:27:14 +0200 Subject: [PATCH 190/214] Improve errors --- src/core/errors.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/errors.ts b/src/core/errors.ts index 83d7d4510..793d2c3f2 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -101,7 +101,7 @@ export class ErrAddressEmpty extends Err { } /** - * Signals an invalid value for gasLimit objects. + * Signals an invalid value for gas limit. */ export class ErrNotEnoughGas extends Err { public constructor(value: number) { @@ -110,7 +110,7 @@ export class ErrNotEnoughGas extends Err { } /** - * Signals an invalid value for nonce objects. + * Signals an invalid value for nonce. */ export class ErrNonceInvalid extends Err { public constructor(value: number) { @@ -119,7 +119,7 @@ export class ErrNonceInvalid extends Err { } /** - * Signals an invalid value for transaction version objects. + * Signals an invalid value for transaction version. */ export class ErrTransactionVersionInvalid extends Err { public constructor(value: number) { @@ -128,7 +128,7 @@ export class ErrTransactionVersionInvalid extends Err { } /** - * Signals an invalid value for transaction options objects. + * Signals an invalid value for transaction options. */ export class ErrTransactionOptionsInvalid extends Err { public constructor(value: number) { From 8035c57e461a7407b01e74a7abab2bf4e2535f7e Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 5 Mar 2025 12:03:50 +0200 Subject: [PATCH 191/214] Token management fixes --- src/core/transactionsFactoryConfig.ts | 6 ++-- src/entrypoints/entrypoints.spec.ts | 3 +- src/smartContracts/resources.ts | 18 +++-------- ...tContractTransactionsOutcomeParser.spec.ts | 4 +-- .../smartContractTransactionsOutcomeParser.ts | 30 +++++-------------- src/tokenManagement/resources.ts | 9 +++++- .../tokenManagementTransactionsFactory.ts | 3 +- 7 files changed, 27 insertions(+), 46 deletions(-) diff --git a/src/core/transactionsFactoryConfig.ts b/src/core/transactionsFactoryConfig.ts index 1ad0007f1..117918813 100644 --- a/src/core/transactionsFactoryConfig.ts +++ b/src/core/transactionsFactoryConfig.ts @@ -62,9 +62,9 @@ export class TransactionsFactoryConfig { this.gasLimitFreezing = 60000000n; this.gasLimitWiping = 60000000n; this.gasLimitEsdtNftCreate = 3000000n; - this.gasLimitEsdtNftUpdateAttributes = 1000000n; - this.gasLimitEsdtNftAddQuantity = 1000000n; - this.gasLimitEsdtNftBurn = 1000000n; + this.gasLimitEsdtNftUpdateAttributes = 500000n; + this.gasLimitEsdtNftAddQuantity = 500000n; + this.gasLimitEsdtNftBurn = 500000n; this.gasLimitStorePerByte = 10000n; this.issueCost = 50000000000000000n; this.gasLimitEsdtModifyRoyalties = 60000000n; diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index cd37de76f..e06d617e8 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -2,7 +2,6 @@ import { assert } from "chai"; import { readFileSync } from "fs"; import path from "path"; import { Account } from "../accounts/account"; -import { Address } from "../core"; import { loadAbiRegistry } from "../testutils"; import { DevnetEntrypoint } from "./entrypoints"; @@ -82,7 +81,7 @@ describe("TestEntrypoint", function () { assert.equal(outcome.contracts.length, 1); - const contractAddress = Address.newFromBech32(outcome.contracts[0].address); + const contractAddress = outcome.contracts[0].address; const executeTransaction = await controller.createTransactionForExecute( sender, diff --git a/src/smartContracts/resources.ts b/src/smartContracts/resources.ts index f9008b85e..508aab388 100644 --- a/src/smartContracts/resources.ts +++ b/src/smartContracts/resources.ts @@ -34,18 +34,8 @@ export type ParsedSmartContractCallOutcome = { returnMessage: string; }; -export class DeployedSmartContract { - address: string; - ownerAddress: string; +export type DeployedSmartContract = { + address: Address; + ownerAddress: Address; codeHash: Uint8Array; - - constructor(address: string, ownerAddress: string, codeHash: Uint8Array) { - this.address = address; - this.ownerAddress = ownerAddress; - this.codeHash = codeHash; - } - - toString(): string { - return `DeployedSmartContract(address=${this.address}, ownerAddress=${this.ownerAddress}, codeHash=${Buffer.from(this.codeHash).toString("hex")})`; - } -} +}; diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts index e4298cbc2..649d4b2a9 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.spec.ts @@ -36,8 +36,8 @@ describe("test smart contract transactions outcome parser", () => { assert.equal(parsed.returnMessage, "ok"); assert.deepEqual(parsed.contracts, [ { - address: contract.toBech32(), - ownerAddress: deployer.toBech32(), + address: contract, + ownerAddress: deployer, codeHash: codeHash, }, ]); diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index fdb0d4588..aadfc484e 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -20,27 +20,13 @@ export class SmartContractTransactionsOutcomeParser { this.abi = options?.abi; } - parseDeploy(options: { transactionOnNetwork: TransactionOnNetwork }): { - returnCode: string; - returnMessage: string; - contracts: { - address: string; - ownerAddress: string; - codeHash: Uint8Array; - }[]; - } { + parseDeploy(options: { transactionOnNetwork: TransactionOnNetwork }): resources.SmartContractDeployOutcome { return this.parseDeployGivenTransactionOnNetwork(options.transactionOnNetwork); } - protected parseDeployGivenTransactionOnNetwork(transactionOnNetwork: TransactionOnNetwork): { - returnCode: string; - returnMessage: string; - contracts: { - address: string; - ownerAddress: string; - codeHash: Uint8Array; - }[]; - } { + protected parseDeployGivenTransactionOnNetwork( + transactionOnNetwork: TransactionOnNetwork, + ): resources.SmartContractDeployOutcome { const directCallOutcome = this.findDirectSmartContractCallOutcome(transactionOnNetwork); const events = transactionOnNetwork.logs.events @@ -61,15 +47,15 @@ export class SmartContractTransactionsOutcomeParser { } private parseScDeployEvent(event: { topics: Uint8Array[] }): { - address: string; - ownerAddress: string; + address: Address; + ownerAddress: Address; codeHash: Uint8Array; } { const topicForAddress = Buffer.from(event.topics[0]).toString("hex"); const topicForOwnerAddress = Buffer.from(event.topics[1]).toString("hex"); const topicForCodeHash = Buffer.from(event.topics[2]); - const address = topicForAddress?.length ? new Address(topicForAddress).toBech32() : ""; - const ownerAddress = topicForOwnerAddress?.length ? new Address(topicForOwnerAddress).toBech32() : ""; + const address = topicForAddress?.length ? new Address(topicForAddress) : Address.empty(); + const ownerAddress = topicForOwnerAddress?.length ? new Address(topicForOwnerAddress) : Address.empty(); const codeHash = topicForCodeHash; return { diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index bb3bf6c8b..d3f7e0fb2 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -25,7 +25,14 @@ export type FungibleSpecialRoleInput = { addRoleLocalBurn: boolean; addRoleESDTTransferRole: boolean; }; -export type SemiFungibleSpecialRoleInput = SpecialRoleInput & { addRoleNFTAddQuantity: boolean }; +export type SemiFungibleSpecialRoleInput = { + user: Address; + tokenIdentifier: string; + addRoleNFTCreate: boolean; + addRoleNFTBurn: boolean; + addRoleNFTAddQuantity: boolean; + addRoleESDTTransferRole: boolean; +}; export type SpecialRoleInput = { user: Address; diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index d6d14e5e4..e715a7748 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -292,7 +292,6 @@ export class TokenManagementTransactionsFactory { options.addRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; options.addRoleNFTAddQuantity ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; options.addRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; - options.addRoleESDTModifyCreator ? args.push(new StringValue("ESDTRoleModifyCreator")) : 0; const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -346,7 +345,7 @@ export class TokenManagementTransactionsFactory { "ESDTNFTCreate", ...this.argSerializer.valuesToStrings([ new StringValue(options.tokenIdentifier), - new BigUIntValue(options.initialQuantity), + new BigUIntValue(options.initialQuantity ?? 1n), new StringValue(options.name), new BigUIntValue(options.royalties), new StringValue(options.hash), From d06690056d4f92913faed5139b4a904548ecb200 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 5 Mar 2025 12:09:09 +0200 Subject: [PATCH 192/214] Fix devnet tests --- .../smartContractTransactionsOutcomeParser.dev.net.spec.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts index a17bd3873..a76fe6b2c 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.dev.net.spec.ts @@ -1,4 +1,5 @@ import { assert } from "chai"; +import { Address } from "../core"; import { createDevnetProvider } from "../testutils/networkProviders"; import { SmartContractTransactionsOutcomeParser } from "./smartContractTransactionsOutcomeParser"; @@ -14,8 +15,8 @@ describe("test smart contract transactions outcome parser on devnet", () => { assert.equal(parsedGivenTransactionOnNetwork.returnCode, "ok"); assert.deepEqual(parsedGivenTransactionOnNetwork.contracts, [ { - address: "erd1qqqqqqqqqqqqqpgqpayq2es08gq8798xhnpr0kzgn7495qt5q6uqd7lpwf", - ownerAddress: "erd1tn62hjp72rznp8vq0lplva5csav6rccpqqdungpxtqz0g2hcq6uq9k4cc6", + address: Address.newFromBech32("erd1qqqqqqqqqqqqqpgqpayq2es08gq8798xhnpr0kzgn7495qt5q6uqd7lpwf"), + ownerAddress: Address.newFromBech32("erd1tn62hjp72rznp8vq0lplva5csav6rccpqqdungpxtqz0g2hcq6uq9k4cc6"), codeHash: Buffer.from("c876625ec34a04445cfd99067777ebe488afdbc6899cd958f4c1d36107ca02d9", "hex"), }, ]); From b5714cd5198e2c72e5c1e27560004d18c5170437 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 5 Mar 2025 12:23:19 +0200 Subject: [PATCH 193/214] Update gas limit --- src/core/transactionsFactoryConfig.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/transactionsFactoryConfig.ts b/src/core/transactionsFactoryConfig.ts index 117918813..d898fbb00 100644 --- a/src/core/transactionsFactoryConfig.ts +++ b/src/core/transactionsFactoryConfig.ts @@ -62,9 +62,9 @@ export class TransactionsFactoryConfig { this.gasLimitFreezing = 60000000n; this.gasLimitWiping = 60000000n; this.gasLimitEsdtNftCreate = 3000000n; - this.gasLimitEsdtNftUpdateAttributes = 500000n; - this.gasLimitEsdtNftAddQuantity = 500000n; - this.gasLimitEsdtNftBurn = 500000n; + this.gasLimitEsdtNftUpdateAttributes = 50000n; + this.gasLimitEsdtNftAddQuantity = 50000n; + this.gasLimitEsdtNftBurn = 50000n; this.gasLimitStorePerByte = 10000n; this.issueCost = 50000000000000000n; this.gasLimitEsdtModifyRoyalties = 60000000n; From a61b57af02fe679e0d4c62cc794353f6d79be3ae Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 5 Mar 2025 13:24:58 +0200 Subject: [PATCH 194/214] Deprecate Smart contract and code as not needed anymore --- src/abi/code.ts | 1 + src/abi/smartContract.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/abi/code.ts b/src/abi/code.ts index e7a8b68d2..dd3946052 100644 --- a/src/abi/code.ts +++ b/src/abi/code.ts @@ -2,6 +2,7 @@ const createHasher = require("blake2b"); const CODE_HASH_LENGTH = 32; /** + * * @deprecated Use the bytecode directly * Bytecode of a Smart Contract, as an abstraction. */ export class Code { diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 35605ea5c..1edda34b8 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -29,6 +29,8 @@ interface IAbi { } /** + * * @deprecated component. Use "SmartContractTransactionsFactory" or "SmartContractController", instead. + * * An abstraction for deploying and interacting with Smart Contracts. */ export class SmartContract implements ISmartContract { From 1222058609820082740d3009fe44da2c2a40f29d Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 5 Mar 2025 14:56:01 +0200 Subject: [PATCH 195/214] Add alias to AbiRegistry --- src/abi/interaction.local.net.spec.ts | 26 ++-- src/abi/interaction.spec.ts | 12 +- src/abi/nativeSerializer.spec.ts | 32 ++--- src/abi/smartContract.spec.ts | 7 +- .../{abiRegistry.spec.ts => abi.spec.ts} | 112 +++++++++--------- src/abi/typesystem/{abiRegistry.ts => abi.ts} | 18 ++- src/abi/typesystem/index.ts | 2 +- src/entrypoints/entrypoints.ts | 4 +- .../smartContractController.spec.ts | 4 +- src/smartContracts/smartContractController.ts | 6 +- .../smartContractTransactionsFactory.spec.ts | 6 +- .../smartContractTransactionsOutcomeParser.ts | 6 +- src/testutils/utils.ts | 8 +- .../transactionEventsParser.spec.ts | 4 +- .../transactionEventsParser.ts | 10 +- 15 files changed, 137 insertions(+), 120 deletions(-) rename src/abi/typesystem/{abiRegistry.spec.ts => abi.spec.ts} (59%) rename src/abi/typesystem/{abiRegistry.ts => abi.ts} (95%) diff --git a/src/abi/interaction.local.net.spec.ts b/src/abi/interaction.local.net.spec.ts index bd805c004..f5c8f8066 100644 --- a/src/abi/interaction.local.net.spec.ts +++ b/src/abi/interaction.local.net.spec.ts @@ -27,14 +27,14 @@ describe("test smart contract interactor", function () { it("should interact with 'answer' (local testnet) using the SmartContractTransactionsFactory", async function () { this.timeout(80000); - let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); + let abi = await loadAbiRegistry("src/testdata/answer.abi.json"); let network = await provider.getNetworkConfig(); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config, - abi: abiRegistry, + abi: abi, }); const bytecode = await promises.readFile("src/testdata/answer.wasm"); @@ -62,7 +62,7 @@ describe("test smart contract interactor", function () { const queryController = new SmartContractController({ chainID: "localnet", networkProvider: provider, - abi: abiRegistry, + abi: abi, }); let transactionOnNetwork = await transactionCompletionAwaiter.awaitCompleted(deployTxHash); let response = queryController.parseDeploy(transactionOnNetwork); @@ -112,12 +112,12 @@ describe("test smart contract interactor", function () { it("should interact with 'basic-features' (local testnet)", async function () { this.timeout(140000); - let abiRegistry = await loadAbiRegistry("src/testdata/basic-features.abi.json"); - let contract = new SmartContract({ abi: abiRegistry }); + let abi = await loadAbiRegistry("src/testdata/basic-features.abi.json"); + let contract = new SmartContract({ abi: abi }); let controller = new SmartContractController({ chainID: "localnet", networkProvider: provider, - abi: abiRegistry, + abi: abi, }); let network = await provider.getNetworkConfig(); @@ -251,16 +251,16 @@ describe("test smart contract interactor", function () { it("should interact with 'counter' (local testnet) using the SmartContractTransactionsFactory", async function () { this.timeout(120000); - let abiRegistry = await loadAbiRegistry("src/testdata/counter.abi.json"); + let abi = await loadAbiRegistry("src/testdata/counter.abi.json"); let network = await provider.getNetworkConfig(); const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config, - abi: abiRegistry, + abi: abi, }); - const parser = new SmartContractTransactionsOutcomeParser({ abi: abiRegistry }); + const parser = new SmartContractTransactionsOutcomeParser({ abi: abi }); const bytecode = await promises.readFile("src/testdata/counter.wasm"); alice.nonce = (await provider.getAccount(alice.address)).nonce; @@ -290,7 +290,7 @@ describe("test smart contract interactor", function () { const queryController = new SmartContractController({ chainID: "localnet", networkProvider: provider, - abi: abiRegistry, + abi: abi, }); let incrementTransaction = factory.createTransactionForExecute(alice.address, { @@ -339,8 +339,8 @@ describe("test smart contract interactor", function () { it("should interact with 'lottery-esdt' (local testnet) using the SmartContractTransactionsFactory", async function () { this.timeout(140000); - let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); - let parser = new SmartContractTransactionsOutcomeParser({ abi: abiRegistry }); + let abi = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); + let parser = new SmartContractTransactionsOutcomeParser({ abi: abi }); alice.nonce = (await provider.getAccount(alice.address)).nonce; let network = await provider.getNetworkConfig(); @@ -348,7 +348,7 @@ describe("test smart contract interactor", function () { const config = new TransactionsFactoryConfig({ chainID: network.chainID }); const factory = new SmartContractTransactionsFactory({ config: config, - abi: abiRegistry, + abi: abi, }); const bytecode = await promises.readFile("src/testdata/lottery-esdt.wasm"); diff --git a/src/abi/interaction.spec.ts b/src/abi/interaction.spec.ts index 40a3c361b..b7ed0a261 100644 --- a/src/abi/interaction.spec.ts +++ b/src/abi/interaction.spec.ts @@ -205,9 +205,9 @@ describe("test smart contract interactor", function () { it("should interact with 'answer'", async function () { this.timeout(30000); - let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json"); - let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); - let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry }); + let abi = await loadAbiRegistry("src/testdata/answer.abi.json"); + let contract = new SmartContract({ address: dummyAddress, abi: abi }); + let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abi }); let interaction = contract.methods.getUltimateAnswer().withGasLimit(543210n).withChainID("T"); @@ -338,9 +338,9 @@ describe("test smart contract interactor", function () { it("should interact with 'lottery-esdt'", async function () { this.timeout(30000); - let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); - let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry }); - let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry }); + let abi = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); + let contract = new SmartContract({ address: dummyAddress, abi: abi }); + let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abi }); let startInteraction = ( contract.methodsExplicit diff --git a/src/abi/nativeSerializer.spec.ts b/src/abi/nativeSerializer.spec.ts index 535c95cc0..548aa877f 100644 --- a/src/abi/nativeSerializer.spec.ts +++ b/src/abi/nativeSerializer.spec.ts @@ -3,7 +3,7 @@ import { assert } from "chai"; import { Address, ErrInvalidArgument } from "../core"; import { NativeSerializer } from "./nativeSerializer"; import { - AbiRegistry, + Abi, AddressType, AddressValue, BigUIntType, @@ -172,7 +172,7 @@ describe("test native serializer", () => { }); it("should handle optionals in a strict manner (but it does not)", async () => { - const endpoint = AbiRegistry.create({ + const endpoint = Abi.create({ endpoints: [ { name: "foo", @@ -222,7 +222,7 @@ describe("test native serializer", () => { }); it("should accept a mix between typed values and regular JavaScript objects (variadic, optionals)", async () => { - const endpoint = AbiRegistry.create({ + const endpoint = Abi.create({ endpoints: [ { name: "foo", @@ -271,7 +271,7 @@ describe("test native serializer", () => { }); it("should accept a mix between typed values and regular JavaScript objects (composite, optionals)", async () => { - const endpoint = AbiRegistry.create({ + const endpoint = Abi.create({ endpoints: [ { name: "foo", @@ -331,7 +331,7 @@ describe("test native serializer", () => { }); it("should accept a mix between typed values and regular JavaScript objects (tuples)", async () => { - const endpoint = AbiRegistry.create({ + const endpoint = Abi.create({ endpoints: [ { name: "foo", @@ -404,7 +404,7 @@ describe("test native serializer", () => { }); it("should accept managed decimals with constants and variable decimals", async () => { - const endpoint = AbiRegistry.create({ + const endpoint = Abi.create({ endpoints: [ { name: "foo", @@ -445,7 +445,7 @@ describe("test native serializer", () => { }); it("should accept no value for variadic types", async () => { - const endpoint = AbiRegistry.create({ + const endpoint = Abi.create({ endpoints: [ { name: "foo", @@ -474,7 +474,7 @@ describe("test native serializer", () => { }); it("should accept null or undefined for option types and optionals", async () => { - const endpoint = AbiRegistry.create({ + const endpoint = Abi.create({ endpoints: [ { name: "foo", @@ -502,7 +502,7 @@ describe("test native serializer", () => { }); it("should perform type inference (enums)", async () => { - const abiRegistry = AbiRegistry.create({ + const abi = Abi.create({ endpoints: [ { name: "foo", @@ -573,8 +573,8 @@ describe("test native serializer", () => { }, }); - const endpoint = abiRegistry.getEndpoint("foo"); - const enumType = abiRegistry.getEnum("MyEnum"); + const endpoint = abi.getEndpoint("foo"); + const enumType = abi.getEnum("MyEnum"); // Simple enum by discriminant const p0 = 0; @@ -604,7 +604,7 @@ describe("test native serializer", () => { }); it("should perform type inference (explicit-enums)", async () => { - const abiRegistry = AbiRegistry.create({ + const abi = Abi.create({ endpoints: [ { name: "foo", @@ -633,8 +633,8 @@ describe("test native serializer", () => { }, }); - const endpoint = abiRegistry.getEndpoint("foo"); - const enumType = abiRegistry.getExplicitEnum("OperationCompletionStatus"); + const endpoint = abi.getEndpoint("foo"); + const enumType = abi.getExplicitEnum("OperationCompletionStatus"); const enumString = "completed"; const typedValues = NativeSerializer.nativeToTypedValues([enumString], endpoint); @@ -644,7 +644,7 @@ describe("test native serializer", () => { }); it("should getArgumentsCardinality", async () => { - const abi = AbiRegistry.create({ + const abi = Abi.create({ endpoints: [ { name: "a", @@ -708,7 +708,7 @@ describe("test native serializer", () => { }); it("should accept a mixed of values for boolen type", async () => { - const endpoint = AbiRegistry.create({ + const endpoint = Abi.create({ endpoints: [ { name: "foo", diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index e2a10d45e..528ebf7bf 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -8,9 +8,10 @@ import { getTestWalletsPath, MarkCompleted, MockNetworkProvider, Wait } from ".. import { Code } from "./code"; import { ContractFunction } from "./function"; import { SmartContract } from "./smartContract"; -import { AbiRegistry, OptionalValue, U32Value, U8Value, VariadicValue } from "./typesystem"; +import { Abi, OptionalValue, U32Value, U8Value, VariadicValue } from "./typesystem"; import { BytesValue } from "./typesystem/bytes"; +// This will be deleted directly describe("test contract", () => { let provider = new MockNetworkProvider(); let chainID = "test"; @@ -202,7 +203,7 @@ describe("test contract", () => { // These parameters are exotic and, generally speaking, can be avoided in contracts: // https://docs.multiversx.com/developers/data/multi-values/ - const abi = AbiRegistry.create({ + const abi = Abi.create({ endpoints: [ { name: "foo", @@ -271,7 +272,7 @@ describe("test contract", () => { }); it("v13 should be stricter than v12 on variadic parameters (since NativeSerializer is used under the hood)", async () => { - const abi = AbiRegistry.create({ + const abi = Abi.create({ endpoints: [ { name: "foo", diff --git a/src/abi/typesystem/abiRegistry.spec.ts b/src/abi/typesystem/abi.spec.ts similarity index 59% rename from src/abi/typesystem/abiRegistry.spec.ts rename to src/abi/typesystem/abi.spec.ts index 216cddba2..b68a34219 100644 --- a/src/abi/typesystem/abiRegistry.spec.ts +++ b/src/abi/typesystem/abi.spec.ts @@ -12,29 +12,29 @@ import { StructType } from "./struct"; import { TokenIdentifierType } from "./tokenIdentifier"; import { VariadicType } from "./variadic"; -describe("test abi registry", () => { +describe("test abi", () => { it("load should also remap known to types", async () => { // Ultimate answer - let registry = await loadAbiRegistry("src/testdata/answer.abi.json"); - let getUltimateAnswer = registry.getEndpoint("getUltimateAnswer"); + let abi = await loadAbiRegistry("src/testdata/answer.abi.json"); + let getUltimateAnswer = abi.getEndpoint("getUltimateAnswer"); assert.instanceOf(getUltimateAnswer.output[0].type, I64Type); // Counter - registry = await loadAbiRegistry("src/testdata/counter.abi.json"); - let getCounter = registry.getEndpoint("get"); + abi = await loadAbiRegistry("src/testdata/counter.abi.json"); + let getCounter = abi.getEndpoint("get"); assert.instanceOf(getCounter.output[0].type, I64Type); // Lottery - registry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); - let start = registry.getEndpoint("start"); - let getStatus = registry.getEndpoint("status"); - let getLotteryInfo = registry.getEndpoint("getLotteryInfo"); + abi = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); + let start = abi.getEndpoint("start"); + let getStatus = abi.getEndpoint("status"); + let getLotteryInfo = abi.getEndpoint("getLotteryInfo"); // basic-features - registry = await loadAbiRegistry("src/testdata/basic-features.abi.json"); - let returnManagedDecimal = registry.getEndpoint("returns_egld_decimal"); - let returnsManagedDecimalSigned = registry.getEndpoint("managed_decimal_ln"); - let returnsManagedDecimalVariable = registry.getEndpoint("managed_decimal_addition_var"); + abi = await loadAbiRegistry("src/testdata/basic-features.abi.json"); + let returnManagedDecimal = abi.getEndpoint("returns_egld_decimal"); + let returnsManagedDecimalSigned = abi.getEndpoint("managed_decimal_ln"); + let returnsManagedDecimalVariable = abi.getEndpoint("managed_decimal_addition_var"); assert.isFalse(start.modifiers.isReadonly()); assert.isTrue(getStatus.modifiers.isReadonly()); @@ -78,8 +78,8 @@ describe("test abi registry", () => { "hex", ); - let registry = await loadAbiRegistry("src/testdata/multisig-full.abi.json"); - let performAction = registry.getEndpoint("getActionData"); + let abi = await loadAbiRegistry("src/testdata/multisig-full.abi.json"); + let performAction = abi.getEndpoint("getActionData"); assert.equal(performAction.output[0].type.getName(), "Action"); let result = bc.decodeTopLevel(buff, performAction.output[0].type); @@ -91,10 +91,10 @@ describe("test abi registry", () => { }); it("should load ABI containing arrayN and nested structs", async () => { - let registry = await loadAbiRegistry("src/testdata/array-in-nested-structs.abi.json"); - let dummyType = registry.getStruct("Dummy"); - let fooType = registry.getStruct("Foo"); - let barType = registry.getStruct("Bar"); + let abi = await loadAbiRegistry("src/testdata/array-in-nested-structs.abi.json"); + let dummyType = abi.getStruct("Dummy"); + let fooType = abi.getStruct("Foo"); + let barType = abi.getStruct("Bar"); let fooTypeFromBarType = barType.getFieldDefinition("foo")!.type; let dummyTypeFromFooTypeFromBarType = fooTypeFromBarType.getFieldDefinition("dummy")!.type; @@ -107,40 +107,40 @@ 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"); + const abi = await loadAbiRegistry("src/testdata/custom-types-out-of-order-a.abi.json"); - assert.deepEqual(registry.getStruct("EsdtTokenTransfer").getNamesOfDependencies(), [ + assert.deepEqual(abi.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"]); - assert.deepEqual(registry.getStruct("TypeC").getNamesOfDependencies(), ["u64"]); + assert.deepEqual(abi.getEnum("EsdtTokenType").getNamesOfDependencies(), []); + assert.deepEqual(abi.getStruct("TypeA").getNamesOfDependencies(), ["TypeB", "TypeC", "u64"]); + assert.deepEqual(abi.getStruct("TypeB").getNamesOfDependencies(), ["TypeC", "u64"]); + assert.deepEqual(abi.getStruct("TypeC").getNamesOfDependencies(), ["u64"]); }); 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"); + const abi = await loadAbiRegistry("src/testdata/custom-types-out-of-order-b.abi.json"); - assert.deepEqual(registry.getStruct("EsdtTokenTransfer").getNamesOfDependencies(), [ + assert.deepEqual(abi.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"]); - assert.deepEqual(registry.getStruct("TypeC").getNamesOfDependencies(), ["u64"]); + assert.deepEqual(abi.getEnum("EsdtTokenType").getNamesOfDependencies(), []); + assert.deepEqual(abi.getStruct("TypeA").getNamesOfDependencies(), ["TypeB", "TypeC", "u64"]); + assert.deepEqual(abi.getStruct("TypeB").getNamesOfDependencies(), ["TypeC", "u64"]); + assert.deepEqual(abi.getStruct("TypeC").getNamesOfDependencies(), ["u64"]); }); it("should load ABI when custom types are out of order (community example: c)", async () => { - const registry = await loadAbiRegistry("src/testdata/custom-types-out-of-order-c.abi.json"); + const abi = await loadAbiRegistry("src/testdata/custom-types-out-of-order-c.abi.json"); - assert.lengthOf(registry.customTypes, 5); - assert.deepEqual(registry.getStruct("LoanCreateOptions").getNamesOfDependencies(), [ + assert.lengthOf(abi.customTypes, 5); + assert.deepEqual(abi.getStruct("LoanCreateOptions").getNamesOfDependencies(), [ "BigUint", "Address", "TokenIdentifier", @@ -150,10 +150,10 @@ describe("test abi registry", () => { }); 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"); + const abi = await loadAbiRegistry("src/testdata/custom-types-out-of-order-d.abi.json"); - assert.lengthOf(registry.customTypes, 12); - assert.deepEqual(registry.getStruct("AuctionItem").getNamesOfDependencies(), [ + assert.lengthOf(abi.customTypes, 12); + assert.deepEqual(abi.getStruct("AuctionItem").getNamesOfDependencies(), [ "u64", "Address", "BigUint", @@ -166,36 +166,36 @@ describe("test abi registry", () => { }); it("should load ABI with counted-variadic", async () => { - const registry = await loadAbiRegistry("src/testdata/counted-variadic.abi.json"); - const dummyType = registry.getStruct("Dummy"); - - assert.deepEqual(registry.getEndpoint("foo").input[0].type, new VariadicType(dummyType, true)); - assert.deepEqual(registry.getEndpoint("bar").input[0].type, new VariadicType(new U32Type(), true)); - assert.deepEqual(registry.getEndpoint("bar").input[1].type, new VariadicType(new BytesType(), true)); - assert.deepEqual(registry.getEndpoint("bar").output[0].type, new VariadicType(new U32Type(), true)); - assert.deepEqual(registry.getEndpoint("bar").output[1].type, new VariadicType(new BytesType(), true)); + const abi = await loadAbiRegistry("src/testdata/counted-variadic.abi.json"); + const dummyType = abi.getStruct("Dummy"); + + assert.deepEqual(abi.getEndpoint("foo").input[0].type, new VariadicType(dummyType, true)); + assert.deepEqual(abi.getEndpoint("bar").input[0].type, new VariadicType(new U32Type(), true)); + assert.deepEqual(abi.getEndpoint("bar").input[1].type, new VariadicType(new BytesType(), true)); + assert.deepEqual(abi.getEndpoint("bar").output[0].type, new VariadicType(new U32Type(), true)); + assert.deepEqual(abi.getEndpoint("bar").output[1].type, new VariadicType(new BytesType(), true)); }); it("should load ABI wih events", async () => { - const registry = await loadAbiRegistry("src/testdata/esdt-safe.abi.json"); + const abi = await loadAbiRegistry("src/testdata/esdt-safe.abi.json"); - assert.lengthOf(registry.events, 8); + assert.lengthOf(abi.events, 8); - const depositEvent = registry.getEvent("deposit"); + const depositEvent = abi.getEvent("deposit"); assert.deepEqual(depositEvent.inputs[0].type, new AddressType()); - assert.deepEqual(depositEvent.inputs[1].type, new ListType(registry.getCustomType("EsdtTokenPayment"))); - assert.deepEqual(depositEvent.inputs[2].type, registry.getCustomType("DepositEvent")); + assert.deepEqual(depositEvent.inputs[1].type, new ListType(abi.getCustomType("EsdtTokenPayment"))); + assert.deepEqual(depositEvent.inputs[2].type, abi.getCustomType("DepositEvent")); - const setStatusEvent = registry.getEvent("setStatusEvent"); + const setStatusEvent = abi.getEvent("setStatusEvent"); assert.deepEqual(setStatusEvent.inputs[0].type, new U64Type()); assert.deepEqual(setStatusEvent.inputs[1].type, new U64Type()); - assert.deepEqual(setStatusEvent.inputs[2].type, registry.getCustomType("TransactionStatus")); + assert.deepEqual(setStatusEvent.inputs[2].type, abi.getCustomType("TransactionStatus")); }); it("should load ABI explicit-enum", async () => { - const registry = await loadAbiRegistry("src/testdata/basic-features.abi.json"); + const abi = await loadAbiRegistry("src/testdata/basic-features.abi.json"); - const enumType = registry.getExplicitEnum("OperationCompletionStatus"); + const enumType = abi.getExplicitEnum("OperationCompletionStatus"); assert.deepEqual(enumType.variants[0].name, "completed"); @@ -203,9 +203,9 @@ describe("test abi registry", () => { }); it("should load abi with title for endpoint", async () => { - const registry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); + const abi = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json"); - const endpoint = registry.getEndpoint("createLotteryPool"); + const endpoint = abi.getEndpoint("createLotteryPool"); assert.equal(endpoint.title, "Create lottery pool"); }); diff --git a/src/abi/typesystem/abiRegistry.ts b/src/abi/typesystem/abi.ts similarity index 95% rename from src/abi/typesystem/abiRegistry.ts rename to src/abi/typesystem/abi.ts index 984f45659..1c462ede8 100644 --- a/src/abi/typesystem/abiRegistry.ts +++ b/src/abi/typesystem/abi.ts @@ -18,7 +18,7 @@ export class AbiRegistry { readonly customTypes: CustomType[] = []; readonly events: EventDefinition[] = []; - private constructor(options: { + protected constructor(options: { name: string; constructorDefinition: EndpointDefinition; upgradeConstructorDefinition?: EndpointDefinition; @@ -240,3 +240,19 @@ function mapEvent(event: EventDefinition, mapper: TypeMapper): EventDefinition { return new EventDefinition(event.identifier, newInputs); } + +export class Abi extends AbiRegistry { + /** + * + */ + constructor(options: { + name: string; + constructorDefinition: EndpointDefinition; + upgradeConstructorDefinition?: EndpointDefinition; + endpoints: EndpointDefinition[]; + customTypes: CustomType[]; + events?: EventDefinition[]; + }) { + super(options); + } +} diff --git a/src/abi/typesystem/index.ts b/src/abi/typesystem/index.ts index f05527ba3..e98aff96f 100644 --- a/src/abi/typesystem/index.ts +++ b/src/abi/typesystem/index.ts @@ -3,7 +3,7 @@ * @module typesystem */ -export * from "./abiRegistry"; +export * from "./abi"; export * from "./address"; export * from "./algebraic"; export * from "./boolean"; diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 73f1b95d6..5a75498da 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -1,4 +1,4 @@ -import { AbiRegistry } from "../abi"; +import { Abi } from "../abi"; import { AccountController, AccountTransactionsFactory } from "../accountManagement"; import { Account } from "../accounts"; import { IAccount } from "../accounts/interfaces"; @@ -106,7 +106,7 @@ class NetworkEntrypoint { return new AccountTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: this.chainId }) }); } - createSmartContractController(abi?: AbiRegistry): SmartContractController { + createSmartContractController(abi?: Abi): SmartContractController { return new SmartContractController({ chainID: this.chainId, networkProvider: this.networkProvider, abi }); } diff --git a/src/smartContracts/smartContractController.spec.ts b/src/smartContracts/smartContractController.spec.ts index eadf1fb16..a6b36a0e7 100644 --- a/src/smartContracts/smartContractController.spec.ts +++ b/src/smartContracts/smartContractController.spec.ts @@ -1,6 +1,6 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { AbiRegistry, BigUIntValue, BooleanValue, BytesValue, Tuple, U16Value, U64Value } from "../abi"; +import { Abi, BigUIntValue, BooleanValue, BytesValue, Tuple, U16Value, U64Value } from "../abi"; import { Address, SmartContractQueryResponse } from "../core"; import { MockNetworkProvider, loadAbiRegistry } from "../testutils"; import { bigIntToBuffer } from "../tokenOperations/codec"; @@ -94,7 +94,7 @@ describe("test smart contract queries controller", () => { }); it("works with ABI, with mixed arguments", async function () { - const abi = AbiRegistry.create({ + const abi = Abi.create({ endpoints: [ { name: "bar", diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index 5a7be445d..fd370f410 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -1,4 +1,4 @@ -import { AbiRegistry, ArgSerializer, isTyped, NativeSerializer } from "../abi"; +import { Abi, ArgSerializer, isTyped, NativeSerializer } from "../abi"; import { IAccount } from "../accounts/interfaces"; import { Address } from "../core"; import { Err, ErrSmartContractQuery } from "../core/errors"; @@ -19,9 +19,9 @@ export class SmartContractController { private transactionWatcher: TransactionWatcher; private txComputer: TransactionComputer; private networkProvider: INetworkProvider; - private abi?: AbiRegistry; + private abi?: Abi; - constructor(options: { chainID: string; networkProvider: INetworkProvider; abi?: AbiRegistry }) { + constructor(options: { chainID: string; networkProvider: INetworkProvider; abi?: Abi }) { this.factory = new SmartContractTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: options.chainID }), abi: options.abi, diff --git a/src/smartContracts/smartContractTransactionsFactory.spec.ts b/src/smartContracts/smartContractTransactionsFactory.spec.ts index 546f76465..217d2b511 100644 --- a/src/smartContracts/smartContractTransactionsFactory.spec.ts +++ b/src/smartContracts/smartContractTransactionsFactory.spec.ts @@ -1,5 +1,5 @@ import { assert } from "chai"; -import { AbiRegistry, Code, U32Value } from "../abi"; +import { Abi, Code, U32Value } from "../abi"; import { Address, Err, Token, TokenTransfer, TransactionsFactoryConfig } from "../core"; import { loadAbiRegistry, loadContractCode } from "../testutils/utils"; import { SmartContractTransactionsFactory } from "./smartContractTransactionsFactory"; @@ -9,7 +9,7 @@ describe("test smart contract transactions factory", function () { let factory: SmartContractTransactionsFactory; let abiAwareFactory: SmartContractTransactionsFactory; let bytecode: Code; - let abi: AbiRegistry; + let abi: Abi; before(async function () { factory = new SmartContractTransactionsFactory({ @@ -427,7 +427,7 @@ describe("test smart contract transactions factory", function () { }); it("should create 'Transaction' for upgrade, when ABI is available (with fallbacks)", async function () { - const abi = AbiRegistry.create({ + const abi = Abi.create({ upgradeConstructor: { inputs: [ { diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index aadfc484e..5ff7db7be 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -1,4 +1,4 @@ -import { AbiRegistry, ArgSerializer } from "../abi"; +import { Abi, ArgSerializer } from "../abi"; import { Address } from "../core/address"; import { ARGUMENTS_SEPARATOR } from "../core/constants"; import { Err } from "../core/errors"; @@ -14,9 +14,9 @@ enum Events { } export class SmartContractTransactionsOutcomeParser { - private readonly abi?: AbiRegistry; + private readonly abi?: Abi; - constructor(options?: { abi?: AbiRegistry }) { + constructor(options?: { abi?: Abi }) { this.abi = options?.abi; } diff --git a/src/testutils/utils.ts b/src/testutils/utils.ts index ce2f96c1a..6c185c6bb 100644 --- a/src/testutils/utils.ts +++ b/src/testutils/utils.ts @@ -1,7 +1,7 @@ import * as fs from "fs"; import { PathLike } from "fs"; import { resolve } from "path"; -import { AbiRegistry, Code, SmartContract, TypedValue } from "../abi"; +import { Abi, Code, SmartContract, TypedValue } from "../abi"; import { Account } from "../accounts"; import { Transaction } from "../core/transaction"; import { getAxios } from "../core/utils"; @@ -55,17 +55,17 @@ export async function loadContractCode(path: PathLike): Promise { return Code.fromBuffer(buffer); } -export async function loadAbiRegistry(path: PathLike): Promise { +export async function loadAbiRegistry(path: PathLike): Promise { if (isOnBrowserTests()) { const axios = await getAxios(); let response: any = await axios.default.get(path.toString()); - return AbiRegistry.create(response.data); + return Abi.create(response.data); } // Load from files let jsonContent: string = await fs.promises.readFile(path, { encoding: "utf8" }); let json = JSON.parse(jsonContent); - return AbiRegistry.create(json); + return Abi.create(json); } export function isOnBrowserTests() { diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts index 52a48853d..ed3676274 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.spec.ts @@ -1,6 +1,6 @@ import BigNumber from "bignumber.js"; import { assert } from "chai"; -import { AbiRegistry } from "../abi"; +import { Abi } from "../abi"; import { Address, TransactionEvent, TransactionLogs, TransactionOnNetwork } from "../core"; import { b64TopicsToBytes, loadAbiRegistry } from "../testutils"; import { findEventsByFirstTopic, SmartContractResult } from "./resources"; @@ -153,7 +153,7 @@ describe("test transaction events parser", () => { }); it("parses event (with multi-values)", async function () { - const abi = AbiRegistry.create({ + const abi = Abi.create({ events: [ { identifier: "doFoobar", diff --git a/src/transactionsOutcomeParsers/transactionEventsParser.ts b/src/transactionsOutcomeParsers/transactionEventsParser.ts index c73f3e26a..4cd5ed945 100644 --- a/src/transactionsOutcomeParsers/transactionEventsParser.ts +++ b/src/transactionsOutcomeParsers/transactionEventsParser.ts @@ -1,11 +1,11 @@ -import { AbiRegistry, ArgSerializer } from "../abi"; +import { Abi, ArgSerializer } from "../abi"; import { TransactionEvent } from "../core/transactionEvents"; export class TransactionEventsParser { - private readonly abi: AbiRegistry; + private readonly abi: Abi; private readonly firstTopicIsIdentifier: boolean; - constructor(options: { abi: AbiRegistry; firstTopicIsIdentifier?: boolean }) { + constructor(options: { abi: Abi; firstTopicIsIdentifier?: boolean }) { this.abi = options.abi; // By default, we consider that the first topic is the event identifier. @@ -41,14 +41,14 @@ export class TransactionEventsParser { const argsSerializer = new ArgSerializer(); // "Indexed" ABI "event.inputs" correspond to "event.topics[1:]": - const indexedInputs = eventDefinition.inputs.filter((input) => input.indexed); + const indexedInputs = eventDefinition.inputs.filter((input: { indexed: any }) => input.indexed); const decodedTopics = argsSerializer.buffersToValues(topics, indexedInputs); for (let i = 0; i < indexedInputs.length; i++) { result[indexedInputs[i].name] = decodedTopics[i].valueOf(); } // "Non-indexed" ABI "event.inputs" correspond to "event.data": - const nonIndexedInputs = eventDefinition.inputs.filter((input) => !input.indexed); + const nonIndexedInputs = eventDefinition.inputs.filter((input: { indexed: any }) => !input.indexed); const decodedDataParts = argsSerializer.buffersToValues(dataItems, nonIndexedInputs); for (let i = 0; i < nonIndexedInputs.length; i++) { result[nonIndexedInputs[i].name] = decodedDataParts[i]?.valueOf(); From 20981b89516217dacbc7b6366f7bcc275ad5af10 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 5 Mar 2025 15:12:33 +0200 Subject: [PATCH 196/214] Remove unused comment --- src/abi/smartContract.spec.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/abi/smartContract.spec.ts b/src/abi/smartContract.spec.ts index 528ebf7bf..273783100 100644 --- a/src/abi/smartContract.spec.ts +++ b/src/abi/smartContract.spec.ts @@ -11,7 +11,6 @@ import { SmartContract } from "./smartContract"; import { Abi, OptionalValue, U32Value, U8Value, VariadicValue } from "./typesystem"; import { BytesValue } from "./typesystem/bytes"; -// This will be deleted directly describe("test contract", () => { let provider = new MockNetworkProvider(); let chainID = "test"; From da2ffe8cb5c43447b78d3f5748136148ecdb0449 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 5 Mar 2025 17:05:34 +0200 Subject: [PATCH 197/214] Add extra gas in case we have relayer and guardian --- src/accountManagement/accountController.ts | 9 +++-- src/core/baseController.ts | 14 ++++++++ src/core/constants.ts | 2 ++ src/core/index.ts | 1 + src/delegation/delegationController.ts | 24 +++++++++++-- src/smartContracts/smartContractController.ts | 8 +++-- .../tokenManagementController.ts | 35 +++++++++++++++++-- src/transfers/transfersControllers.ts | 8 +++-- 8 files changed, 91 insertions(+), 10 deletions(-) create mode 100644 src/core/baseController.ts diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index e4cb9c455..00599fba4 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -1,16 +1,17 @@ import { IAccount } from "../accounts/interfaces"; -import { Address } from "../core"; +import { Address, BaseController } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; import { SaveKeyValueInput, SetGuardianInput } from "./resources"; -export class AccountController { +export class AccountController extends BaseController { private factory: AccountTransactionsFactory; private txComputer: TransactionComputer; constructor(options: { chainID: string }) { + super(); this.factory = new AccountTransactionsFactory({ config: new TransactionsFactoryConfig(options), }); @@ -27,6 +28,7 @@ export class AccountController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -42,6 +44,7 @@ export class AccountController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -55,6 +58,7 @@ export class AccountController { const transaction = this.factory.createTransactionForGuardingAccount(sender.address); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -70,6 +74,7 @@ export class AccountController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; diff --git a/src/core/baseController.ts b/src/core/baseController.ts new file mode 100644 index 000000000..43db3b191 --- /dev/null +++ b/src/core/baseController.ts @@ -0,0 +1,14 @@ +import { Transaction } from "../core/transaction"; +import { EXTRA_GAS_LIMIT_FOR_GUARDED_TRANSACTIONS, EXTRA_GAS_LIMIT_FOR_RELAYED_TRANSACTIONS } from "./constants"; + +export class BaseController { + addExtraGasLimitIfRequired(transaction: Transaction): void { + if (transaction.guardian && !transaction.guardian.isEmpty()) { + transaction.gasLimit += BigInt(EXTRA_GAS_LIMIT_FOR_GUARDED_TRANSACTIONS); + } + + if (transaction.relayer && !transaction.relayer.isEmpty()) { + transaction.gasLimit += BigInt(EXTRA_GAS_LIMIT_FOR_RELAYED_TRANSACTIONS); + } + } +} diff --git a/src/core/constants.ts b/src/core/constants.ts index d62de0fa7..765ed156c 100644 --- a/src/core/constants.ts +++ b/src/core/constants.ts @@ -26,3 +26,5 @@ export const SDK_JS_SIGNER = "sdk-js"; export const UNKNOWN_SIGNER = "unknown"; export const EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER = "EGLD-000000"; +export const EXTRA_GAS_LIMIT_FOR_GUARDED_TRANSACTIONS = 50_000; +export const EXTRA_GAS_LIMIT_FOR_RELAYED_TRANSACTIONS = 50_000; diff --git a/src/core/index.ts b/src/core/index.ts index ce95f33f4..72d825d07 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -2,6 +2,7 @@ require("./globals"); export * from "./address"; export * from "./asyncTimer"; +export * from "./baseController"; export * from "./config"; export * from "./errors"; export * from "./interface"; diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index f0c0f0f3e..1392d3986 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -1,5 +1,5 @@ import { IAccount } from "../accounts/interfaces"; -import { Address } from "../core"; +import { Address, BaseController } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; @@ -10,13 +10,14 @@ import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; import * as resources from "./resources"; -export class DelegationController { +export class DelegationController extends BaseController { private transactionAwaiter: TransactionWatcher; private factory: DelegationTransactionsFactory; private parser: DelegationTransactionsOutcomeParser; private txComputer: TransactionComputer; constructor(options: { chainID: string; networkProvider: INetworkProvider }) { + super(); this.transactionAwaiter = new TransactionWatcher(options.networkProvider); this.factory = new DelegationTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: options.chainID }), @@ -35,6 +36,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -59,6 +61,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -74,6 +77,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -89,6 +93,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -104,6 +109,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -119,6 +125,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -134,6 +141,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -149,6 +157,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -164,6 +173,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -179,6 +189,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -194,6 +205,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -212,6 +224,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -230,6 +243,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -245,6 +259,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -260,6 +275,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -275,6 +291,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -290,6 +307,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -305,6 +323,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -321,6 +340,7 @@ export class DelegationController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index fd370f410..e36551243 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -1,6 +1,6 @@ import { Abi, ArgSerializer, isTyped, NativeSerializer } from "../abi"; import { IAccount } from "../accounts/interfaces"; -import { Address } from "../core"; +import { Address, BaseController } from "../core"; import { Err, ErrSmartContractQuery } from "../core/errors"; import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../core/smartContractQuery"; import { Transaction } from "../core/transaction"; @@ -13,7 +13,7 @@ import { SmartContractTransactionsOutcomeParser } from "../transactionsOutcomePa import * as resources from "./resources"; import { SmartContractTransactionsFactory } from "./smartContractTransactionsFactory"; -export class SmartContractController { +export class SmartContractController extends BaseController { private factory: SmartContractTransactionsFactory; private parser: SmartContractTransactionsOutcomeParser; private transactionWatcher: TransactionWatcher; @@ -22,6 +22,7 @@ export class SmartContractController { private abi?: Abi; constructor(options: { chainID: string; networkProvider: INetworkProvider; abi?: Abi }) { + super(); this.factory = new SmartContractTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: options.chainID }), abi: options.abi, @@ -43,6 +44,7 @@ export class SmartContractController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -67,6 +69,7 @@ export class SmartContractController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -82,6 +85,7 @@ export class SmartContractController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index e63821477..da006224f 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -1,5 +1,5 @@ import { IAccount } from "../accounts/interfaces"; -import { Address } from "../core"; +import { Address, BaseController } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; @@ -10,13 +10,14 @@ import { TokenManagementTransactionsOutcomeParser } from "../transactionsOutcome import * as resources from "./resources"; import { TokenManagementTransactionsFactory } from "./tokenManagementTransactionsFactory"; -export class TokenManagementController { +export class TokenManagementController extends BaseController { private factory: TokenManagementTransactionsFactory; private transactionAwaiter: TransactionWatcher; private txComputer: TransactionComputer; private parser: TokenManagementTransactionsOutcomeParser; constructor(options: { chainID: string; networkProvider: INetworkProvider }) { + super(); this.factory = new TokenManagementTransactionsFactory({ config: new TransactionsFactoryConfig({ chainID: options.chainID }), }); @@ -35,6 +36,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -59,6 +61,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -83,6 +86,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -107,6 +111,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -131,6 +136,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -155,6 +161,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -179,6 +186,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -203,6 +211,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -230,6 +239,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -257,6 +267,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -281,6 +292,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -305,6 +317,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -329,6 +342,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -353,6 +367,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -377,6 +392,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -401,6 +417,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -425,6 +442,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -449,6 +467,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -473,6 +492,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -497,6 +517,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -521,6 +542,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -545,6 +567,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -569,6 +592,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -593,6 +617,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -617,6 +642,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -641,6 +667,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -665,6 +692,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -689,6 +717,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -709,6 +738,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -733,6 +763,7 @@ export class TokenManagementController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index 55f5d446d..f06f68bef 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -1,16 +1,17 @@ import { IAccount } from "../accounts/interfaces"; -import { Address } from "../core"; +import { Address, BaseController } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionComputer } from "../core/transactionComputer"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import * as resources from "./resources"; import { TransferTransactionsFactory } from "./transferTransactionsFactory"; -export class TransfersController { +export class TransfersController extends BaseController { private factory: TransferTransactionsFactory; private txComputer: TransactionComputer; constructor(options: { chainID: string }) { + super(); this.factory = new TransferTransactionsFactory({ config: new TransactionsFactoryConfig(options) }); this.txComputer = new TransactionComputer(); } @@ -25,6 +26,7 @@ export class TransfersController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -40,6 +42,7 @@ export class TransfersController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; @@ -55,6 +58,7 @@ export class TransfersController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); return transaction; From 0c1b3510550d07439cddc4812636ed3caa59c7a4 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 6 Mar 2025 10:27:32 +0200 Subject: [PATCH 198/214] Add missing test --- src/core/tokens.spec.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/core/tokens.spec.ts b/src/core/tokens.spec.ts index 28118e261..08f75e446 100644 --- a/src/core/tokens.spec.ts +++ b/src/core/tokens.spec.ts @@ -46,6 +46,22 @@ describe("test tokens and token computer", async () => { const fungibleTokenIdentifier = "FNG-123456"; identifier = tokenComputer.extractIdentifierFromExtendedIdentifier(fungibleTokenIdentifier); assert.equal(identifier, "FNG-123456"); + + const numericTokenTicker = "2065-65td7s"; + identifier = tokenComputer.extractIdentifierFromExtendedIdentifier(numericTokenTicker); + assert.equal(identifier, "2065-65td7s"); + + const numericTokenTickerWithNonce = "2065-65td7s-01"; + identifier = tokenComputer.extractIdentifierFromExtendedIdentifier(numericTokenTickerWithNonce); + assert.equal(identifier, "2065-65td7s"); + + const numericTokenTickerWithPrefix = "t0-2065-65td7s"; + identifier = tokenComputer.extractIdentifierFromExtendedIdentifier(numericTokenTickerWithPrefix); + assert.equal(identifier, "t0-2065-65td7s"); + + const numericTokenTickerWithPrefixAndNonce = "t0-2065-65td7s"; + identifier = tokenComputer.extractIdentifierFromExtendedIdentifier(numericTokenTickerWithPrefixAndNonce); + assert.equal(identifier, "t0-2065-65td7s"); }); it("should fail if prefix longer than expected", async () => { From f43060569fa614e356aaba32beed36e4e4716ee1 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 6 Mar 2025 11:56:00 +0200 Subject: [PATCH 199/214] Add missing methods on token management factory and controller --- src/tokenManagement/resources.ts | 32 ++--- .../tokenManagementController.ts | 98 +++++++++++++++ .../tokenManagementTransactionFactory.spec.ts | 76 ++++++++++-- .../tokenManagementTransactionsFactory.ts | 112 +++++++++++++++--- 4 files changed, 273 insertions(+), 45 deletions(-) diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index d3f7e0fb2..d7a050b66 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -21,31 +21,31 @@ export type IssueInput = { export type FungibleSpecialRoleInput = { user: Address; tokenIdentifier: string; - addRoleLocalMint: boolean; - addRoleLocalBurn: boolean; - addRoleESDTTransferRole: boolean; + localMintRole: boolean; + localBurnRole: boolean; + ESDTTransferRole: boolean; }; export type SemiFungibleSpecialRoleInput = { user: Address; tokenIdentifier: string; - addRoleNFTCreate: boolean; - addRoleNFTBurn: boolean; - addRoleNFTAddQuantity: boolean; - addRoleESDTTransferRole: boolean; + NFTCreateRole: boolean; + NFTBurnRole: boolean; + NFTAddQuantityRole: boolean; + ESDTTransferRole: boolean; }; export type SpecialRoleInput = { user: Address; tokenIdentifier: string; - addRoleNFTCreate: boolean; - addRoleNFTBurn: boolean; - addRoleNFTUpdateAttributes: boolean; - addRoleNFTAddURI: boolean; - addRoleESDTTransferRole: boolean; - addRoleESDTModifyCreator?: boolean; - addRoleNFTRecreate?: boolean; - addRoleESDTSetNewURI?: boolean; - addRoleESDTModifyRoyalties?: boolean; + NFTCreateRole: boolean; + NFTBurnRole: boolean; + NFTUpdateAttributesRole: boolean; + NFTAddURIRole: boolean; + ESDTTransferRole: boolean; + ESDTModifyCreatorRole?: boolean; + NFTRecreateRole?: boolean; + ESDTSetNewURIRole?: boolean; + ESDTModifyRoyaltiesRole?: boolean; }; export type MintInput = { diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index da006224f..d59b2af98 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -226,6 +226,25 @@ export class TokenManagementController extends BaseController { return this.parser.parseSetSpecialRole(transactionOnNetwork); } + async createTransactionForunsettingSpecialRoleOnFungibleToken( + sender: IAccount, + nonce: bigint, + options: resources.FungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + ): Promise { + const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnFungibleToken( + sender.address, + options, + ); + + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); + transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + async createTransactionForSettingSpecialRoleOnSemiFungibleToken( sender: IAccount, nonce: bigint, @@ -254,6 +273,66 @@ export class TokenManagementController extends BaseController { return this.parser.parseSetSpecialRole(transactionOnNetwork); } + async createTransactionForUnsettingSpecialRoleOnSemiFungibleToken( + sender: IAccount, + nonce: bigint, + options: resources.SemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + ): Promise { + const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnSemiFungibleToken( + sender.address, + options, + ); + + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); + transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async createTransactionForSettingSpecialRoleOnMetaESDT( + sender: IAccount, + nonce: bigint, + options: resources.SemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + ): Promise { + const transaction = this.factory.createTransactionForSettingSpecialRoleOnMetaESDT(sender.address, options); + + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); + transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + + async awaitCompletedSetSpecialRoleOnMetaESDTToken(txHash: string): Promise { + const transaction = await this.transactionAwaiter.awaitCompleted(txHash); + return this.parseSetSpecialRoleOnSemiFungibleToken(transaction); + } + + parseSetSpecialRoleOnMetaESDTToken(transactionOnNetwork: TransactionOnNetwork): resources.SpecialRoleOutput[] { + return this.parser.parseSetSpecialRole(transactionOnNetwork); + } + + async createTransactionForUnsettingSpecialRoleOnMetaESDT( + sender: IAccount, + nonce: bigint, + options: resources.SemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + ): Promise { + const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnMetaESDT(sender.address, options); + + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); + transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + async createTransactionForSettingSpecialRoleOnNonFungibleToken( sender: IAccount, nonce: bigint, @@ -282,6 +361,25 @@ export class TokenManagementController extends BaseController { return this.parser.parseSetSpecialRole(transactionOnNetwork); } + async createTransactionForUnsettingSpecialRoleOnNonFungibleToken( + sender: IAccount, + nonce: bigint, + options: resources.SpecialRoleInput & { guardian?: Address; relayer?: Address }, + ): Promise { + const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnNonFungibleToken( + sender.address, + options, + ); + + transaction.guardian = options.guardian ?? Address.empty(); + transaction.relayer = options.relayer ?? Address.empty(); + transaction.nonce = nonce; + this.addExtraGasLimitIfRequired(transaction); + transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + + return transaction; + } + async createTransactionForCreatingNft( sender: IAccount, nonce: bigint, diff --git a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts index a339af6a7..b600661d6 100644 --- a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts @@ -137,9 +137,9 @@ describe("test token management transactions factory", () => { { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - addRoleLocalMint: true, - addRoleLocalBurn: false, - addRoleESDTTransferRole: false, + localMintRole: true, + localBurnRole: false, + ESDTTransferRole: false, }, ); @@ -154,15 +154,38 @@ describe("test token management transactions factory", () => { assert.equal(transaction.value, 0n); }); + it("should create 'Transaction' for unsetting special role on fungible token", () => { + const transaction = tokenManagementFactory.createTransactionForUnsettingSpecialRoleOnFungibleToken( + frank.address, + { + user: grace.address, + tokenIdentifier: "FRANK-11ce3e", + localMintRole: true, + localBurnRole: false, + ESDTTransferRole: false, + }, + ); + + assert.deepEqual( + transaction.data, + Buffer.from( + "unSetSpecialRole@4652414e4b2d313163653365@1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13@45534454526f6c654c6f63616c4d696e74", + ), + ); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); + assert.equal(transaction.value, 0n); + }); + it("should create 'Transaction' for setting all special roles on fungible token", () => { const transaction = tokenManagementFactory.createTransactionForSettingSpecialRoleOnFungibleToken( frank.address, { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - addRoleLocalMint: true, - addRoleLocalBurn: true, - addRoleESDTTransferRole: true, + localMintRole: true, + localBurnRole: true, + ESDTTransferRole: true, }, ); @@ -183,13 +206,13 @@ describe("test token management transactions factory", () => { { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - addRoleNFTCreate: true, - addRoleNFTBurn: false, - addRoleNFTUpdateAttributes: true, - addRoleNFTAddURI: true, - addRoleESDTTransferRole: false, - addRoleESDTModifyCreator: true, - addRoleNFTRecreate: true, + NFTCreateRole: true, + NFTBurnRole: false, + NFTUpdateAttributesRole: true, + NFTAddURIRole: true, + ESDTTransferRole: false, + ESDTModifyCreatorRole: true, + NFTRecreateRole: true, }, ); @@ -204,6 +227,33 @@ describe("test token management transactions factory", () => { assert.equal(transaction.value, 0n); }); + it("should create 'Transaction' for unsetting special role on non-fungible token", () => { + const transaction = tokenManagementFactory.createTransactionForUnsettingSpecialRoleOnNonFungibleToken( + frank.address, + { + user: grace.address, + tokenIdentifier: "FRANK-11ce3e", + NFTCreateRole: true, + NFTBurnRole: false, + NFTUpdateAttributesRole: true, + NFTAddURIRole: true, + ESDTTransferRole: false, + ESDTModifyCreatorRole: true, + NFTRecreateRole: true, + }, + ); + + assert.deepEqual( + transaction.data, + Buffer.from( + "unSetSpecialRole@4652414e4b2d313163653365@1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13@45534454526f6c654e4654437265617465@45534454526f6c654e465455706461746541747472696275746573@45534454526f6c654e4654416464555249@45534454526f6c654d6f6469667943726561746f72@45534454526f6c654e46545265637265617465", + ), + ); + assert.deepEqual(transaction.sender, frank.address); + assert.deepEqual(transaction.receiver, Address.newFromHex(ESDT_CONTRACT_ADDRESS_HEX, config.addressHrp)); + assert.equal(transaction.value, 0n); + }); + it("should create 'Transaction' for creating nft", () => { const transaction = tokenManagementFactory.createTransactionForCreatingNFT(grace.address, { tokenIdentifier: "FRANK-aa9e8d", diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index e715a7748..2d46eadc2 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -266,9 +266,9 @@ export class TokenManagementTransactionsFactory { ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.addRoleLocalMint ? args.push(new StringValue("ESDTRoleLocalMint")) : 0; - options.addRoleLocalBurn ? args.push(new StringValue("ESDTRoleLocalBurn")) : 0; - options.addRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.localMintRole ? args.push(new StringValue("ESDTRoleLocalMint")) : 0; + options.localBurnRole ? args.push(new StringValue("ESDTRoleLocalBurn")) : 0; + options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -282,16 +282,38 @@ export class TokenManagementTransactionsFactory { }).build(); } + createTransactionForUnsettingSpecialRoleOnFungibleToken( + sender: Address, + options: resources.FungibleSpecialRoleInput, + ): Transaction { + const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; + + options.localMintRole ? args.push(new StringValue("ESDTRoleLocalMint")) : 0; + options.localBurnRole ? args.push(new StringValue("ESDTRoleLocalBurn")) : 0; + options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + + const dataParts = ["unSetSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + + return new TransactionBuilder({ + config: this.config, + sender: sender, + receiver: this.esdtContractAddress, + dataParts: dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true, + }).build(); + } + createTransactionForSettingSpecialRoleOnSemiFungibleToken( sender: Address, options: resources.SemiFungibleSpecialRoleInput, ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.addRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; - options.addRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; - options.addRoleNFTAddQuantity ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; - options.addRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.NFTCreateRole ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; + options.NFTBurnRole ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; + options.NFTAddQuantityRole ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; + options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -305,6 +327,29 @@ export class TokenManagementTransactionsFactory { }).build(); } + createTransactionForUnsettingSpecialRoleOnSemiFungibleToken( + sender: Address, + options: resources.SemiFungibleSpecialRoleInput, + ): Transaction { + const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; + + options.NFTCreateRole ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; + options.NFTBurnRole ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; + options.NFTAddQuantityRole ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; + options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + + const dataParts = ["unSetSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + + return new TransactionBuilder({ + config: this.config, + sender: sender, + receiver: this.esdtContractAddress, + dataParts: dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true, + }).build(); + } + createTransactionForSettingSpecialRoleOnMetaESDT( sender: Address, options: resources.SemiFungibleSpecialRoleInput, @@ -312,21 +357,28 @@ export class TokenManagementTransactionsFactory { return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(sender, options); } + createTransactionForUnsettingSpecialRoleOnMetaESDT( + sender: Address, + options: resources.SemiFungibleSpecialRoleInput, + ): Transaction { + return this.createTransactionForUnsettingSpecialRoleOnSemiFungibleToken(sender, options); + } + createTransactionForSettingSpecialRoleOnNonFungibleToken( sender: Address, options: resources.SpecialRoleInput, ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.addRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; - options.addRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; - options.addRoleNFTUpdateAttributes ? args.push(new StringValue("ESDTRoleNFTUpdateAttributes")) : 0; - options.addRoleNFTAddURI ? args.push(new StringValue("ESDTRoleNFTAddURI")) : 0; - options.addRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; - options.addRoleESDTModifyCreator ? args.push(new StringValue("ESDTRoleModifyCreator")) : 0; - options.addRoleNFTRecreate ? args.push(new StringValue("ESDTRoleNFTRecreate")) : 0; - options.addRoleESDTSetNewURI ? args.push(new StringValue("ESDTRoleSetNewURI")) : 0; - options.addRoleESDTModifyRoyalties ? args.push(new StringValue("ESDTRoleModifyRoyalties")) : 0; + options.NFTCreateRole ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; + options.NFTBurnRole ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; + options.NFTUpdateAttributesRole ? args.push(new StringValue("ESDTRoleNFTUpdateAttributes")) : 0; + options.NFTAddURIRole ? args.push(new StringValue("ESDTRoleNFTAddURI")) : 0; + options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.ESDTModifyCreatorRole ? args.push(new StringValue("ESDTRoleModifyCreator")) : 0; + options.NFTRecreateRole ? args.push(new StringValue("ESDTRoleNFTRecreate")) : 0; + options.ESDTSetNewURIRole ? args.push(new StringValue("ESDTRoleSetNewURI")) : 0; + options.ESDTModifyRoyaltiesRole ? args.push(new StringValue("ESDTRoleModifyRoyalties")) : 0; const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -340,6 +392,34 @@ export class TokenManagementTransactionsFactory { }).build(); } + createTransactionForUnsettingSpecialRoleOnNonFungibleToken( + sender: Address, + options: resources.SpecialRoleInput, + ): Transaction { + const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; + + options.NFTCreateRole ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; + options.NFTBurnRole ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; + options.NFTUpdateAttributesRole ? args.push(new StringValue("ESDTRoleNFTUpdateAttributes")) : 0; + options.NFTAddURIRole ? args.push(new StringValue("ESDTRoleNFTAddURI")) : 0; + options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.ESDTModifyCreatorRole ? args.push(new StringValue("ESDTRoleModifyCreator")) : 0; + options.NFTRecreateRole ? args.push(new StringValue("ESDTRoleNFTRecreate")) : 0; + options.ESDTSetNewURIRole ? args.push(new StringValue("ESDTRoleSetNewURI")) : 0; + options.ESDTModifyRoyaltiesRole ? args.push(new StringValue("ESDTRoleModifyRoyalties")) : 0; + + const dataParts = ["unSetSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + + return new TransactionBuilder({ + config: this.config, + sender: sender, + receiver: this.esdtContractAddress, + dataParts: dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true, + }).build(); + } + createTransactionForCreatingNFT(sender: Address, options: resources.MintInput): Transaction { const dataParts = [ "ESDTNFTCreate", From c71472dcb24a0e13b014a1a4727379791395b0cf Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 6 Mar 2025 11:59:19 +0200 Subject: [PATCH 200/214] Fix naming --- src/tokenManagement/tokenManagementController.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index d59b2af98..9115783b1 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -226,7 +226,7 @@ export class TokenManagementController extends BaseController { return this.parser.parseSetSpecialRole(transactionOnNetwork); } - async createTransactionForunsettingSpecialRoleOnFungibleToken( + async createTransactionForUnsettingSpecialRoleOnFungibleToken( sender: IAccount, nonce: bigint, options: resources.FungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, From a0e9af4aff8485015ff74fa19ccc4410f4a65efc Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 6 Mar 2025 12:00:51 +0200 Subject: [PATCH 201/214] Bump version --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 73f49d64b..d77448154 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.0", + "version": "14.0.0-beta.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.0", + "version": "14.0.0-beta.1", "license": "MIT", "dependencies": { "@multiversx/sdk-transaction-decoder": "1.0.2", diff --git a/package.json b/package.json index 42dee64ec..dd6788400 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.0", + "version": "14.0.0-beta.1", "description": "MultiversX SDK for JavaScript and TypeScript", "author": "MultiversX", "homepage": "https://multiversx.com", From 055ab0a5acacba233b728165d01912a87b75fbd3 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 6 Mar 2025 12:17:51 +0200 Subject: [PATCH 202/214] Revert input resource rename --- src/tokenManagement/resources.ts | 62 +++++++++++----- .../tokenManagementController.ts | 8 +-- .../tokenManagementTransactionFactory.spec.ts | 46 ++++++------ .../tokenManagementTransactionsFactory.ts | 72 +++++++++---------- 4 files changed, 109 insertions(+), 79 deletions(-) diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index d7a050b66..85dfa2155 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -21,31 +21,61 @@ export type IssueInput = { export type FungibleSpecialRoleInput = { user: Address; tokenIdentifier: string; - localMintRole: boolean; - localBurnRole: boolean; - ESDTTransferRole: boolean; + addRoleLocalMint: boolean; + addRoleLocalBurn: boolean; + addRoleESDTTransferRole: boolean; }; export type SemiFungibleSpecialRoleInput = { user: Address; tokenIdentifier: string; - NFTCreateRole: boolean; - NFTBurnRole: boolean; - NFTAddQuantityRole: boolean; - ESDTTransferRole: boolean; + addRoleNFTCreate: boolean; + addRoleNFTBurn: boolean; + addRoleNFTAddQuantity: boolean; + addRoleESDTTransferRole: boolean; }; export type SpecialRoleInput = { user: Address; tokenIdentifier: string; - NFTCreateRole: boolean; - NFTBurnRole: boolean; - NFTUpdateAttributesRole: boolean; - NFTAddURIRole: boolean; - ESDTTransferRole: boolean; - ESDTModifyCreatorRole?: boolean; - NFTRecreateRole?: boolean; - ESDTSetNewURIRole?: boolean; - ESDTModifyRoyaltiesRole?: boolean; + addRoleNFTCreate: boolean; + addRoleNFTBurn: boolean; + addRoleNFTUpdateAttributes: boolean; + addRoleNFTAddURI: boolean; + addRoleESDTTransferRole: boolean; + addRoleESDTModifyCreator?: boolean; + addRoleNFTRecreate?: boolean; + addRoleESDTSetNewURI?: boolean; + addRoleESDTModifyRoyalties?: boolean; +}; + +export type UnsetFungibleSpecialRoleInput = { + user: Address; + tokenIdentifier: string; + removeRoleLocalMint: boolean; + removeRoleLocalBurn: boolean; + removeRoleESDTTransferRole: boolean; +}; +export type UnsetSemiFungibleSpecialRoleInput = { + user: Address; + tokenIdentifier: string; + removeRoleNFTCreate: boolean; + removeRoleNFTBurn: boolean; + removeRoleNFTAddQuantity: boolean; + removeRoleESDTTransferRole: boolean; +}; + +export type UnsetSpecialRoleInput = { + user: Address; + tokenIdentifier: string; + removeRoleNFTCreate: boolean; + removeRoleNFTBurn: boolean; + removeRoleNFTUpdateAttributes: boolean; + removeRoleNFTAddURI: boolean; + removeRoleESDTTransferRole: boolean; + removeRoleESDTModifyCreator?: boolean; + removeRoleNFTRecreate?: boolean; + removeRoleESDTSetNewURI?: boolean; + removeRoleESDTModifyRoyalties?: boolean; }; export type MintInput = { diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index 9115783b1..f62246c44 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -229,7 +229,7 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingSpecialRoleOnFungibleToken( sender: IAccount, nonce: bigint, - options: resources.FungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.UnsetFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnFungibleToken( sender.address, @@ -276,7 +276,7 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingSpecialRoleOnSemiFungibleToken( sender: IAccount, nonce: bigint, - options: resources.SemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.UnsetSemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnSemiFungibleToken( sender.address, @@ -320,7 +320,7 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingSpecialRoleOnMetaESDT( sender: IAccount, nonce: bigint, - options: resources.SemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.UnsetSemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnMetaESDT(sender.address, options); @@ -364,7 +364,7 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingSpecialRoleOnNonFungibleToken( sender: IAccount, nonce: bigint, - options: resources.SpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.UnsetSpecialRoleInput & { guardian?: Address; relayer?: Address }, ): Promise { const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnNonFungibleToken( sender.address, diff --git a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts index b600661d6..157acc4e9 100644 --- a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts @@ -137,9 +137,9 @@ describe("test token management transactions factory", () => { { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - localMintRole: true, - localBurnRole: false, - ESDTTransferRole: false, + addRoleLocalMint: true, + addRoleLocalBurn: false, + addRoleESDTTransferRole: false, }, ); @@ -160,9 +160,9 @@ describe("test token management transactions factory", () => { { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - localMintRole: true, - localBurnRole: false, - ESDTTransferRole: false, + removeRoleLocalMint: true, + removeRoleLocalBurn: false, + removeRoleESDTTransferRole: false, }, ); @@ -183,9 +183,9 @@ describe("test token management transactions factory", () => { { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - localMintRole: true, - localBurnRole: true, - ESDTTransferRole: true, + addRoleLocalMint: true, + addRoleLocalBurn: true, + addRoleESDTTransferRole: true, }, ); @@ -206,13 +206,13 @@ describe("test token management transactions factory", () => { { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - NFTCreateRole: true, - NFTBurnRole: false, - NFTUpdateAttributesRole: true, - NFTAddURIRole: true, - ESDTTransferRole: false, - ESDTModifyCreatorRole: true, - NFTRecreateRole: true, + addRoleNFTCreate: true, + addRoleNFTBurn: false, + addRoleNFTUpdateAttributes: true, + addRoleNFTAddURI: true, + addRoleESDTTransferRole: false, + addRoleESDTModifyCreator: true, + addRoleNFTRecreate: true, }, ); @@ -233,13 +233,13 @@ describe("test token management transactions factory", () => { { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - NFTCreateRole: true, - NFTBurnRole: false, - NFTUpdateAttributesRole: true, - NFTAddURIRole: true, - ESDTTransferRole: false, - ESDTModifyCreatorRole: true, - NFTRecreateRole: true, + removeRoleNFTCreate: true, + removeRoleNFTBurn: false, + removeRoleNFTUpdateAttributes: true, + removeRoleNFTAddURI: true, + removeRoleESDTTransferRole: false, + removeRoleESDTModifyCreator: true, + removeRoleNFTRecreate: true, }, ); diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index 2d46eadc2..7f200303b 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -266,9 +266,9 @@ export class TokenManagementTransactionsFactory { ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.localMintRole ? args.push(new StringValue("ESDTRoleLocalMint")) : 0; - options.localBurnRole ? args.push(new StringValue("ESDTRoleLocalBurn")) : 0; - options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.addRoleLocalMint ? args.push(new StringValue("ESDTRoleLocalMint")) : 0; + options.addRoleLocalBurn ? args.push(new StringValue("ESDTRoleLocalBurn")) : 0; + options.addRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -284,13 +284,13 @@ export class TokenManagementTransactionsFactory { createTransactionForUnsettingSpecialRoleOnFungibleToken( sender: Address, - options: resources.FungibleSpecialRoleInput, + options: resources.UnsetFungibleSpecialRoleInput, ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.localMintRole ? args.push(new StringValue("ESDTRoleLocalMint")) : 0; - options.localBurnRole ? args.push(new StringValue("ESDTRoleLocalBurn")) : 0; - options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.removeRoleLocalMint ? args.push(new StringValue("ESDTRoleLocalMint")) : 0; + options.removeRoleESDTTransferRole ? args.push(new StringValue("ESDTRoleLocalBurn")) : 0; + options.removeRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; const dataParts = ["unSetSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -310,10 +310,10 @@ export class TokenManagementTransactionsFactory { ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.NFTCreateRole ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; - options.NFTBurnRole ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; - options.NFTAddQuantityRole ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; - options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.addRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; + options.addRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; + options.addRoleNFTAddQuantity ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; + options.addRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -329,14 +329,14 @@ export class TokenManagementTransactionsFactory { createTransactionForUnsettingSpecialRoleOnSemiFungibleToken( sender: Address, - options: resources.SemiFungibleSpecialRoleInput, + options: resources.UnsetSemiFungibleSpecialRoleInput, ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.NFTCreateRole ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; - options.NFTBurnRole ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; - options.NFTAddQuantityRole ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; - options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.removeRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; + options.removeRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; + options.removeRoleNFTAddQuantity ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; + options.removeRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; const dataParts = ["unSetSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -359,7 +359,7 @@ export class TokenManagementTransactionsFactory { createTransactionForUnsettingSpecialRoleOnMetaESDT( sender: Address, - options: resources.SemiFungibleSpecialRoleInput, + options: resources.UnsetSemiFungibleSpecialRoleInput, ): Transaction { return this.createTransactionForUnsettingSpecialRoleOnSemiFungibleToken(sender, options); } @@ -370,15 +370,15 @@ export class TokenManagementTransactionsFactory { ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.NFTCreateRole ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; - options.NFTBurnRole ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; - options.NFTUpdateAttributesRole ? args.push(new StringValue("ESDTRoleNFTUpdateAttributes")) : 0; - options.NFTAddURIRole ? args.push(new StringValue("ESDTRoleNFTAddURI")) : 0; - options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; - options.ESDTModifyCreatorRole ? args.push(new StringValue("ESDTRoleModifyCreator")) : 0; - options.NFTRecreateRole ? args.push(new StringValue("ESDTRoleNFTRecreate")) : 0; - options.ESDTSetNewURIRole ? args.push(new StringValue("ESDTRoleSetNewURI")) : 0; - options.ESDTModifyRoyaltiesRole ? args.push(new StringValue("ESDTRoleModifyRoyalties")) : 0; + options.addRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; + options.addRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; + options.addRoleNFTUpdateAttributes ? args.push(new StringValue("ESDTRoleNFTUpdateAttributes")) : 0; + options.addRoleNFTAddURI ? args.push(new StringValue("ESDTRoleNFTAddURI")) : 0; + options.addRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.addRoleESDTModifyCreator ? args.push(new StringValue("ESDTRoleModifyCreator")) : 0; + options.addRoleNFTRecreate ? args.push(new StringValue("ESDTRoleNFTRecreate")) : 0; + options.addRoleESDTSetNewURI ? args.push(new StringValue("ESDTRoleSetNewURI")) : 0; + options.addRoleESDTModifyRoyalties ? args.push(new StringValue("ESDTRoleModifyRoyalties")) : 0; const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; @@ -394,19 +394,19 @@ export class TokenManagementTransactionsFactory { createTransactionForUnsettingSpecialRoleOnNonFungibleToken( sender: Address, - options: resources.SpecialRoleInput, + options: resources.UnsetSpecialRoleInput, ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.NFTCreateRole ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; - options.NFTBurnRole ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; - options.NFTUpdateAttributesRole ? args.push(new StringValue("ESDTRoleNFTUpdateAttributes")) : 0; - options.NFTAddURIRole ? args.push(new StringValue("ESDTRoleNFTAddURI")) : 0; - options.ESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; - options.ESDTModifyCreatorRole ? args.push(new StringValue("ESDTRoleModifyCreator")) : 0; - options.NFTRecreateRole ? args.push(new StringValue("ESDTRoleNFTRecreate")) : 0; - options.ESDTSetNewURIRole ? args.push(new StringValue("ESDTRoleSetNewURI")) : 0; - options.ESDTModifyRoyaltiesRole ? args.push(new StringValue("ESDTRoleModifyRoyalties")) : 0; + options.removeRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; + options.removeRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; + options.removeRoleNFTUpdateAttributes ? args.push(new StringValue("ESDTRoleNFTUpdateAttributes")) : 0; + options.removeRoleNFTAddURI ? args.push(new StringValue("ESDTRoleNFTAddURI")) : 0; + options.removeRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; + options.removeRoleESDTModifyCreator ? args.push(new StringValue("ESDTRoleModifyCreator")) : 0; + options.removeRoleNFTRecreate ? args.push(new StringValue("ESDTRoleNFTRecreate")) : 0; + options.removeRoleESDTSetNewURI ? args.push(new StringValue("ESDTRoleSetNewURI")) : 0; + options.removeRoleESDTModifyRoyalties ? args.push(new StringValue("ESDTRoleModifyRoyalties")) : 0; const dataParts = ["unSetSpecialRole", ...this.argSerializer.valuesToStrings(args)]; From a2bf580000292f3c62f68f70e9c2bcbdb469b689 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 6 Mar 2025 12:24:59 +0200 Subject: [PATCH 203/214] Remove unset for nft creation role --- src/tokenManagement/resources.ts | 2 -- src/tokenManagement/tokenManagementTransactionFactory.spec.ts | 3 +-- src/tokenManagement/tokenManagementTransactionsFactory.ts | 2 -- 3 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/tokenManagement/resources.ts b/src/tokenManagement/resources.ts index 85dfa2155..69b5d5c23 100644 --- a/src/tokenManagement/resources.ts +++ b/src/tokenManagement/resources.ts @@ -58,7 +58,6 @@ export type UnsetFungibleSpecialRoleInput = { export type UnsetSemiFungibleSpecialRoleInput = { user: Address; tokenIdentifier: string; - removeRoleNFTCreate: boolean; removeRoleNFTBurn: boolean; removeRoleNFTAddQuantity: boolean; removeRoleESDTTransferRole: boolean; @@ -67,7 +66,6 @@ export type UnsetSemiFungibleSpecialRoleInput = { export type UnsetSpecialRoleInput = { user: Address; tokenIdentifier: string; - removeRoleNFTCreate: boolean; removeRoleNFTBurn: boolean; removeRoleNFTUpdateAttributes: boolean; removeRoleNFTAddURI: boolean; diff --git a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts index 157acc4e9..7f13ebd87 100644 --- a/src/tokenManagement/tokenManagementTransactionFactory.spec.ts +++ b/src/tokenManagement/tokenManagementTransactionFactory.spec.ts @@ -233,7 +233,6 @@ describe("test token management transactions factory", () => { { user: grace.address, tokenIdentifier: "FRANK-11ce3e", - removeRoleNFTCreate: true, removeRoleNFTBurn: false, removeRoleNFTUpdateAttributes: true, removeRoleNFTAddURI: true, @@ -246,7 +245,7 @@ describe("test token management transactions factory", () => { assert.deepEqual( transaction.data, Buffer.from( - "unSetSpecialRole@4652414e4b2d313163653365@1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13@45534454526f6c654e4654437265617465@45534454526f6c654e465455706461746541747472696275746573@45534454526f6c654e4654416464555249@45534454526f6c654d6f6469667943726561746f72@45534454526f6c654e46545265637265617465", + "unSetSpecialRole@4652414e4b2d313163653365@1e8a8b6b49de5b7be10aaa158a5a6a4abb4b56cc08f524bb5e6cd5f211ad3e13@45534454526f6c654e465455706461746541747472696275746573@45534454526f6c654e4654416464555249@45534454526f6c654d6f6469667943726561746f72@45534454526f6c654e46545265637265617465", ), ); assert.deepEqual(transaction.sender, frank.address); diff --git a/src/tokenManagement/tokenManagementTransactionsFactory.ts b/src/tokenManagement/tokenManagementTransactionsFactory.ts index 7f200303b..90ad40a27 100644 --- a/src/tokenManagement/tokenManagementTransactionsFactory.ts +++ b/src/tokenManagement/tokenManagementTransactionsFactory.ts @@ -333,7 +333,6 @@ export class TokenManagementTransactionsFactory { ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.removeRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; options.removeRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; options.removeRoleNFTAddQuantity ? args.push(new StringValue("ESDTRoleNFTAddQuantity")) : 0; options.removeRoleESDTTransferRole ? args.push(new StringValue("ESDTTransferRole")) : 0; @@ -398,7 +397,6 @@ export class TokenManagementTransactionsFactory { ): Transaction { const args = [new StringValue(options.tokenIdentifier), new AddressValue(options.user)]; - options.removeRoleNFTCreate ? args.push(new StringValue("ESDTRoleNFTCreate")) : 0; options.removeRoleNFTBurn ? args.push(new StringValue("ESDTRoleNFTBurn")) : 0; options.removeRoleNFTUpdateAttributes ? args.push(new StringValue("ESDTRoleNFTUpdateAttributes")) : 0; options.removeRoleNFTAddURI ? args.push(new StringValue("ESDTRoleNFTAddURI")) : 0; From d5b0321af3f672502a8ace2975ca206f9dc16ac8 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 6 Mar 2025 12:35:16 +0200 Subject: [PATCH 204/214] Update to use signTransaction on controllers --- src/accountManagement/accountController.ts | 11 +-- src/delegation/delegationController.ts | 41 +++++------ src/smartContracts/smartContractController.ts | 9 +-- .../tokenManagementController.ts | 73 +++++++++---------- src/transfers/transfersControllers.ts | 9 +-- 5 files changed, 64 insertions(+), 79 deletions(-) diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index 00599fba4..8e28ea850 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -1,21 +1,18 @@ import { IAccount } from "../accounts/interfaces"; import { Address, BaseController } from "../core"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; import { SaveKeyValueInput, SetGuardianInput } from "./resources"; export class AccountController extends BaseController { private factory: AccountTransactionsFactory; - private txComputer: TransactionComputer; constructor(options: { chainID: string }) { super(); this.factory = new AccountTransactionsFactory({ config: new TransactionsFactoryConfig(options), }); - this.txComputer = new TransactionComputer(); } async createTransactionForSavingKeyValue( @@ -29,7 +26,7 @@ export class AccountController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -45,7 +42,7 @@ export class AccountController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -59,7 +56,7 @@ export class AccountController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -75,7 +72,7 @@ export class AccountController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index 1392d3986..d40559d84 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -1,7 +1,6 @@ import { IAccount } from "../accounts/interfaces"; import { Address, BaseController } from "../core"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { TransactionWatcher } from "../core/transactionWatcher"; @@ -14,7 +13,6 @@ export class DelegationController extends BaseController { private transactionAwaiter: TransactionWatcher; private factory: DelegationTransactionsFactory; private parser: DelegationTransactionsOutcomeParser; - private txComputer: TransactionComputer; constructor(options: { chainID: string; networkProvider: INetworkProvider }) { super(); @@ -23,7 +21,6 @@ export class DelegationController extends BaseController { config: new TransactionsFactoryConfig({ chainID: options.chainID }), }); this.parser = new DelegationTransactionsOutcomeParser(); - this.txComputer = new TransactionComputer(); } async createTransactionForNewDelegationContract( @@ -37,7 +34,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -62,7 +59,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -78,7 +75,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -94,7 +91,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -110,7 +107,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -126,7 +123,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -142,7 +139,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -158,7 +155,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -174,7 +171,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -190,7 +187,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -206,7 +203,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -225,7 +222,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -244,7 +241,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -260,7 +257,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -276,7 +273,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -292,7 +289,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -308,7 +305,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -324,7 +321,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -341,7 +338,7 @@ export class DelegationController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index e36551243..a9cb96495 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -4,7 +4,6 @@ import { Address, BaseController } from "../core"; import { Err, ErrSmartContractQuery } from "../core/errors"; import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../core/smartContractQuery"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { TransactionWatcher } from "../core/transactionWatcher"; @@ -17,7 +16,6 @@ export class SmartContractController extends BaseController { private factory: SmartContractTransactionsFactory; private parser: SmartContractTransactionsOutcomeParser; private transactionWatcher: TransactionWatcher; - private txComputer: TransactionComputer; private networkProvider: INetworkProvider; private abi?: Abi; @@ -29,7 +27,6 @@ export class SmartContractController extends BaseController { }); this.parser = new SmartContractTransactionsOutcomeParser(options); this.transactionWatcher = new TransactionWatcher(options.networkProvider); - this.txComputer = new TransactionComputer(); this.networkProvider = options.networkProvider; this.abi = options.abi; } @@ -45,7 +42,7 @@ export class SmartContractController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -70,7 +67,7 @@ export class SmartContractController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -86,7 +83,7 @@ export class SmartContractController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index f62246c44..b77cf7063 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -1,7 +1,6 @@ import { IAccount } from "../accounts/interfaces"; import { Address, BaseController } from "../core"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { TransactionWatcher } from "../core/transactionWatcher"; @@ -13,7 +12,6 @@ import { TokenManagementTransactionsFactory } from "./tokenManagementTransaction export class TokenManagementController extends BaseController { private factory: TokenManagementTransactionsFactory; private transactionAwaiter: TransactionWatcher; - private txComputer: TransactionComputer; private parser: TokenManagementTransactionsOutcomeParser; constructor(options: { chainID: string; networkProvider: INetworkProvider }) { @@ -22,7 +20,6 @@ export class TokenManagementController extends BaseController { config: new TransactionsFactoryConfig({ chainID: options.chainID }), }); this.transactionAwaiter = new TransactionWatcher(options.networkProvider); - this.txComputer = new TransactionComputer(); this.parser = new TokenManagementTransactionsOutcomeParser(); } @@ -37,7 +34,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -62,7 +59,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -87,7 +84,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -112,7 +109,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -137,7 +134,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -162,7 +159,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -187,7 +184,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -212,7 +209,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -240,7 +237,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -259,7 +256,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -287,7 +284,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -303,7 +300,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -328,7 +325,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -347,7 +344,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -375,7 +372,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -391,7 +388,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -416,7 +413,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -441,7 +438,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -466,7 +463,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -491,7 +488,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -516,7 +513,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -541,7 +538,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -566,7 +563,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -591,7 +588,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -616,7 +613,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -641,7 +638,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -666,7 +663,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -691,7 +688,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -716,7 +713,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -741,7 +738,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -766,7 +763,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -791,7 +788,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -816,7 +813,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -837,7 +834,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -862,7 +859,7 @@ export class TokenManagementController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index f06f68bef..099be1241 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -1,19 +1,16 @@ import { IAccount } from "../accounts/interfaces"; import { Address, BaseController } from "../core"; import { Transaction } from "../core/transaction"; -import { TransactionComputer } from "../core/transactionComputer"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import * as resources from "./resources"; import { TransferTransactionsFactory } from "./transferTransactionsFactory"; export class TransfersController extends BaseController { private factory: TransferTransactionsFactory; - private txComputer: TransactionComputer; constructor(options: { chainID: string }) { super(); this.factory = new TransferTransactionsFactory({ config: new TransactionsFactoryConfig(options) }); - this.txComputer = new TransactionComputer(); } async createTransactionForNativeTokenTransfer( @@ -27,7 +24,7 @@ export class TransfersController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -43,7 +40,7 @@ export class TransfersController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } @@ -59,7 +56,7 @@ export class TransfersController extends BaseController { transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; this.addExtraGasLimitIfRequired(transaction); - transaction.signature = await sender.sign(this.txComputer.computeBytesForSigning(transaction)); + transaction.signature = await sender.signTransaction(transaction); return transaction; } From 98e0e02d4b186d68c79e773b1d7330ec460c2ae2 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 12 Mar 2025 14:57:03 +0200 Subject: [PATCH 205/214] Add gasPrice and gasLimit to controllers --- src/core/baseController.ts | 23 ++- src/delegation/delegationController.ts | 78 +++++----- src/entrypoints/entrypoints.spec.ts | 25 +++ src/smartContracts/smartContractController.ts | 14 +- .../tokenManagementController.ts | 142 +++++++++--------- src/transfers/transfersControllers.ts | 14 +- 6 files changed, 170 insertions(+), 126 deletions(-) diff --git a/src/core/baseController.ts b/src/core/baseController.ts index 43db3b191..56fc8cdfb 100644 --- a/src/core/baseController.ts +++ b/src/core/baseController.ts @@ -1,8 +1,27 @@ -import { Transaction } from "../core/transaction"; +import { Address } from "./address"; import { EXTRA_GAS_LIMIT_FOR_GUARDED_TRANSACTIONS, EXTRA_GAS_LIMIT_FOR_RELAYED_TRANSACTIONS } from "./constants"; +import { Transaction } from "./transaction"; + +export type BaseControllerInput = { + guardian?: Address; + relayer?: Address; + gasPrice?: bigint; + gasLimit?: bigint; +}; export class BaseController { - addExtraGasLimitIfRequired(transaction: Transaction): void { + protected setTransactionGasOptions(transaction: Transaction, options: { gasLimit?: bigint; gasPrice?: bigint }) { + if (options.gasLimit) { + transaction.gasLimit = options.gasLimit; + } else { + this.addExtraGasLimitIfRequired(transaction); + } + if (options.gasPrice) { + transaction.gasPrice = options.gasPrice; + } + } + + protected addExtraGasLimitIfRequired(transaction: Transaction): void { if (transaction.guardian && !transaction.guardian.isEmpty()) { transaction.gasLimit += BigInt(EXTRA_GAS_LIMIT_FOR_GUARDED_TRANSACTIONS); } diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index d40559d84..ecba3f986 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -1,5 +1,5 @@ import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController } from "../core"; +import { Address, BaseController, BaseControllerInput } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; @@ -26,14 +26,14 @@ export class DelegationController extends BaseController { async createTransactionForNewDelegationContract( sender: IAccount, nonce: bigint, - options: resources.NewDelegationContractInput & { guardian?: Address; relayer?: Address }, + options: resources.NewDelegationContractInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForNewDelegationContract(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -51,14 +51,14 @@ export class DelegationController extends BaseController { async createTransactionForAddingNodes( sender: IAccount, nonce: bigint, - options: resources.AddNodesInput & { guardian?: Address; relayer?: Address }, + options: resources.AddNodesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForAddingNodes(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -67,14 +67,14 @@ export class DelegationController extends BaseController { async createTransactionForRemovingNodes( sender: IAccount, nonce: bigint, - options: resources.ManageNodesInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageNodesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForRemovingNodes(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -83,14 +83,14 @@ export class DelegationController extends BaseController { async createTransactionForStakingNodes( sender: IAccount, nonce: bigint, - options: resources.ManageNodesInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageNodesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForStakingNodes(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -99,14 +99,14 @@ export class DelegationController extends BaseController { async createTransactionForUnbondingNodes( sender: IAccount, nonce: bigint, - options: resources.ManageNodesInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageNodesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnbondingNodes(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -115,14 +115,14 @@ export class DelegationController extends BaseController { async createTransactionForUnstakingNodes( sender: IAccount, nonce: bigint, - options: resources.ManageNodesInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageNodesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnstakingNodes(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -131,14 +131,14 @@ export class DelegationController extends BaseController { async createTransactionForUnjailingNodes( sender: IAccount, nonce: bigint, - options: resources.UnjailingNodesInput & { guardian?: Address; relayer?: Address }, + options: resources.UnjailingNodesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnjailingNodes(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -147,14 +147,14 @@ export class DelegationController extends BaseController { async createTransactionForChangingServiceFee( sender: IAccount, nonce: bigint, - options: resources.ChangeServiceFee & { guardian?: Address; relayer?: Address }, + options: resources.ChangeServiceFee & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForChangingServiceFee(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -163,14 +163,14 @@ export class DelegationController extends BaseController { async createTransactionForModifyingDelegationCap( sender: IAccount, nonce: bigint, - options: resources.ModifyDelegationCapInput & { guardian?: Address; relayer?: Address }, + options: resources.ModifyDelegationCapInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForModifyingDelegationCap(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -179,14 +179,14 @@ export class DelegationController extends BaseController { async createTransactionForSettingAutomaticActivation( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageDelegationContractInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingAutomaticActivation(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -195,14 +195,14 @@ export class DelegationController extends BaseController { async createTransactionForUnsettingAutomaticActivation( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageDelegationContractInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingAutomaticActivation(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -211,7 +211,7 @@ export class DelegationController extends BaseController { async createTransactionForSettingCapCheckOnRedelegateRewards( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageDelegationContractInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingCapCheckOnRedelegateRewards( sender.address, @@ -221,7 +221,7 @@ export class DelegationController extends BaseController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -230,7 +230,7 @@ export class DelegationController extends BaseController { async createTransactionForUnsettingCapCheckOnRedelegateRewards( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageDelegationContractInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingCapCheckOnRedelegateRewards( sender.address, @@ -240,7 +240,7 @@ export class DelegationController extends BaseController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -249,14 +249,14 @@ export class DelegationController extends BaseController { async createTransactionForSettingMetadata( sender: IAccount, nonce: bigint, - options: resources.SetContractMetadataInput & { guardian?: Address; relayer?: Address }, + options: resources.SetContractMetadataInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingMetadata(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -265,14 +265,14 @@ export class DelegationController extends BaseController { async createTransactionForDelegating( sender: IAccount, nonce: bigint, - options: resources.DelegateActionsInput & { guardian?: Address; relayer?: Address }, + options: resources.DelegateActionsInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForDelegating(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -281,14 +281,14 @@ export class DelegationController extends BaseController { async createTransactionForClaimingRewards( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageDelegationContractInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForClaimingRewards(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -297,14 +297,14 @@ export class DelegationController extends BaseController { async createTransactionForRedelegatingRewards( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageDelegationContractInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForRedelegatingRewards(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -313,14 +313,14 @@ export class DelegationController extends BaseController { async createTransactionForUndelegating( sender: IAccount, nonce: bigint, - options: resources.DelegateActionsInput & { guardian?: Address; relayer?: Address }, + options: resources.DelegateActionsInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUndelegating(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -329,7 +329,7 @@ export class DelegationController extends BaseController { async createTransactionForWithdrawing( sender: IAccount, nonce: bigint, - options: resources.ManageDelegationContractInput & { guardian?: Address; relayer?: Address }, + options: resources.ManageDelegationContractInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForWithdrawing(sender.address, options); @@ -337,7 +337,7 @@ export class DelegationController extends BaseController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; diff --git a/src/entrypoints/entrypoints.spec.ts b/src/entrypoints/entrypoints.spec.ts index e06d617e8..5febc135a 100644 --- a/src/entrypoints/entrypoints.spec.ts +++ b/src/entrypoints/entrypoints.spec.ts @@ -31,6 +31,31 @@ describe("TestEntrypoint", function () { ); }); + it("native transfer with gas options", async () => { + const controller = entrypoint.createTransfersController(); + const filePath = path.join("src", "testdata", "testwallets", "alice.pem"); + const sender = await Account.newFromPem(filePath); + sender.nonce = 77777n; + + const gasLimit = BigInt(50000); + const gasPrice = BigInt(1000); + + const transaction = await controller.createTransactionForTransfer( + sender, + BigInt(sender.getNonceThenIncrement().valueOf()), + { + receiver: sender.address, + nativeAmount: BigInt(0), + data: Buffer.from("hello"), + gasLimit: gasLimit, + gasPrice: gasPrice, + }, + ); + + assert.equal(transaction.gasLimit, gasLimit, "Gas limit should be set correctly"); + assert.equal(transaction.gasPrice, gasPrice, "Gas price should be set correctly"); + }); + it("native transfer with guardian and relayer", async () => { const controller = entrypoint.createTransfersController(); const filePath = path.join("src", "testdata", "testwallets"); diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index a9cb96495..c5810c81f 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -1,6 +1,6 @@ import { Abi, ArgSerializer, isTyped, NativeSerializer } from "../abi"; import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController } from "../core"; +import { Address, BaseController, BaseControllerInput } from "../core"; import { Err, ErrSmartContractQuery } from "../core/errors"; import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../core/smartContractQuery"; import { Transaction } from "../core/transaction"; @@ -34,14 +34,14 @@ export class SmartContractController extends BaseController { async createTransactionForDeploy( sender: IAccount, nonce: bigint, - options: resources.ContractDeployInput & { guardian?: Address; relayer?: Address }, + options: resources.ContractDeployInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForDeploy(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -59,14 +59,14 @@ export class SmartContractController extends BaseController { async createTransactionForUpgrade( sender: IAccount, nonce: bigint, - options: resources.ContractUpgradeInput & { guardian?: Address; relayer?: Address }, + options: resources.ContractUpgradeInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUpgrade(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -75,14 +75,14 @@ export class SmartContractController extends BaseController { async createTransactionForExecute( sender: IAccount, nonce: bigint, - options: resources.ContractExecuteInput & { guardian?: Address; relayer?: Address }, + options: resources.ContractExecuteInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForExecute(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index b77cf7063..947e84e64 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -1,5 +1,5 @@ import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController } from "../core"; +import { Address, BaseController, BaseControllerInput } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; @@ -26,14 +26,14 @@ export class TokenManagementController extends BaseController { async createTransactionForIssuingFungible( sender: IAccount, nonce: bigint, - options: resources.IssueFungibleInput & { guardian?: Address; relayer?: Address }, + options: resources.IssueFungibleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForIssuingFungible(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -51,14 +51,14 @@ export class TokenManagementController extends BaseController { async createTransactionForIssuingSemiFungible( sender: IAccount, nonce: bigint, - options: resources.IssueSemiFungibleInput & { guardian?: Address; relayer?: Address }, + options: resources.IssueSemiFungibleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForIssuingSemiFungible(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -76,14 +76,14 @@ export class TokenManagementController extends BaseController { async createTransactionForIssuingNonFungible( sender: IAccount, nonce: bigint, - options: resources.IssueNonFungibleInput & { guardian?: Address; relayer?: Address }, + options: resources.IssueNonFungibleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForIssuingNonFungible(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -101,14 +101,14 @@ export class TokenManagementController extends BaseController { async createTransactionForRegisteringMetaEsdt( sender: IAccount, nonce: bigint, - options: resources.RegisterMetaESDTInput & { guardian?: Address; relayer?: Address }, + options: resources.RegisterMetaESDTInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForRegisteringMetaESDT(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -126,14 +126,14 @@ export class TokenManagementController extends BaseController { async createTransactionForRegisteringAndSettingRoles( sender: IAccount, nonce: bigint, - options: resources.RegisterRolesInput & { guardian?: Address; relayer?: Address }, + options: resources.RegisterRolesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForRegisteringAndSettingRoles(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -151,14 +151,14 @@ export class TokenManagementController extends BaseController { async createTransactionForSetBurnRoleGlobally( sender: IAccount, nonce: bigint, - options: resources.BurnRoleGloballyInput & { guardian?: Address; relayer?: Address }, + options: resources.BurnRoleGloballyInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingBurnRoleGlobally(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -176,14 +176,14 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingBurnRoleGlobally( sender: IAccount, nonce: bigint, - options: resources.BurnRoleGloballyInput & { guardian?: Address; relayer?: Address }, + options: resources.BurnRoleGloballyInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingBurnRoleGlobally(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -201,14 +201,14 @@ export class TokenManagementController extends BaseController { async createTransactionForSettingSpecialRoleOnFungibleToken( sender: IAccount, nonce: bigint, - options: resources.FungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.FungibleSpecialRoleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnFungibleToken(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -226,7 +226,7 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingSpecialRoleOnFungibleToken( sender: IAccount, nonce: bigint, - options: resources.UnsetFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.UnsetFungibleSpecialRoleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnFungibleToken( sender.address, @@ -236,7 +236,7 @@ export class TokenManagementController extends BaseController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -245,7 +245,7 @@ export class TokenManagementController extends BaseController { async createTransactionForSettingSpecialRoleOnSemiFungibleToken( sender: IAccount, nonce: bigint, - options: resources.SemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.SemiFungibleSpecialRoleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnSemiFungibleToken( sender.address, @@ -255,7 +255,7 @@ export class TokenManagementController extends BaseController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -273,7 +273,7 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingSpecialRoleOnSemiFungibleToken( sender: IAccount, nonce: bigint, - options: resources.UnsetSemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.UnsetSemiFungibleSpecialRoleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnSemiFungibleToken( sender.address, @@ -283,7 +283,7 @@ export class TokenManagementController extends BaseController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -292,14 +292,14 @@ export class TokenManagementController extends BaseController { async createTransactionForSettingSpecialRoleOnMetaESDT( sender: IAccount, nonce: bigint, - options: resources.SemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.SemiFungibleSpecialRoleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnMetaESDT(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -317,14 +317,14 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingSpecialRoleOnMetaESDT( sender: IAccount, nonce: bigint, - options: resources.UnsetSemiFungibleSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.UnsetSemiFungibleSpecialRoleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnMetaESDT(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -333,7 +333,7 @@ export class TokenManagementController extends BaseController { async createTransactionForSettingSpecialRoleOnNonFungibleToken( sender: IAccount, nonce: bigint, - options: resources.SpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.SpecialRoleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingSpecialRoleOnNonFungibleToken( sender.address, @@ -343,7 +343,7 @@ export class TokenManagementController extends BaseController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -361,7 +361,7 @@ export class TokenManagementController extends BaseController { async createTransactionForUnsettingSpecialRoleOnNonFungibleToken( sender: IAccount, nonce: bigint, - options: resources.UnsetSpecialRoleInput & { guardian?: Address; relayer?: Address }, + options: resources.UnsetSpecialRoleInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnsettingSpecialRoleOnNonFungibleToken( sender.address, @@ -371,7 +371,7 @@ export class TokenManagementController extends BaseController { transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -380,14 +380,14 @@ export class TokenManagementController extends BaseController { async createTransactionForCreatingNft( sender: IAccount, nonce: bigint, - options: resources.MintInput & { guardian?: Address; relayer?: Address }, + options: resources.MintInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForCreatingNFT(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -405,14 +405,14 @@ export class TokenManagementController extends BaseController { async createTransactionForPausing( sender: IAccount, nonce: bigint, - options: resources.PausingInput & { guardian?: Address; relayer?: Address }, + options: resources.PausingInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForPausing(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -430,14 +430,14 @@ export class TokenManagementController extends BaseController { async createTransactionForUnpausing( sender: IAccount, nonce: bigint, - options: resources.PausingInput & { guardian?: Address; relayer?: Address }, + options: resources.PausingInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnpausing(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -455,14 +455,14 @@ export class TokenManagementController extends BaseController { async createTransactionForFreezing( sender: IAccount, nonce: bigint, - options: resources.ManagementInput & { guardian?: Address; relayer?: Address }, + options: resources.ManagementInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForFreezing(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -480,14 +480,14 @@ export class TokenManagementController extends BaseController { async createTransactionForUnFreezing( sender: IAccount, nonce: bigint, - options: resources.ManagementInput & { guardian?: Address; relayer?: Address }, + options: resources.ManagementInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnfreezing(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -505,14 +505,14 @@ export class TokenManagementController extends BaseController { async createTransactionForWiping( sender: IAccount, nonce: bigint, - options: resources.ManagementInput & { guardian?: Address; relayer?: Address }, + options: resources.ManagementInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForWiping(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -530,14 +530,14 @@ export class TokenManagementController extends BaseController { async createTransactionForLocaMinting( sender: IAccount, nonce: bigint, - options: resources.LocalMintInput & { guardian?: Address; relayer?: Address }, + options: resources.LocalMintInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForLocalMint(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -555,14 +555,14 @@ export class TokenManagementController extends BaseController { async createTransactionForLocalBurning( sender: IAccount, nonce: bigint, - options: resources.LocalBurnInput & { guardian?: Address; relayer?: Address }, + options: resources.LocalBurnInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForLocalBurning(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -580,14 +580,14 @@ export class TokenManagementController extends BaseController { async createTransactionForUpdatingAttributes( sender: IAccount, nonce: bigint, - options: resources.UpdateAttributesInput & { guardian?: Address; relayer?: Address }, + options: resources.UpdateAttributesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUpdatingAttributes(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -605,14 +605,14 @@ export class TokenManagementController extends BaseController { async createTransactionForAddingQuantity( sender: IAccount, nonce: bigint, - options: resources.UpdateQuantityInput & { guardian?: Address; relayer?: Address }, + options: resources.UpdateQuantityInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForAddingQuantity(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -630,14 +630,14 @@ export class TokenManagementController extends BaseController { async createTransactionForBurningQuantity( sender: IAccount, nonce: bigint, - options: resources.UpdateQuantityInput & { guardian?: Address; relayer?: Address }, + options: resources.UpdateQuantityInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForBurningQuantity(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -655,14 +655,14 @@ export class TokenManagementController extends BaseController { async createTransactionForModifyingRoyalties( sender: IAccount, nonce: bigint, - options: resources.ModifyRoyaltiesInput & { guardian?: Address; relayer?: Address }, + options: resources.ModifyRoyaltiesInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForModifyingRoyalties(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -680,14 +680,14 @@ export class TokenManagementController extends BaseController { async createTransactionForSettingNewUris( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, + options: resources.SetNewUriInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingNewUris(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -705,14 +705,14 @@ export class TokenManagementController extends BaseController { async createTransactionForModifyingCreator( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, + options: resources.SetNewUriInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -730,14 +730,14 @@ export class TokenManagementController extends BaseController { async createTransactionForUpdatingMetadata( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, + options: resources.SetNewUriInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForModifyingCreator(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -755,14 +755,14 @@ export class TokenManagementController extends BaseController { async createTransactionForMetadataRecreate( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, + options: resources.SetNewUriInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForMetadataRecreate(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -780,14 +780,14 @@ export class TokenManagementController extends BaseController { async createTransactionForChangingTokenToDynamic( sender: IAccount, nonce: bigint, - options: resources.SetNewUriInput & { guardian?: Address; relayer?: Address }, + options: resources.SetNewUriInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForChangingTokenToDynamic(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -805,14 +805,14 @@ export class TokenManagementController extends BaseController { async createTransactionForUpdatingTokenId( sender: IAccount, nonce: bigint, - options: resources.UpdateTokenIDInput & { guardian?: Address; relayer?: Address }, + options: resources.UpdateTokenIDInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUpdatingTokenId(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -826,14 +826,14 @@ export class TokenManagementController extends BaseController { async createTransactionForRegisteringDynamicToken( sender: IAccount, nonce: bigint, - options: resources.RegisteringDynamicTokenInput & { guardian?: Address; relayer?: Address }, + options: resources.RegisteringDynamicTokenInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForRegisteringDynamicToken(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -851,14 +851,14 @@ export class TokenManagementController extends BaseController { async createTransactionForRegisteringDynamicTokenAndSettingRoles( sender: IAccount, nonce: bigint, - options: resources.RegisteringDynamicTokenInput & { guardian?: Address; relayer?: Address }, + options: resources.RegisteringDynamicTokenInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForRegisteringDynamicAndSettingRoles(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index 099be1241..6c323d38a 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -1,5 +1,5 @@ import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController } from "../core"; +import { Address, BaseController, BaseControllerInput } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import * as resources from "./resources"; @@ -16,14 +16,14 @@ export class TransfersController extends BaseController { async createTransactionForNativeTokenTransfer( sender: IAccount, nonce: bigint, - options: resources.NativeTokenTransferInput & { guardian?: Address; relayer?: Address }, + options: resources.NativeTokenTransferInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForNativeTokenTransfer(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -32,14 +32,14 @@ export class TransfersController extends BaseController { async createTransactionForEsdtTokenTransfer( sender: IAccount, nonce: bigint, - options: resources.CustomTokenTransferInput & { guardian?: Address; relayer?: Address }, + options: resources.CustomTokenTransferInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForESDTTokenTransfer(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -48,14 +48,14 @@ export class TransfersController extends BaseController { async createTransactionForTransfer( sender: IAccount, nonce: bigint, - options: resources.CreateTransferTransactionInput & { guardian?: Address; relayer?: Address }, + options: resources.CreateTransferTransactionInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForTransfer(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; From 0881204933a78d6f1e2756f12c65440a48e463d1 Mon Sep 17 00:00:00 2001 From: danielailie Date: Wed, 12 Mar 2025 15:17:42 +0200 Subject: [PATCH 206/214] Add gas options also on account controller --- src/accountManagement/accountController.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index 8e28ea850..f34ddeb4f 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -1,5 +1,5 @@ import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController } from "../core"; +import { Address, BaseController, BaseControllerInput } from "../core"; import { Transaction } from "../core/transaction"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; @@ -18,14 +18,14 @@ export class AccountController extends BaseController { async createTransactionForSavingKeyValue( sender: IAccount, nonce: bigint, - options: SaveKeyValueInput & { guardian?: Address; relayer?: Address }, + options: SaveKeyValueInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSavingKeyValue(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -34,14 +34,14 @@ export class AccountController extends BaseController { async createTransactionForSettingGuardian( sender: IAccount, nonce: bigint, - options: SetGuardianInput & { guardian?: Address; relayer?: Address }, + options: SetGuardianInput & BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForSettingGuardian(sender.address, options); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -50,12 +50,12 @@ export class AccountController extends BaseController { async createTransactionForGuardingAccount( sender: IAccount, nonce: bigint, - options: { relayer?: Address }, + options: { relayer?: Address; gasPrice?: bigint; gasLimit?: bigint }, ): Promise { const transaction = this.factory.createTransactionForGuardingAccount(sender.address); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; @@ -64,14 +64,14 @@ export class AccountController extends BaseController { async createTransactionForUnguardingAccount( sender: IAccount, nonce: bigint, - options: { guardian: Address; relayer?: Address }, + options: BaseControllerInput, ): Promise { const transaction = this.factory.createTransactionForUnguardingAccount(sender.address); transaction.guardian = options.guardian ?? Address.empty(); transaction.relayer = options.relayer ?? Address.empty(); transaction.nonce = nonce; - this.addExtraGasLimitIfRequired(transaction); + this.setTransactionGasOptions(transaction, options); transaction.signature = await sender.signTransaction(transaction); return transaction; From fc5880605d5b1c65c412f0c22f0fdd9086a77264 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 13 Mar 2025 11:38:45 +0200 Subject: [PATCH 207/214] Update codemetadata --- src/abi/codec/codemetadata.ts | 10 +- src/abi/index.ts | 1 - src/abi/smartContract.ts | 2 +- src/abi/typesystem/codeMetadata.ts | 2 +- src/{abi => core}/codeMetadata.spec.ts | 8 +- src/{abi => core}/codeMetadata.ts | 91 ++++++++++++++----- src/core/index.ts | 1 + src/networkProviders/accounts.ts | 3 +- .../smartContractTransactionsFactory.ts | 6 +- 9 files changed, 81 insertions(+), 43 deletions(-) rename src/{abi => core}/codeMetadata.spec.ts (92%) rename src/{abi => core}/codeMetadata.ts (73%) diff --git a/src/abi/codec/codemetadata.ts b/src/abi/codec/codemetadata.ts index 09682de28..f487c00ae 100644 --- a/src/abi/codec/codemetadata.ts +++ b/src/abi/codec/codemetadata.ts @@ -1,22 +1,22 @@ -import { CodeMetadata, CodeMetadataLength } from "../codeMetadata"; +import { CodeMetadata, CodeMetadataLength } from "../../core/codeMetadata"; import { CodeMetadataValue } from "../typesystem/codeMetadata"; export class CodeMetadataCodec { decodeNested(buffer: Buffer): [CodeMetadataValue, number] { - const codeMetadata = CodeMetadata.newFromBuffer(buffer.slice(0, CodeMetadataLength)); + const codeMetadata = CodeMetadata.newFromBytes(buffer.slice(0, CodeMetadataLength)); return [new CodeMetadataValue(codeMetadata), CodeMetadataLength]; } decodeTopLevel(buffer: Buffer): CodeMetadataValue { - const codeMetadata = CodeMetadata.newFromBuffer(buffer); + const codeMetadata = CodeMetadata.newFromBytes(new Uint8Array(buffer)); return new CodeMetadataValue(codeMetadata); } encodeNested(codeMetadata: CodeMetadataValue): Buffer { - return codeMetadata.valueOf().toBuffer(); + return Buffer.from(codeMetadata.valueOf().toBytes()); } encodeTopLevel(codeMetadata: CodeMetadataValue): Buffer { - return codeMetadata.valueOf().toBuffer(); + return Buffer.from(codeMetadata.valueOf().toBytes()); } } diff --git a/src/abi/index.ts b/src/abi/index.ts index 04ff81463..e72a5528f 100644 --- a/src/abi/index.ts +++ b/src/abi/index.ts @@ -2,7 +2,6 @@ export * from "./argSerializer"; export * from "./argumentErrorContext"; export * from "./code"; export * from "./codec"; -export * from "./codeMetadata"; export * from "./function"; export * from "./interaction"; export * from "./interface"; diff --git a/src/abi/smartContract.ts b/src/abi/smartContract.ts index 1edda34b8..7282430be 100644 --- a/src/abi/smartContract.ts +++ b/src/abi/smartContract.ts @@ -1,4 +1,5 @@ import { Address, AddressComputer } from "../core/address"; +import { CodeMetadata } from "../core/codeMetadata"; import { Compatibility } from "../core/compatibility"; import { TRANSACTION_MIN_GAS_PRICE } from "../core/constants"; import { ErrContractHasNoAddress } from "../core/errors"; @@ -6,7 +7,6 @@ import { Transaction } from "../core/transaction"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { guardValueIsSet } from "../core/utils"; import { SmartContractTransactionsFactory } from "./../smartContracts/smartContractTransactionsFactory"; -import { CodeMetadata } from "./codeMetadata"; import { ContractFunction } from "./function"; import { Interaction } from "./interaction"; import { diff --git a/src/abi/typesystem/codeMetadata.ts b/src/abi/typesystem/codeMetadata.ts index 60ff6c210..2db85c44e 100644 --- a/src/abi/typesystem/codeMetadata.ts +++ b/src/abi/typesystem/codeMetadata.ts @@ -1,4 +1,4 @@ -import { CodeMetadata } from "../codeMetadata"; +import { CodeMetadata } from "../../core"; import { PrimitiveType, PrimitiveValue } from "./types"; export class CodeMetadataType extends PrimitiveType { diff --git a/src/abi/codeMetadata.spec.ts b/src/core/codeMetadata.spec.ts similarity index 92% rename from src/abi/codeMetadata.spec.ts rename to src/core/codeMetadata.spec.ts index 2322a6417..a0a4a4282 100644 --- a/src/abi/codeMetadata.spec.ts +++ b/src/core/codeMetadata.spec.ts @@ -25,7 +25,7 @@ describe("CodeMetadata Class Tests", function () { it("should convert to buffer correctly", function () { const metadata = new CodeMetadata(true, true, true, true); - const buffer = metadata.toBuffer(); + const buffer = metadata.toBytes(); assert.equal(buffer.length, 2); assert.equal(buffer[0], CodeMetadata.ByteZero.Upgradeable | CodeMetadata.ByteZero.Readable); @@ -37,7 +37,7 @@ describe("CodeMetadata Class Tests", function () { CodeMetadata.ByteZero.Upgradeable | CodeMetadata.ByteZero.Readable, CodeMetadata.ByteOne.Payable | CodeMetadata.ByteOne.PayableBySc, ]); - const metadata = CodeMetadata.newFromBuffer(buffer); + const metadata = CodeMetadata.newFromBytes(buffer); assert.isTrue(metadata.upgradeable); assert.isTrue(metadata.readable); @@ -47,7 +47,7 @@ describe("CodeMetadata Class Tests", function () { it("should create from buffer correctly when some flags are set", function () { const buffer = Buffer.from([CodeMetadata.ByteZero.Upgradeable, CodeMetadata.ByteOne.PayableBySc]); - const metadata = CodeMetadata.newFromBuffer(buffer); + const metadata = CodeMetadata.newFromBytes(buffer); assert.isTrue(metadata.upgradeable); assert.isFalse(metadata.readable); @@ -60,7 +60,7 @@ describe("CodeMetadata Class Tests", function () { assert.throws( () => { - CodeMetadata.newFromBuffer(buffer); + CodeMetadata.newFromBytes(buffer); }, Error, "code metadata buffer has length 1, expected 2", diff --git a/src/abi/codeMetadata.ts b/src/core/codeMetadata.ts similarity index 73% rename from src/abi/codeMetadata.ts rename to src/core/codeMetadata.ts index 34160f5ce..ccbac8fb7 100644 --- a/src/abi/codeMetadata.ts +++ b/src/core/codeMetadata.ts @@ -41,11 +41,29 @@ export class CodeMetadata { this.payableBySc = payableBySc; } + /** + * Named constructor + * Creates a metadata object from a buffer. + * Should check that data has correct length (2 bytes) + */ static newFromBytes(bytes: Uint8Array): CodeMetadata { - return CodeMetadata.newFromBuffer(Buffer.from(bytes)); + if (bytes.length != CodeMetadataLength) { + throw new Error(`code metadata buffer has length ${bytes.length}, expected ${CodeMetadataLength}`); + } + + const byteZero = bytes[0]; + const byteOne = bytes[1]; + + const upgradeable = (byteZero & CodeMetadata.ByteZero.Upgradeable) !== 0; + const readable = (byteZero & CodeMetadata.ByteZero.Readable) !== 0; + const payable = (byteOne & CodeMetadata.ByteOne.Payable) !== 0; + const payableBySc = (byteOne & CodeMetadata.ByteOne.PayableBySc) !== 0; + + return new CodeMetadata(upgradeable, readable, payable, payableBySc); } /** + * @deprecated Use {@link newFromBytes} instead. * Creates a metadata object from a buffer. */ static newFromBuffer(buffer: Buffer): CodeMetadata { @@ -65,35 +83,30 @@ export class CodeMetadata { } /** - * Adjust the metadata (the `upgradeable` attribute), when preparing the deployment transaction. - */ - toggleUpgradeable(value: boolean) { - this.upgradeable = value; - } - - /** - * Adjust the metadata (the `readable` attribute), when preparing the deployment transaction. + * Converts the metadata to the protocol-friendly representation. */ - toggleReadable(value: boolean) { - this.readable = value; - } + toBytes(): Uint8Array { + let byteZero = 0; + let byteOne = 0; - /** - * Adjust the metadata (the `payable` attribute), when preparing the deployment transaction. - */ - togglePayable(value: boolean) { - this.payable = value; - } + if (this.upgradeable) { + byteZero |= CodeMetadata.ByteZero.Upgradeable; + } + if (this.readable) { + byteZero |= CodeMetadata.ByteZero.Readable; + } + if (this.payable) { + byteOne |= CodeMetadata.ByteOne.Payable; + } + if (this.payableBySc) { + byteOne |= CodeMetadata.ByteOne.PayableBySc; + } - /** - * Adjust the metadata (the `payableBySc` attribute), when preparing the deployment transaction. - */ - togglePayableBySc(value: boolean) { - this.payableBySc = value; + return new Uint8Array(Buffer.from([byteZero, byteOne])); } /** - * Converts the metadata to the protocol-friendly representation. + * @deprecated Use {@link toBytes} instead. */ toBuffer(): Buffer { let byteZero = 0; @@ -119,7 +132,35 @@ export class CodeMetadata { * Converts the metadata to a hex-encoded string. */ toString() { - return this.toBuffer().toString("hex"); + return Buffer.from(this.toBytes()).toString("hex"); + } + + /** + * Adjust the metadata (the `upgradeable` attribute), when preparing the deployment transaction. + */ + toggleUpgradeable(value: boolean) { + this.upgradeable = value; + } + + /** + * Adjust the metadata (the `readable` attribute), when preparing the deployment transaction. + */ + toggleReadable(value: boolean) { + this.readable = value; + } + + /** + * Adjust the metadata (the `payable` attribute), when preparing the deployment transaction. + */ + togglePayable(value: boolean) { + this.payable = value; + } + + /** + * Adjust the metadata (the `payableBySc` attribute), when preparing the deployment transaction. + */ + togglePayableBySc(value: boolean) { + this.payableBySc = value; } /** diff --git a/src/core/index.ts b/src/core/index.ts index 72d825d07..78be0e4a7 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -3,6 +3,7 @@ require("./globals"); export * from "./address"; export * from "./asyncTimer"; export * from "./baseController"; +export * from "./codeMetadata"; export * from "./config"; export * from "./errors"; export * from "./interface"; diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index c6f0ae90b..d79722fe4 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -1,5 +1,4 @@ -import { CodeMetadata } from "../abi"; -import { Address } from "../core/address"; +import { Address, CodeMetadata } from "../core"; /** * A plain view of an account, as queried from the Network. diff --git a/src/smartContracts/smartContractTransactionsFactory.ts b/src/smartContracts/smartContractTransactionsFactory.ts index fde7dded3..521a8f600 100644 --- a/src/smartContracts/smartContractTransactionsFactory.ts +++ b/src/smartContracts/smartContractTransactionsFactory.ts @@ -1,7 +1,5 @@ -import { ArgSerializer, CodeMetadata, ContractFunction, EndpointDefinition } from "../abi"; -import { NativeSerializer } from "../abi/nativeSerializer"; -import { isTyped } from "../abi/typesystem"; -import { Address } from "../core/address"; +import { ArgSerializer, ContractFunction, EndpointDefinition, isTyped, NativeSerializer } from "../abi"; +import { Address, CodeMetadata } from "../core"; import { CONTRACT_DEPLOY_ADDRESS_HEX, VM_TYPE_WASM_VM } from "../core/constants"; import { Err } from "../core/errors"; import { Logger } from "../core/logger"; From dfe9e8971667958b4ac69edf051229f24a5bdbe4 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 13 Mar 2025 11:39:12 +0200 Subject: [PATCH 208/214] Add descriptions on account and address --- src/accounts/account.ts | 57 +++++++++++++++++++++++++++++++++-------- src/core/address.ts | 57 +++++++++++++++++++++++------------------ 2 files changed, 79 insertions(+), 35 deletions(-) diff --git a/src/accounts/account.ts b/src/accounts/account.ts index 0c1716fa4..9d5d8647e 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -18,7 +18,8 @@ export class Account implements IAccount { readonly address: Address; /** - * The nonce of the account (the account sequence number). + * Local copy of the account nonce. + * Must be explicitly managed by client code. */ nonce: bigint = 0n; @@ -41,6 +42,11 @@ export class Account implements IAccount { this.address = this.publicKey.toAddress(hrp); } + /** + * Named constructor + * Loads a secret key from a PEM file. PEM files may contain multiple accounts - thus, an (optional) "index" is used to select the desired secret key. + * Returns an Account object, initialized with the secret key. + */ static async newFromPem( path: PathLike, index: number = 0, @@ -51,6 +57,12 @@ export class Account implements IAccount { return new Account(userSigner.secretKey, hrp); } + /** + * Named constructor + * Loads a secret key from an encrypted keystore file. Handles both keystores that hold a mnemonic and ones that hold a secret key (legacy). + * For keystores that hold an encrypted mnemonic, the optional "address_index" parameter is used to derive the desired secret key. + * Returns an Account object, initialized with the secret key. + */ static newFromKeystore( filePath: string, password: string, @@ -61,6 +73,11 @@ export class Account implements IAccount { return new Account(secretKey, hrp); } + /** + * Named constructor + * Loads (derives) a secret key from a mnemonic. The optional "address_index" parameter is used to guide the derivation. + * Returns an Account object, initialized with the secret key. + */ static newFromMnemonic( mnemonic: string, addressIndex: number = 0, @@ -70,7 +87,10 @@ export class Account implements IAccount { const secretKey = mnemonicHandler.deriveKey(addressIndex); return new Account(secretKey, hrp); } - + /** + * Named constructor + * Returns an Account object, initialized with the secret key. + */ static newFromKeypair(keypair: KeyPair, hrp: string = LibraryConfig.DefaultAddressHrp): Account { return new Account(keypair.secretKey, hrp); } @@ -83,58 +103,75 @@ export class Account implements IAccount { } /** - * Converts the account to a pretty, plain JavaScript object. + * Signs using the secret key of the account. */ - toJSON(): any { - return { - address: this.address.toBech32(), - nonce: this.nonce.valueOf(), - }; - } - async sign(data: Uint8Array): Promise { return this.secretKey.sign(data); } + /** + * Verifies the signature using the public key of the account. + */ async verify(data: Uint8Array, signature: Uint8Array): Promise { return this.publicKey.verify(data, signature); } + /** + * Serializes the transaction, computes the signature and returns it. + */ async signTransaction(transaction: Transaction): Promise { const transactionComputer = new TransactionComputer(); const serializedTransaction = transactionComputer.computeBytesForSigning(transaction); return this.secretKey.sign(serializedTransaction); } + /** + * Verifies the transaction signature using the public key of the account. + */ async verifyTransactionSignature(transaction: Transaction, signature: Uint8Array): Promise { const transactionComputer = new TransactionComputer(); const serializedTransaction = transactionComputer.computeBytesForVerifying(transaction); return this.publicKey.verify(serializedTransaction, signature); } + /** + * Serializes the message, computes the signature and returns it. + */ async signMessage(message: Message): Promise { const messageComputer = new MessageComputer(); const serializedMessage = messageComputer.computeBytesForSigning(message); return this.secretKey.sign(serializedMessage); } + /** + * Verifies the message signature using the public key of the account. + */ async verifyMessageSignature(message: Message, signature: Uint8Array): Promise { const messageComputer = new MessageComputer(); const serializedMessage = messageComputer.computeBytesForVerifying(message); return this.publicKey.verify(serializedMessage, signature); } + /** + * Gets the nonce (the one from the object's state) and increments it. + */ getNonceThenIncrement(): bigint { let nonce = this.nonce; this.nonce = this.nonce + 1n; return nonce; } + /** + * Saves the wallet to a pem file + */ saveToPem(path: string): void { const pem = new UserPem(this.address.toBech32(), this.secretKey); pem.save(path); } + /** + * Saves the wallet to a keystore file + */ saveToKeystore(path: PathLike, password: string): void { const wallet = UserWallet.fromSecretKey({ secretKey: this.secretKey, password }); wallet.save(path, this.address.getHrp()); diff --git a/src/core/address.ts b/src/core/address.ts index 67f40554c..ca7293a40 100644 --- a/src/core/address.ts +++ b/src/core/address.ts @@ -85,6 +85,7 @@ export class Address { } /** + * Named constructor * Creates an address object from a bech32-encoded string */ static newFromBech32(value: string): Address { @@ -102,6 +103,7 @@ export class Address { } /** + * Named constructor * Creates an address object from a hex-encoded string */ static newFromHex(value: string, hrp?: string): Address { @@ -123,29 +125,6 @@ export class Address { return Buffer.from(value, "hex").length == PUBKEY_LENGTH; } - /** - * Creates an empty address object. - * Generally speaking, this should not be used by client code (internal use only). - */ - static empty(): Address { - return new Address(""); - } - - /** - * Performs address validation without throwing errors - */ - static isValid(value: string): boolean { - const decoded = bech32.decodeUnsafe(value); - const prefix = decoded?.prefix; - const pubkey = decoded ? Buffer.from(bech32.fromWords(decoded.words)) : undefined; - - if (prefix !== LibraryConfig.DefaultAddressHrp || pubkey?.length !== PUBKEY_LENGTH) { - return false; - } - - return true; - } - /** * @deprecated Use {@link toHex} instead. */ @@ -192,7 +171,7 @@ export class Address { } /** - * Returns the pubkey as raw bytes (buffer) + * Returns the underlying public key. */ getPublicKey(): Buffer { return this.publicKey; @@ -205,6 +184,29 @@ export class Address { return this.hrp; } + /** + * Creates an empty address object. + * Generally speaking, this should not be used by client code (internal use only). + */ + static empty(): Address { + return new Address(""); + } + + /** + * Performs address validation without throwing errors + */ + static isValid(value: string): boolean { + const decoded = bech32.decodeUnsafe(value); + const prefix = decoded?.prefix; + const pubkey = decoded ? Buffer.from(bech32.fromWords(decoded.words)) : undefined; + + if (prefix !== LibraryConfig.DefaultAddressHrp || pubkey?.length !== PUBKEY_LENGTH) { + return false; + } + + return true; + } + /** * Returns whether the address is empty. */ @@ -269,7 +271,9 @@ export class AddressComputer { constructor(numberOfShardsWithoutMeta?: number) { this.numberOfShardsWithoutMeta = numberOfShardsWithoutMeta || CURRENT_NUMBER_OF_SHARDS_WITHOUT_META; } - + /** + * Note that the first input parameter is received as an interface, but the return value is a concrete type (see guidelines). + */ computeContractAddress(deployer: Address, deploymentNonce: bigint): Address { const initialPadding = Buffer.alloc(8, 0); const ownerPubkey = deployer.getPublicKey(); @@ -288,6 +292,9 @@ export class AddressComputer { return new Address(addressBytes); } + /** + * The number of shards (necessary for computing the shard ID) would be received as a constructor parameter - constructor is not captured by specs. + */ getShardOfAddress(address: Address): number { return this.getShardOfPubkey(address.getPublicKey(), this.numberOfShardsWithoutMeta); } From 2c7cb053cdb3e4f23d1ef6953318f88b068db126 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 13 Mar 2025 11:54:18 +0200 Subject: [PATCH 209/214] Remove unnecesary conversion --- src/abi/codec/codemetadata.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/abi/codec/codemetadata.ts b/src/abi/codec/codemetadata.ts index f487c00ae..458a465f4 100644 --- a/src/abi/codec/codemetadata.ts +++ b/src/abi/codec/codemetadata.ts @@ -8,7 +8,7 @@ export class CodeMetadataCodec { } decodeTopLevel(buffer: Buffer): CodeMetadataValue { - const codeMetadata = CodeMetadata.newFromBytes(new Uint8Array(buffer)); + const codeMetadata = CodeMetadata.newFromBytes(buffer); return new CodeMetadataValue(codeMetadata); } From 9aa22045b74ef18f76673eec32259b6f23480acb Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 13 Mar 2025 12:03:46 +0200 Subject: [PATCH 210/214] Code review follow up --- src/accounts/account.ts | 4 ++-- src/core/address.ts | 7 +------ src/core/codeMetadata.ts | 16 ++-------------- 3 files changed, 5 insertions(+), 22 deletions(-) diff --git a/src/accounts/account.ts b/src/accounts/account.ts index 9d5d8647e..ab3292c3a 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -60,7 +60,7 @@ export class Account implements IAccount { /** * Named constructor * Loads a secret key from an encrypted keystore file. Handles both keystores that hold a mnemonic and ones that hold a secret key (legacy). - * For keystores that hold an encrypted mnemonic, the optional "address_index" parameter is used to derive the desired secret key. + * For keystores that hold an encrypted mnemonic, the optional "addressIndex" parameter is used to derive the desired secret key. * Returns an Account object, initialized with the secret key. */ static newFromKeystore( @@ -75,7 +75,7 @@ export class Account implements IAccount { /** * Named constructor - * Loads (derives) a secret key from a mnemonic. The optional "address_index" parameter is used to guide the derivation. + * Loads (derives) a secret key from a mnemonic. The optional "addressIndex" parameter is used to guide the derivation. * Returns an Account object, initialized with the secret key. */ static newFromMnemonic( diff --git a/src/core/address.ts b/src/core/address.ts index ca7293a40..652ade8ef 100644 --- a/src/core/address.ts +++ b/src/core/address.ts @@ -271,9 +271,7 @@ export class AddressComputer { constructor(numberOfShardsWithoutMeta?: number) { this.numberOfShardsWithoutMeta = numberOfShardsWithoutMeta || CURRENT_NUMBER_OF_SHARDS_WITHOUT_META; } - /** - * Note that the first input parameter is received as an interface, but the return value is a concrete type (see guidelines). - */ + computeContractAddress(deployer: Address, deploymentNonce: bigint): Address { const initialPadding = Buffer.alloc(8, 0); const ownerPubkey = deployer.getPublicKey(); @@ -292,9 +290,6 @@ export class AddressComputer { return new Address(addressBytes); } - /** - * The number of shards (necessary for computing the shard ID) would be received as a constructor parameter - constructor is not captured by specs. - */ getShardOfAddress(address: Address): number { return this.getShardOfPubkey(address.getPublicKey(), this.numberOfShardsWithoutMeta); } diff --git a/src/core/codeMetadata.ts b/src/core/codeMetadata.ts index ccbac8fb7..77c682866 100644 --- a/src/core/codeMetadata.ts +++ b/src/core/codeMetadata.ts @@ -44,7 +44,7 @@ export class CodeMetadata { /** * Named constructor * Creates a metadata object from a buffer. - * Should check that data has correct length (2 bytes) + * Also checks that data has correct length (2 bytes) */ static newFromBytes(bytes: Uint8Array): CodeMetadata { if (bytes.length != CodeMetadataLength) { @@ -67,19 +67,7 @@ export class CodeMetadata { * Creates a metadata object from a buffer. */ static newFromBuffer(buffer: Buffer): CodeMetadata { - if (buffer.length != CodeMetadataLength) { - throw new Error(`code metadata buffer has length ${buffer.length}, expected ${CodeMetadataLength}`); - } - - const byteZero = buffer[0]; - const byteOne = buffer[1]; - - const upgradeable = (byteZero & CodeMetadata.ByteZero.Upgradeable) !== 0; - const readable = (byteZero & CodeMetadata.ByteZero.Readable) !== 0; - const payable = (byteOne & CodeMetadata.ByteOne.Payable) !== 0; - const payableBySc = (byteOne & CodeMetadata.ByteOne.PayableBySc) !== 0; - - return new CodeMetadata(upgradeable, readable, payable, payableBySc); + return this.newFromBytes(buffer); } /** From dcb127d7f60e2dc711072b00fab5d4e4532ef9e3 Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 13 Mar 2025 14:45:34 +0200 Subject: [PATCH 211/214] Add description and delete unnecesary code --- src/accountManagement/accountController.ts | 2 +- src/accounts/account.ts | 9 +- src/accounts/index.ts | 1 - src/accounts/interfaces.ts | 12 -- src/core/index.ts | 2 +- src/core/{interface.ts => interfaces.ts} | 13 ++ src/core/message.ts | 7 + src/core/tokens.ts | 40 +++- src/core/transaction.spec.ts | 2 +- src/core/transaction.ts | 60 +++--- src/core/transactionComputer.ts | 26 ++- src/core/transactionWatcher.ts | 2 +- src/delegation/delegationController.ts | 16 +- src/entrypoints/entrypoints.ts | 56 +++++- src/networkProviders/accounts.ts | 58 ++++++ src/networkProviders/apiNetworkProvider.ts | 37 ++-- src/networkProviders/blocks.ts | 82 +++++++++ src/networkProviders/index.ts | 7 +- src/networkProviders/interface.ts | 33 ++-- src/networkProviders/pairs.ts | 54 ------ src/networkProviders/proxyNetworkProvider.ts | 36 ++-- src/networkProviders/resources.ts | 172 ------------------ src/networkProviders/tokens.ts | 34 +++- src/networkProviders/transactionReceipt.ts | 24 --- src/smartContracts/smartContractController.ts | 23 ++- .../smartContractTransactionsOutcomeParser.ts | 4 + src/testutils/mockNetworkProvider.ts | 13 +- .../tokenManagementController.ts | 16 +- src/transfers/transfersControllers.ts | 12 +- src/wallet/index.ts | 1 + 30 files changed, 441 insertions(+), 413 deletions(-) delete mode 100644 src/accounts/interfaces.ts rename src/core/{interface.ts => interfaces.ts} (62%) create mode 100644 src/networkProviders/blocks.ts delete mode 100644 src/networkProviders/pairs.ts delete mode 100644 src/networkProviders/transactionReceipt.ts diff --git a/src/accountManagement/accountController.ts b/src/accountManagement/accountController.ts index f34ddeb4f..90f747c10 100644 --- a/src/accountManagement/accountController.ts +++ b/src/accountManagement/accountController.ts @@ -1,5 +1,5 @@ -import { IAccount } from "../accounts/interfaces"; import { Address, BaseController, BaseControllerInput } from "../core"; +import { IAccount } from "../core/interfaces"; import { Transaction } from "../core/transaction"; import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; import { AccountTransactionsFactory } from "./accountTransactionsFactory"; diff --git a/src/accounts/account.ts b/src/accounts/account.ts index ab3292c3a..f32e54833 100644 --- a/src/accounts/account.ts +++ b/src/accounts/account.ts @@ -1,12 +1,7 @@ import * as fs from "fs"; import { PathLike } from "fs"; -import { Message, MessageComputer, TransactionComputer } from "../core"; -import { Address } from "../core/address"; -import { LibraryConfig } from "../core/config"; -import { Transaction } from "../core/transaction"; -import { KeyPair, Mnemonic, UserPublicKey, UserSecretKey, UserSigner, UserWallet } from "../wallet"; -import { UserPem } from "../wallet/userPem"; -import { IAccount } from "./interfaces"; +import { Address, IAccount, LibraryConfig, Message, MessageComputer, Transaction, TransactionComputer } from "../core"; +import { KeyPair, Mnemonic, UserPem, UserPublicKey, UserSecretKey, UserSigner, UserWallet } from "../wallet"; /** * An abstraction representing an account (user or Smart Contract) on the Network. diff --git a/src/accounts/index.ts b/src/accounts/index.ts index 5b58bd041..ed4079f3e 100644 --- a/src/accounts/index.ts +++ b/src/accounts/index.ts @@ -1,2 +1 @@ export * from "./account"; -export * from "./interfaces"; diff --git a/src/accounts/interfaces.ts b/src/accounts/interfaces.ts deleted file mode 100644 index a10b9e943..000000000 --- a/src/accounts/interfaces.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Message, Transaction } from "../core"; -import { Address } from "../core/address"; - -export interface IAccount { - readonly address: Address; - - sign(data: Uint8Array): Promise; - signTransaction(transaction: Transaction): Promise; - verifyTransactionSignature(transaction: Transaction, signature: Uint8Array): Promise; - signMessage(message: Message): Promise; - verifyMessageSignature(message: Message, signature: Uint8Array): Promise; -} diff --git a/src/core/index.ts b/src/core/index.ts index 78be0e4a7..cc5f927df 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -6,7 +6,7 @@ export * from "./baseController"; export * from "./codeMetadata"; export * from "./config"; export * from "./errors"; -export * from "./interface"; +export * from "./interfaces"; export * from "./logger"; export * from "./message"; export * from "./networkParams"; diff --git a/src/core/interface.ts b/src/core/interfaces.ts similarity index 62% rename from src/core/interface.ts rename to src/core/interfaces.ts index eb2d5283c..fee8dc136 100644 --- a/src/core/interface.ts +++ b/src/core/interfaces.ts @@ -1,3 +1,16 @@ +import { Message, Transaction } from "."; +import { Address } from "./address"; + +export interface IAccount { + readonly address: Address; + + sign(data: Uint8Array): Promise; + signTransaction(transaction: Transaction): Promise; + verifyTransactionSignature(transaction: Transaction, signature: Uint8Array): Promise; + signMessage(message: Message): Promise; + verifyMessageSignature(message: Message, signature: Uint8Array): Promise; +} + import { TransactionOnNetwork } from "./transactionOnNetwork"; export interface ITransactionFetcher { diff --git a/src/core/message.ts b/src/core/message.ts index 03bbde1a6..e7452904b 100644 --- a/src/core/message.ts +++ b/src/core/message.ts @@ -51,6 +51,9 @@ export class MessageComputer { return createKeccakHash("keccak256").update(bytesToHash).digest(); } + /** + * returns the result of `compute_bytes_for_signing() + */ computeBytesForVerifying(message: Message): Uint8Array { return this.computeBytesForSigning(message); } @@ -71,6 +74,10 @@ export class MessageComputer { }; } + /** + * packed_message should be the one obtained from calling `pack_message()` + * should treat both 'legacy message' and current message + */ unpackMessage(packedMessage: { message: string; signature?: string; diff --git a/src/core/tokens.ts b/src/core/tokens.ts index bd1ff3098..f2ae30b27 100644 --- a/src/core/tokens.ts +++ b/src/core/tokens.ts @@ -21,6 +21,9 @@ interface ILegacyTokenTransferOptions { export type TokenType = "NFT" | "SFT" | "META" | "FNG"; export class Token { + /** + * E.g. "FOO-abcdef", "EGLD". + */ readonly identifier: string; readonly nonce: bigint; @@ -88,6 +91,10 @@ export class TokenTransfer { } } + /** * + * @param amount + * @returns @TokenTransfer from native token + */ static newFromNativeAmount(amount: bigint): TokenTransfer { const token = new Token({ identifier: EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER }); return new TokenTransfer({ token, amount }); @@ -98,7 +105,7 @@ export class TokenTransfer { } /** - * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use {@link newFromNativeAmount} instead. */ static egldFromAmount(amount: BigNumber.Value) { const amountAsBigInteger = new BigNumber(amount).shiftedBy(EGLDNumDecimals).decimalPlaces(0); @@ -106,7 +113,7 @@ export class TokenTransfer { } /** - * @deprecated Use the constructor instead: new TokenTransfer({ token, amount }); + * @deprecated Use {@link newFromNativeAmount} instead. */ static egldFromBigInteger(amountAsBigInteger: BigNumber.Value) { return new TokenTransfer({ @@ -232,10 +239,16 @@ export class TokenComputer { TOKEN_RANDOM_SEQUENCE_LENGTH = 6; constructor() {} + /** + * Returns token.nonce == 0 + */ isFungible(token: Token): boolean { return token.nonce === 0n; } + /** + * Given "FOO-abcdef-0a" returns 10. + */ extractNonceFromExtendedIdentifier(identifier: string): number { const parts = identifier.split("-"); @@ -252,6 +265,9 @@ export class TokenComputer { return decodeUnsignedNumber(Buffer.from(hexNonce, "hex")); } + /** + * Given "FOO-abcdef-0a" returns FOO-abcdef. + */ extractIdentifierFromExtendedIdentifier(identifier: string): string { const parts = identifier.split("-"); const { prefix, ticker, randomSequence } = this.splitIdentifierIntoComponents(parts); @@ -264,6 +280,22 @@ export class TokenComputer { return ticker + "-" + randomSequence; } + /** + * Given "FOO-abcdef-0a" returns FOO. + * Given "FOO-abcdef" returns FOO. + */ + extractTickerFromExtendedIdentifier(identifier: string): string { + const parts = identifier.split("-"); + const { prefix, ticker, randomSequence } = this.splitIdentifierIntoComponents(parts); + + this.validateExtendedIdentifier(prefix, ticker, randomSequence, parts); + if (prefix) { + this.checkLengthOfPrefix(prefix); + return prefix + "-" + ticker + "-" + randomSequence; + } + return ticker; + } + computeExtendedIdentifier(token: Token): string { const parts = token.identifier.split("-"); const { prefix, ticker, randomSequence } = this.splitIdentifierIntoComponents(parts); @@ -315,10 +347,6 @@ export class TokenComputer { } } - private isLowercaseAlphanumeric(str: string): boolean { - return /^[a-z0-9]+$/.test(str); - } - private checkLengthOfRandomSequence(randomSequence: string): void { if (randomSequence.length !== this.TOKEN_RANDOM_SEQUENCE_LENGTH) { throw new ErrInvalidTokenIdentifier( diff --git a/src/core/transaction.spec.ts b/src/core/transaction.spec.ts index d6d8ffcd2..ec54350ae 100644 --- a/src/core/transaction.spec.ts +++ b/src/core/transaction.spec.ts @@ -5,7 +5,7 @@ import { ProtoSerializer } from "../proto"; import { getTestWalletsPath } from "../testutils/utils"; import { Address } from "./address"; import { MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS, TRANSACTION_OPTIONS_DEFAULT } from "./constants"; -import { INetworkConfig } from "./interface"; +import { INetworkConfig } from "./interfaces"; import { Transaction } from "./transaction"; import { TransactionComputer } from "./transactionComputer"; diff --git a/src/core/transaction.ts b/src/core/transaction.ts index 8f27ab997..00de7a681 100644 --- a/src/core/transaction.ts +++ b/src/core/transaction.ts @@ -1,7 +1,7 @@ import { BigNumber } from "bignumber.js"; import { Address } from "./address"; import { TRANSACTION_MIN_GAS_PRICE, TRANSACTION_OPTIONS_DEFAULT, TRANSACTION_VERSION_DEFAULT } from "./constants"; -import { INetworkConfig, IPlainTransactionObject } from "./interface"; +import { INetworkConfig, IPlainTransactionObject } from "./interfaces"; import { interpretSignatureAsBuffer } from "./signature"; import { TransactionComputer } from "./transactionComputer"; @@ -138,14 +138,14 @@ export class Transaction { } /** - * @deprecated method, use the "nonce" property instead. + * @deprecated method, use {@link nonce} property instead. */ getNonce(): bigint { return this.nonce; } /** - * @deprecated method, use the "nonce" property instead. + * @deprecated method, use {@link nonce} property instead. * Sets the account sequence number of the sender. Must be done prior signing. */ setNonce(nonce: bigint) { @@ -153,147 +153,147 @@ export class Transaction { } /** - * @deprecated method, use the "value" property instead. + * @deprecated method, use {@link value} property instead. */ getValue(): bigint { return this.value; } /** - * @deprecated method, use the "value" property instead. + * @deprecated method, use {@link value} property instead. */ setValue(value: bigint) { this.value = value; } /** - * @deprecated method, use the "sender" property instead. + * @deprecated method, use {@link sender} property instead. */ getSender(): Address { return this.sender; } /** - * @deprecated method, use the "sender" property instead. + * @deprecated method, use {@link sender} property instead. */ setSender(sender: Address) { this.sender = sender; } /** - * @deprecated method, use the "receiver" property instead. + * @deprecated method, use {@link receiver} property instead. */ getReceiver(): Address { return this.receiver; } /** - * @deprecated method, use the "senderUsername" property instead. + * @deprecated method, use {@link senderUsername} property instead. */ getSenderUsername(): string { return this.senderUsername; } /** - * @deprecated method, use the "senderUsername" property instead. + * @deprecated method, use {@link senderUsername} property instead. */ setSenderUsername(senderUsername: string) { this.senderUsername = senderUsername; } /** - * @deprecated method, use the "receiverUsername" property instead. + * @deprecated method, use {@link receiverUsername} property instead. */ getReceiverUsername(): string { return this.receiverUsername; } /** - * @deprecated method, use the "receiverUsername" property instead. + * @deprecated method, use {@link receiverUsername} property instead. */ setReceiverUsername(receiverUsername: string) { this.receiverUsername = receiverUsername; } /** - * @deprecated method, use the "guardian" property instead. + * @deprecated method, use {@link guardian} property instead. */ getGuardian(): Address { return this.guardian; } /** - * @deprecated method, use the "gasPrice" property instead. + * @deprecated method, use {@link gasPrice} property instead. */ getGasPrice(): bigint { return this.gasPrice; } /** - * @deprecated method, use the "gasPrice" property instead. + * @deprecated method, use {@link gasPrice} property instead. */ setGasPrice(gasPrice: bigint) { this.gasPrice = gasPrice; } /** - * @deprecated method, use the "gasLimit" property instead. + * @deprecated method, use {@link gasLimit} property instead. */ getGasLimit(): bigint { return this.gasLimit; } /** - * @deprecated method, use the "gasLimit" property instead. + * @deprecated method, use {@link gasLimit} property instead. */ setGasLimit(gasLimit: bigint) { this.gasLimit = gasLimit; } /** - * @deprecated method, use the "data" property instead. + * @deprecated method, use {@link data} property instead. */ getData(): Uint8Array { return this.data; } /** - * @deprecated method, use the "chainID" property instead. + * @deprecated method, use {@link chainID} property instead. */ getChainID(): string { return this.chainID; } /** - * @deprecated method, use the "chainID" property instead. + * @deprecated method, use {@link chainID} property instead. */ setChainID(chainID: string) { this.chainID = chainID; } /** - * @deprecated method, use the "version" property instead. + * @deprecated method, use {@link version} property instead. */ getVersion(): number { return this.version; } /** - * @deprecated method, use the "version" property instead. + * @deprecated method, use {@link version} property instead. */ setVersion(version: number) { this.version = version; } /** - * @deprecated method, use the "options" property instead. + * @deprecated method, use {@link options} property instead. */ getOptions(): number { return this.options; } /** - * @deprecated method, use the "options" property instead. + * @deprecated method, use {@link options} property instead. * * Question for review: check how the options are set by sdk-dapp, wallet, ledger, extension. */ @@ -302,21 +302,21 @@ export class Transaction { } /** - * @deprecated method, use the "signature" property instead. + * @deprecated method, use{@link signature} property instead. */ getSignature(): Buffer { return Buffer.from(this.signature); } /** - * @deprecated method, use the "guardianSignature" property instead. + * @deprecated method, use {@link guardianSignature} property instead. */ getGuardianSignature(): Buffer { return Buffer.from(this.guardianSignature); } /** - * @deprecated method, use the "guardian" property instead. + * @deprecated method, use {@link guardian} property instead. */ setGuardian(guardian: Address) { this.guardian = guardian; @@ -372,7 +372,7 @@ export class Transaction { } /** - * @deprecated method, use "Transaction.newFromPlainObject()" instead. + * @deprecated method, use {@link toPlainObject} instead. * Converts a plain object transaction into a Transaction Object. * * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() @@ -415,7 +415,7 @@ export class Transaction { } /** - * @deprecated method, use the "signature" property instead. + * @deprecated method, use {@link signature} property instead. * Applies the signature on the transaction. * * @param signature The signature, as computed by a signer. @@ -425,7 +425,7 @@ export class Transaction { } /** - * @deprecated method, use the "guardianSignature" property instead. + * @deprecated method, use {@link guardianSignature} property instead. * Applies the guardian signature on the transaction. * * @param guardianSignature The signature, as computed by a signer. diff --git a/src/core/transactionComputer.ts b/src/core/transactionComputer.ts index 4e65a3000..81cbb08f2 100644 --- a/src/core/transactionComputer.ts +++ b/src/core/transactionComputer.ts @@ -7,7 +7,7 @@ import { TRANSACTION_OPTIONS_TX_HASH_SIGN, } from "./constants"; import * as errors from "./errors"; -import { INetworkConfig } from "./interface"; +import { INetworkConfig } from "./interfaces"; import { Transaction } from "./transaction"; const createTransactionHasher = require("blake2b"); @@ -46,6 +46,9 @@ export class TransactionComputer { return feeForMove + processingFee; } + /** + * Compute bytes for signing the transaction + */ computeBytesForSigning(transaction: Transaction): Uint8Array { this.ensureValidTransactionFields(transaction); @@ -54,6 +57,9 @@ export class TransactionComputer { return new Uint8Array(Buffer.from(serialized)); } + /** + * Compute bytes for verifying the transaction signature + */ computeBytesForVerifying(transaction: Transaction): Uint8Array { const isTxSignedByHash = this.hasOptionsSetForHashSigning(transaction); @@ -63,6 +69,9 @@ export class TransactionComputer { return this.computeBytesForSigning(transaction); } + /** + * Serializes the transaction then computes the hash; used for hash signing transactions. + */ computeHashForSigning(transaction: Transaction): Uint8Array { const plainTransaction = this.toPlainObject(transaction); const signable = Buffer.from(JSON.stringify(plainTransaction)); @@ -77,14 +86,23 @@ export class TransactionComputer { return Buffer.from(hash, "hex").toString("hex"); } + /** + * Returns true if the second least significant bit is set; returns false otherwise + */ hasOptionsSetForGuardedTransaction(transaction: Transaction): boolean { return (transaction.options & TRANSACTION_OPTIONS_TX_GUARDED) == TRANSACTION_OPTIONS_TX_GUARDED; } + /** + * Returns true if the least significant bit is set; returns false otherwise; should also have transaction.version >= 2 + */ hasOptionsSetForHashSigning(transaction: Transaction): boolean { return (transaction.options & TRANSACTION_OPTIONS_TX_HASH_SIGN) == TRANSACTION_OPTIONS_TX_HASH_SIGN; } + /** + * Sets guardian address, transaction.version = 2, sets transaction.options second least significant bit + */ applyGuardian(transaction: Transaction, guardian: Address) { if (transaction.version < MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { transaction.version = MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; @@ -94,10 +112,16 @@ export class TransactionComputer { transaction.guardian = guardian; } + /** + * Returns true if transaction.relayer is set; returns false otherwise; + */ isRelayedV3Transaction(transaction: Transaction) { return !transaction.relayer.isEmpty(); } + /** + * Sets the least significant bit of the `options` field; also ensures that `version` >= 2 + */ applyOptionsForHashSigning(transaction: Transaction) { if (transaction.version < MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { transaction.version = MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; diff --git a/src/core/transactionWatcher.ts b/src/core/transactionWatcher.ts index e6654a181..0f1826b83 100644 --- a/src/core/transactionWatcher.ts +++ b/src/core/transactionWatcher.ts @@ -5,7 +5,7 @@ import { ErrExpectedTransactionStatusNotReached, ErrIsCompletedFieldIsMissingOnTransaction, } from "./errors"; -import { ITransactionFetcher } from "./interface"; +import { ITransactionFetcher } from "./interfaces"; import { Logger } from "./logger"; import { TransactionEvent } from "./transactionEvents"; import { TransactionOnNetwork } from "./transactionOnNetwork"; diff --git a/src/delegation/delegationController.ts b/src/delegation/delegationController.ts index ecba3f986..1f4384caf 100644 --- a/src/delegation/delegationController.ts +++ b/src/delegation/delegationController.ts @@ -1,9 +1,13 @@ -import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController, BaseControllerInput } from "../core"; -import { Transaction } from "../core/transaction"; -import { TransactionOnNetwork } from "../core/transactionOnNetwork"; -import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; -import { TransactionWatcher } from "../core/transactionWatcher"; +import { + Address, + BaseController, + BaseControllerInput, + IAccount, + Transaction, + TransactionOnNetwork, + TransactionsFactoryConfig, + TransactionWatcher, +} from "../core"; import { INetworkProvider } from "../networkProviders/interface"; import { DelegationTransactionsFactory } from "./delegationTransactionsFactory"; import { DelegationTransactionsOutcomeParser } from "./delegationTransactionsOutcomeParser"; diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index 5a75498da..a9b0a6739 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -1,22 +1,23 @@ import { Abi } from "../abi"; import { AccountController, AccountTransactionsFactory } from "../accountManagement"; import { Account } from "../accounts"; -import { IAccount } from "../accounts/interfaces"; -import { Address } from "../core/address"; -import { ErrInvalidNetworkProviderKind } from "../core/errors"; -import { Message } from "../core/message"; -import { Transaction } from "../core/transaction"; -import { TransactionOnNetwork } from "../core/transactionOnNetwork"; -import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; -import { TransactionWatcher } from "../core/transactionWatcher"; +import { + Address, + ErrInvalidNetworkProviderKind, + IAccount, + Message, + Transaction, + TransactionOnNetwork, + TransactionsFactoryConfig, + TransactionWatcher, +} from "../core"; import { DelegationController, DelegationTransactionsFactory } from "../delegation"; import { ApiNetworkProvider, ProxyNetworkProvider } from "../networkProviders"; import { INetworkProvider } from "../networkProviders/interface"; import { SmartContractTransactionsFactory } from "../smartContracts"; import { SmartContractController } from "../smartContracts/smartContractController"; import { TokenManagementController, TokenManagementTransactionsFactory } from "../tokenManagement"; -import { TransferTransactionsFactory } from "../transfers"; -import { TransfersController } from "../transfers/transfersControllers"; +import { TransfersController, TransferTransactionsFactory } from "../transfers"; import { UserSecretKey } from "../wallet"; import { DevnetEntrypointConfig, MainnetEntrypointConfig, TestnetEntrypointConfig } from "./config"; @@ -36,11 +37,17 @@ class NetworkEntrypoint { this.chainId = options.chainId; } + /** + * Creates a new Account by generating a new secret key and instantiating an UserSigner + */ async createAccount(): Promise { const secretKey = UserSecretKey.generate(); return new Account(secretKey); } + /** + * Calls a faucet + */ async getAirdrop(_address: Address): Promise { throw new Error("Not implemented"); } @@ -49,10 +56,20 @@ class NetworkEntrypoint { transaction.signature = await account.signTransaction(transaction); } + /** + * Verifies if the signature field is valid + * @param transaction + * @param account + */ async verifyTransactionSignature(transaction: Transaction, account: IAccount): Promise { return await account.verifyTransactionSignature(transaction, transaction.signature); } + /** + * Verifies if message signature is valid + * @param message + * @param account + */ async verifyMessageSignature(message: Message, account: IAccount): Promise { if (!message.address) { throw new Error("`address` property of Message is not set"); @@ -65,18 +82,34 @@ class NetworkEntrypoint { return await account.verifyMessageSignature(message, message.signature); } + /** + * Fetches the account nonce from the network. + * @param address + */ async recallAccountNonce(address: Address): Promise { return (await this.networkProvider.getAccount(address)).nonce; } + /** + * Function of the network provider, promoted to the facade. + * @param transactions + */ sendTransactions(transactions: Transaction[]): Promise<[number, string[]]> { return this.networkProvider.sendTransactions(transactions); } + /** + * Function of the network provider, promoted to the facade. + * @param transaction + */ sendTransaction(transaction: Transaction): Promise { return this.networkProvider.sendTransaction(transaction); } + /** + * Generic function to await a transaction on the network. + * @param txHash + */ async awaitCompletedTransaction(txHash: string): Promise { const transactionAwaiter = new TransactionWatcher(this.networkProvider); return transactionAwaiter.awaitCompleted(txHash); @@ -86,6 +119,9 @@ class NetworkEntrypoint { return this.networkProvider.getTransaction(txHash); } + /** + * Access to the underlying network provider. + */ createNetworkProvider(): INetworkProvider { return this.networkProvider; } diff --git a/src/networkProviders/accounts.ts b/src/networkProviders/accounts.ts index d79722fe4..1be9ce39f 100644 --- a/src/networkProviders/accounts.ts +++ b/src/networkProviders/accounts.ts @@ -1,4 +1,6 @@ +import { BytesValue } from "../abi"; import { Address, CodeMetadata } from "../core"; +import { BlockCoordinates } from "./blocks"; /** * A plain view of an account, as queried from the Network. @@ -124,3 +126,59 @@ export class Guardian { return result; } } +export class AccountStorageEntry { + raw: Record = {}; + address: Address = Address.empty(); + key: string = ""; + value: string = ""; + + constructor(init?: Partial) { + Object.assign(this, init); + } + + static fromHttpResponse(payload: any, key: string): AccountStorageEntry { + const result = new AccountStorageEntry(); + const value = payload["value"] || ""; + + result.raw = payload; + result.key = key; + result.value = BytesValue.fromHex(value).toString(); + + return result; + } +} + +/** + * A plain view of an account storage. + */ + +export class AccountStorage { + raw: Record = {}; + blockCoordinates!: BlockCoordinates; + entries: AccountStorageEntry[] = []; + constructor(init?: Partial) { + Object.assign(this, init); + } + + static fromHttpResponse(payload: any): AccountStorage { + let result = new AccountStorage(); + + const pairs = payload["pairs"] || {}; + const entries: AccountStorageEntry[] = Object.entries(pairs).map(([key, value]) => { + const decodedKey = Buffer.from(key, "hex").toString("utf8"); + const val: string = value ? (value as string).toString() : ""; + const decodedValue = Buffer.from(val).toString(); + + return new AccountStorageEntry({ + raw: { [key]: value }, + key: decodedKey, + value: decodedValue, + }); + }); + result.raw = payload; + result.entries = entries; + result.blockCoordinates = BlockCoordinates.fromHttpResponse(payload); + + return result; + } +} diff --git a/src/networkProviders/apiNetworkProvider.ts b/src/networkProviders/apiNetworkProvider.ts index 4f24841eb..bedf6dcd3 100644 --- a/src/networkProviders/apiNetworkProvider.ts +++ b/src/networkProviders/apiNetworkProvider.ts @@ -1,15 +1,22 @@ -import { Address } from "../core/address"; +import { + Address, + ErrContractQuery, + ErrNetworkProvider, + getAxios, + prepareTransactionForBroadcasting, + SmartContractQuery, + SmartContractQueryResponse, + Token, + TokenComputer, + Transaction, + TransactionOnNetwork, + TransactionStatus, + TransactionWatcher, +} from "../core"; import { METACHAIN_ID } from "../core/constants"; -import { ErrContractQuery, ErrNetworkProvider } from "../core/errors"; -import { SmartContractQuery, SmartContractQueryResponse } from "../core/smartContractQuery"; -import { Token, TokenComputer } from "../core/tokens"; -import { Transaction } from "../core/transaction"; -import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../core/transactionOnNetwork"; -import { TransactionStatus } from "../core/transactionStatus"; -import { TransactionWatcher } from "../core/transactionWatcher"; -import { getAxios } from "../core/utils"; import { AccountAwaiter } from "./accountAwaiter"; -import { AccountOnNetwork } from "./accounts"; +import { AccountOnNetwork, AccountStorage, AccountStorageEntry } from "./accounts"; +import { BlockOnNetwork } from "./blocks"; import { defaultAxiosConfig, defaultPagination } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; @@ -18,15 +25,9 @@ import { NetworkConfig } from "./networkConfig"; import { NetworkProviderConfig } from "./networkProviderConfig"; import { NetworkStatus } from "./networkStatus"; import { ProxyNetworkProvider } from "./proxyNetworkProvider"; -import { - AccountStorage, - AccountStorageEntry, - AwaitingOptions, - BlockOnNetwork, - TokenAmountOnNetwork, - TransactionCostResponse, -} from "./resources"; +import { AwaitingOptions, TransactionCostResponse } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; +import { TokenAmountOnNetwork } from "./tokens"; import { extendUserAgentIfBackend } from "./userAgent"; // TODO: Find & remove duplicate code between "ProxyNetworkProvider" and "ApiNetworkProvider". diff --git a/src/networkProviders/blocks.ts b/src/networkProviders/blocks.ts new file mode 100644 index 000000000..bab275760 --- /dev/null +++ b/src/networkProviders/blocks.ts @@ -0,0 +1,82 @@ +/** + * An object holding network status configuration parameters. + */ + +export class BlockOnNetwork { + /** + * The raw data return by provider. + */ + public raw: Record = {}; + + /** + * The shard number. + */ + public shard: number = 0; + + /** + * The shard nonce. + */ + public nonce: bigint = 0n; + + /** + * The block hash. + */ + public hash: string = ""; + + /** + * The block previous hash. + */ + public previousHash: string = ""; + + /** + * The block timestamp. + */ + public timestamp: number = 0; + + /** + * The block timestamp. + */ + public round: number = 0; + + /** + * The block timestamp. + */ + public epoch: number = 0; + + /** + * Constructs a configuration object from a HTTP response (as returned by the provider). + */ + static fromHttpResponse(payload: any): BlockOnNetwork { + let blockOnNetwork = new BlockOnNetwork(); + + blockOnNetwork.raw = payload; + blockOnNetwork.shard = Number(payload["shard"]) ?? 0; + blockOnNetwork.nonce = BigInt(payload["nonce"] ?? 0); + blockOnNetwork.hash = payload["hash"] ?? ""; + blockOnNetwork.previousHash = payload["prevBlockHash"] ?? payload["prevHash"] ?? ""; + blockOnNetwork.timestamp = Number(payload["timestamp"] ?? 0); + blockOnNetwork.round = Number(payload["round"] ?? 0); + blockOnNetwork.epoch = Number(payload["epoch"] ?? 0); + + return blockOnNetwork; + } +} + +export class BlockCoordinates { + nonce: bigint = 0n; + hash: string = ""; + rootHash: string = ""; + constructor(init?: Partial) { + Object.assign(this, init); + } + static fromHttpResponse(payload: any): BlockCoordinates { + const result = new BlockCoordinates(); + const value = payload["blockInfo"] || {}; + + result.nonce = value["nonce"] || 0n; + result.hash = value["hash"] || ""; + result.rootHash = value["rootHash"] || ""; + + return result; + } +} diff --git a/src/networkProviders/index.ts b/src/networkProviders/index.ts index 502cddf47..97f5dffa9 100644 --- a/src/networkProviders/index.ts +++ b/src/networkProviders/index.ts @@ -4,13 +4,12 @@ export { ProxyNetworkProvider } from "./proxyNetworkProvider"; export { ContractQueryResponse } from "./contractQueryResponse"; export { ContractResultItem, ContractResults } from "./contractResults"; -export { TransactionReceipt } from "./transactionReceipt"; - -export { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; -export { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens"; export * from "./accounts"; +export * from "./blocks"; export { NetworkConfig } from "./networkConfig"; export { NetworkProviderConfig } from "./networkProviderConfig"; export { NetworkStatus } from "./networkStatus"; export * from "./resources"; +export * from "./tokenDefinitions"; +export * from "./tokens"; diff --git a/src/networkProviders/interface.ts b/src/networkProviders/interface.ts index 1e845a12e..0920d8474 100644 --- a/src/networkProviders/interface.ts +++ b/src/networkProviders/interface.ts @@ -1,20 +1,18 @@ -import { Address } from "../core/address"; -import { SmartContractQuery, SmartContractQueryResponse } from "../core/smartContractQuery"; -import { Token } from "../core/tokens"; -import { Transaction } from "../core/transaction"; -import { TransactionOnNetwork } from "../core/transactionOnNetwork"; -import { TransactionStatus } from "../core/transactionStatus"; -import { AccountOnNetwork } from "./accounts"; +import { + Address, + SmartContractQuery, + SmartContractQueryResponse, + Token, + Transaction, + TransactionOnNetwork, + TransactionStatus, +} from "../core"; +import { AccountOnNetwork, AccountStorage, AccountStorageEntry } from "./accounts"; import { NetworkConfig } from "./networkConfig"; import { NetworkStatus } from "./networkStatus"; -import { - AccountStorage, - AccountStorageEntry, - AwaitingOptions, - TokenAmountOnNetwork, - TransactionCostResponse, -} from "./resources"; +import { AwaitingOptions, TransactionCostResponse } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; +import { TokenAmountOnNetwork } from "./tokens"; /** * An interface that defines the endpoints of an HTTP API Provider. @@ -62,14 +60,11 @@ export interface INetworkProvider { sendTransaction(tx: Transaction): Promise; /** - * Simulates the processing of an already-signed transaction. - * + * Simulates the processing of an already-signed transaction. * */ simulateTransaction(tx: Transaction): Promise; - /** - * Estimates the cost of a transaction. - * + * Estimates the cost of a transaction. * */ estimateTransactionCost(tx: Transaction): Promise; diff --git a/src/networkProviders/pairs.ts b/src/networkProviders/pairs.ts deleted file mode 100644 index 26e2605a1..000000000 --- a/src/networkProviders/pairs.ts +++ /dev/null @@ -1,54 +0,0 @@ -import BigNumber from "bignumber.js"; -import { Address } from "../core/address"; - -export class PairOnNetwork { - address: Address = Address.empty(); - id: string = ""; - symbol: string = ""; - name: string = ""; - price: BigNumber = new BigNumber(0); - baseId: string = ""; - basePrice: BigNumber = new BigNumber(0); - baseSymbol: string = ""; - baseName: string = ""; - quoteId: string = ""; - quotePrice: BigNumber = new BigNumber(0); - quoteSymbol: string = ""; - quoteName: string = ""; - totalValue: BigNumber = new BigNumber(0); - volume24h: BigNumber = new BigNumber(0); - state: string = ""; - type: string = ""; - - rawResponse: any = {}; - - constructor(init?: Partial) { - Object.assign(this, init); - } - - static fromApiHttpResponse(payload: any): PairOnNetwork { - const result = new PairOnNetwork(); - - result.address = new Address(payload.address || ""); - result.id = payload.id || ""; - result.symbol = payload.symbol || ""; - result.name = payload.name || ""; - result.price = new BigNumber(payload.price || 0); - result.baseId = payload.baseId || ""; - result.basePrice = new BigNumber(payload.basePrice || 0); - result.baseSymbol = payload.baseSymbol || ""; - result.baseName = payload.baseName || ""; - result.quoteId = payload.quoteId || ""; - result.quotePrice = new BigNumber(payload.quotePrice || 0); - result.quoteSymbol = payload.quoteSymbol || ""; - result.quoteName = payload.quoteName || ""; - result.totalValue = new BigNumber(payload.totalValue || 0); - result.volume24h = new BigNumber(payload.volume24h || 0); - result.state = payload.state || ""; - result.type = payload.type || ""; - - result.rawResponse = payload; - - return result; - } -} diff --git a/src/networkProviders/proxyNetworkProvider.ts b/src/networkProviders/proxyNetworkProvider.ts index 8882c961b..f62f632bb 100644 --- a/src/networkProviders/proxyNetworkProvider.ts +++ b/src/networkProviders/proxyNetworkProvider.ts @@ -1,15 +1,21 @@ -import { Address } from "../core/address"; +import { + Address, + ErrContractQuery, + ErrNetworkProvider, + getAxios, + prepareTransactionForBroadcasting, + SmartContractQuery, + SmartContractQueryResponse, + Token, + Transaction, + TransactionOnNetwork, + TransactionStatus, + TransactionWatcher, +} from "../core"; import { ESDT_CONTRACT_ADDRESS_HEX, METACHAIN_ID } from "../core/constants"; -import { ErrContractQuery, ErrNetworkProvider } from "../core/errors"; -import { SmartContractQuery, SmartContractQueryResponse } from "../core/smartContractQuery"; -import { Token } from "../core/tokens"; -import { Transaction } from "../core/transaction"; -import { prepareTransactionForBroadcasting, TransactionOnNetwork } from "../core/transactionOnNetwork"; -import { TransactionStatus } from "../core/transactionStatus"; -import { TransactionWatcher } from "../core/transactionWatcher"; -import { getAxios } from "../core/utils"; import { AccountAwaiter } from "./accountAwaiter"; -import { AccountOnNetwork, GuardianData } from "./accounts"; +import { AccountOnNetwork, AccountStorage, AccountStorageEntry, GuardianData } from "./accounts"; +import { BlockOnNetwork } from "./blocks"; import { defaultAxiosConfig } from "./config"; import { BaseUserAgent } from "./constants"; import { ContractQueryRequest } from "./contractQueryRequest"; @@ -17,15 +23,9 @@ import { INetworkProvider } from "./interface"; import { NetworkConfig } from "./networkConfig"; import { NetworkProviderConfig } from "./networkProviderConfig"; import { NetworkStatus } from "./networkStatus"; -import { - AccountStorage, - AccountStorageEntry, - AwaitingOptions, - BlockOnNetwork, - TokenAmountOnNetwork, - TransactionCostResponse, -} from "./resources"; +import { AwaitingOptions, TransactionCostResponse } from "./resources"; import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions"; +import { TokenAmountOnNetwork } from "./tokens"; import { extendUserAgentIfBackend } from "./userAgent"; // TODO: Find & remove duplicate code between "ProxyNetworkProvider" and "ApiNetworkProvider". diff --git a/src/networkProviders/resources.ts b/src/networkProviders/resources.ts index 98c76d5af..a4f9f1484 100644 --- a/src/networkProviders/resources.ts +++ b/src/networkProviders/resources.ts @@ -1,6 +1,3 @@ -import { BytesValue } from "../abi"; -import { Address } from "../core/address"; -import { Token } from "../core/tokens"; import { TransactionStatus } from "../core/transactionStatus"; import { DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS, @@ -8,144 +5,6 @@ import { DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS, } from "./constants"; -/** - * A plain view of an account storage. - */ -export class AccountStorage { - raw: Record = {}; - blockCoordinates!: BlockCoordinates; - entries: AccountStorageEntry[] = []; - constructor(init?: Partial) { - Object.assign(this, init); - } - - static fromHttpResponse(payload: any): AccountStorage { - let result = new AccountStorage(); - - const pairs = payload["pairs"] || {}; - const entries: AccountStorageEntry[] = Object.entries(pairs).map(([key, value]) => { - const decodedKey = Buffer.from(key, "hex").toString("utf8"); - const val: string = value ? (value as string).toString() : ""; - const decodedValue = Buffer.from(val).toString(); - - return new AccountStorageEntry({ - raw: { [key]: value }, - key: decodedKey, - value: decodedValue, - }); - }); - result.raw = payload; - result.entries = entries; - result.blockCoordinates = BlockCoordinates.fromHttpResponse(payload); - - return result; - } -} - -/** - * An object holding network status configuration parameters. - */ -export class BlockOnNetwork { - /** - * The raw data return by provider. - */ - public raw: Record = {}; - - /** - * The shard number. - */ - public shard: number = 0; - - /** - * The shard nonce. - */ - public nonce: bigint = 0n; - - /** - * The block hash. - */ - public hash: string = ""; - - /** - * The block previous hash. - */ - public previousHash: string = ""; - - /** - * The block timestamp. - */ - public timestamp: number = 0; - - /** - * The block timestamp. - */ - public round: number = 0; - - /** - * The block timestamp. - */ - public epoch: number = 0; - - /** - * Constructs a configuration object from a HTTP response (as returned by the provider). - */ - static fromHttpResponse(payload: any): BlockOnNetwork { - let blockOnNetwork = new BlockOnNetwork(); - - blockOnNetwork.raw = payload; - blockOnNetwork.shard = Number(payload["shard"]) ?? 0; - blockOnNetwork.nonce = BigInt(payload["nonce"] ?? 0); - blockOnNetwork.hash = payload["hash"] ?? ""; - blockOnNetwork.previousHash = payload["prevBlockHash"] ?? payload["prevHash"] ?? ""; - blockOnNetwork.timestamp = Number(payload["timestamp"] ?? 0); - blockOnNetwork.round = Number(payload["round"] ?? 0); - blockOnNetwork.epoch = Number(payload["epoch"] ?? 0); - - return blockOnNetwork; - } -} - -export class BlockCoordinates { - nonce: bigint = 0n; - hash: string = ""; - rootHash: string = ""; - constructor(init?: Partial) { - Object.assign(this, init); - } - static fromHttpResponse(payload: any): BlockCoordinates { - const result = new BlockCoordinates(); - const value = payload["blockInfo"] || {}; - - result.nonce = value["nonce"] || 0n; - result.hash = value["hash"] || ""; - result.rootHash = value["rootHash"] || ""; - - return result; - } -} - -export class AccountStorageEntry { - raw: Record = {}; - address: Address = Address.empty(); - key: string = ""; - value: string = ""; - - constructor(init?: Partial) { - Object.assign(this, init); - } - - static fromHttpResponse(payload: any, key: string): AccountStorageEntry { - const result = new AccountStorageEntry(); - const value = payload["value"] || ""; - - result.raw = payload; - result.key = key; - result.value = BytesValue.fromHex(value).toString(); - - return result; - } -} - export class AwaitingOptions { pollingIntervalInMilliseconds: number = DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS; timeoutInMilliseconds: number = DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS; @@ -166,34 +25,3 @@ export class TransactionCostResponse { return result; } } - -export class TokenAmountOnNetwork { - raw: Record = {}; - token: Token = new Token({ identifier: "" }); - amount: bigint = 0n; - block_coordinates?: BlockCoordinates; - - constructor(init?: Partial) { - Object.assign(this, init); - } - - static fromProxyResponse(payload: any): TokenAmountOnNetwork { - const result = new TokenAmountOnNetwork(); - - result.raw = payload; - result.amount = BigInt(payload["balance"] ?? 0); - result.token = new Token({ identifier: payload["tokenIdentifier"] ?? "", nonce: payload["nonce"] ?? 0 }); - - return result; - } - - static fromApiResponse(payload: any): TokenAmountOnNetwork { - const result = new TokenAmountOnNetwork(); - - result.raw = payload; - result.amount = BigInt(payload["balance"] ?? 0); - result.token = new Token({ identifier: payload["identifier"] ?? "", nonce: payload["nonce"] ?? 0 }); - - return result; - } -} diff --git a/src/networkProviders/tokens.ts b/src/networkProviders/tokens.ts index 60d52ac9e..92a0aafb2 100644 --- a/src/networkProviders/tokens.ts +++ b/src/networkProviders/tokens.ts @@ -1,6 +1,7 @@ import { BigNumber } from "bignumber.js"; -import { Address } from "../core/address"; +import { Address, Token } from "../core"; import { numberToPaddedHex } from "../core/utils.codec"; +import { BlockCoordinates } from "./blocks"; export class FungibleTokenOfAccountOnNetwork { identifier: string = ""; @@ -92,3 +93,34 @@ export class NonFungibleTokenOfAccountOnNetwork { return collection; } } + +export class TokenAmountOnNetwork { + raw: Record = {}; + token: Token = new Token({ identifier: "" }); + amount: bigint = 0n; + block_coordinates?: BlockCoordinates; + + constructor(init?: Partial) { + Object.assign(this, init); + } + + static fromProxyResponse(payload: any): TokenAmountOnNetwork { + const result = new TokenAmountOnNetwork(); + + result.raw = payload; + result.amount = BigInt(payload["balance"] ?? 0); + result.token = new Token({ identifier: payload["tokenIdentifier"] ?? "", nonce: payload["nonce"] ?? 0 }); + + return result; + } + + static fromApiResponse(payload: any): TokenAmountOnNetwork { + const result = new TokenAmountOnNetwork(); + + result.raw = payload; + result.amount = BigInt(payload["balance"] ?? 0); + result.token = new Token({ identifier: payload["identifier"] ?? "", nonce: payload["nonce"] ?? 0 }); + + return result; + } +} diff --git a/src/networkProviders/transactionReceipt.ts b/src/networkProviders/transactionReceipt.ts deleted file mode 100644 index 5b4b7f607..000000000 --- a/src/networkProviders/transactionReceipt.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Address } from "../core/address"; - -export class TransactionReceipt { - value: string = ""; - sender: Address = Address.empty(); - data: string = ""; - hash: string = ""; - - static fromHttpResponse(response: { - value: string; - sender: string; - data: string; - txHash: string; - }): TransactionReceipt { - let receipt = new TransactionReceipt(); - - receipt.value = (response.value || 0).toString(); - receipt.sender = new Address(response.sender); - receipt.data = response.data; - receipt.hash = response.txHash; - - return receipt; - } -} diff --git a/src/smartContracts/smartContractController.ts b/src/smartContracts/smartContractController.ts index c5810c81f..cd370bbcc 100644 --- a/src/smartContracts/smartContractController.ts +++ b/src/smartContracts/smartContractController.ts @@ -1,12 +1,19 @@ import { Abi, ArgSerializer, isTyped, NativeSerializer } from "../abi"; -import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController, BaseControllerInput } from "../core"; -import { Err, ErrSmartContractQuery } from "../core/errors"; -import { SmartContractQuery, SmartContractQueryInput, SmartContractQueryResponse } from "../core/smartContractQuery"; -import { Transaction } from "../core/transaction"; -import { TransactionOnNetwork } from "../core/transactionOnNetwork"; -import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; -import { TransactionWatcher } from "../core/transactionWatcher"; +import { + Address, + BaseController, + BaseControllerInput, + Err, + ErrSmartContractQuery, + IAccount, + SmartContractQuery, + SmartContractQueryInput, + SmartContractQueryResponse, + Transaction, + TransactionOnNetwork, + TransactionsFactoryConfig, + TransactionWatcher, +} from "../core"; import { INetworkProvider } from "../networkProviders/interface"; import { SmartContractTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; import * as resources from "./resources"; diff --git a/src/smartContracts/smartContractTransactionsOutcomeParser.ts b/src/smartContracts/smartContractTransactionsOutcomeParser.ts index 5ff7db7be..75ba1e3dd 100644 --- a/src/smartContracts/smartContractTransactionsOutcomeParser.ts +++ b/src/smartContracts/smartContractTransactionsOutcomeParser.ts @@ -20,6 +20,10 @@ export class SmartContractTransactionsOutcomeParser { this.abi = options?.abi; } + /** + * Parses the transaction and recovers basic information about the contract(s) deployed by the transaction. + * @param options + */ parseDeploy(options: { transactionOnNetwork: TransactionOnNetwork }): resources.SmartContractDeployOutcome { return this.parseDeployGivenTransactionOnNetwork(options.transactionOnNetwork); } diff --git a/src/testutils/mockNetworkProvider.ts b/src/testutils/mockNetworkProvider.ts index 08ce1b788..5760c970e 100644 --- a/src/testutils/mockNetworkProvider.ts +++ b/src/testutils/mockNetworkProvider.ts @@ -10,20 +10,17 @@ import { TransactionOnNetwork } from "../core/transactionOnNetwork"; import { TransactionStatus } from "../core/transactionStatus"; import { AccountOnNetwork, + AccountStorage, + AccountStorageEntry, DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork, NetworkConfig, NetworkStatus, } from "../networkProviders"; +import { BlockOnNetwork } from "../networkProviders/blocks"; import { INetworkProvider, IPagination } from "../networkProviders/interface"; -import { - AccountStorage, - AccountStorageEntry, - AwaitingOptions, - BlockOnNetwork, - TokenAmountOnNetwork, - TransactionCostResponse, -} from "../networkProviders/resources"; +import { AwaitingOptions, TransactionCostResponse } from "../networkProviders/resources"; +import { TokenAmountOnNetwork } from "../networkProviders/tokens"; import { SmartContractResult } from "../transactionsOutcomeParsers"; import { createAccountBalance } from "./utils"; diff --git a/src/tokenManagement/tokenManagementController.ts b/src/tokenManagement/tokenManagementController.ts index 947e84e64..33d8e3158 100644 --- a/src/tokenManagement/tokenManagementController.ts +++ b/src/tokenManagement/tokenManagementController.ts @@ -1,9 +1,13 @@ -import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController, BaseControllerInput } from "../core"; -import { Transaction } from "../core/transaction"; -import { TransactionOnNetwork } from "../core/transactionOnNetwork"; -import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; -import { TransactionWatcher } from "../core/transactionWatcher"; +import { + Address, + BaseController, + BaseControllerInput, + IAccount, + Transaction, + TransactionOnNetwork, + TransactionsFactoryConfig, + TransactionWatcher, +} from "../core"; import { INetworkProvider } from "../networkProviders/interface"; import { TokenManagementTransactionsOutcomeParser } from "../transactionsOutcomeParsers"; import * as resources from "./resources"; diff --git a/src/transfers/transfersControllers.ts b/src/transfers/transfersControllers.ts index 6c323d38a..50c797e29 100644 --- a/src/transfers/transfersControllers.ts +++ b/src/transfers/transfersControllers.ts @@ -1,7 +1,11 @@ -import { IAccount } from "../accounts/interfaces"; -import { Address, BaseController, BaseControllerInput } from "../core"; -import { Transaction } from "../core/transaction"; -import { TransactionsFactoryConfig } from "../core/transactionsFactoryConfig"; +import { + Address, + BaseController, + BaseControllerInput, + IAccount, + Transaction, + TransactionsFactoryConfig, +} from "../core"; import * as resources from "./resources"; import { TransferTransactionsFactory } from "./transferTransactionsFactory"; diff --git a/src/wallet/index.ts b/src/wallet/index.ts index ebcbb8db3..a0181b16d 100644 --- a/src/wallet/index.ts +++ b/src/wallet/index.ts @@ -3,6 +3,7 @@ export * from "./keypair"; export * from "./mnemonic"; export * from "./pem"; export * from "./userKeys"; +export * from "./userPem"; export * from "./userSigner"; export * from "./userVerifier"; export * from "./userWallet"; From 8983e6a088c06f533f7a16eae62bc2e4125f449f Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 13 Mar 2025 14:46:49 +0200 Subject: [PATCH 212/214] Bumb version --- package-lock.json | 16 ++++++++-------- package.json | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index d77448154..946cadc84 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.1", + "version": "14.0.0-beta.2", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.1", + "version": "14.0.0-beta.2", "license": "MIT", "dependencies": { "@multiversx/sdk-transaction-decoder": "1.0.2", @@ -886,9 +886,9 @@ } }, "node_modules/axios": { - "version": "1.7.4", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz", - "integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==", + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.3.tgz", + "integrity": "sha512-iP4DebzoNlP/YN2dpwCgb8zoCmhtkajzS48JvwmkSkXvPI3DHc7m+XYL5tGnSlJtR6nImXZmdCuN5aP8dh1d8A==", "optional": true, "dependencies": { "follow-redirects": "^1.15.6", @@ -5829,9 +5829,9 @@ "dev": true }, "axios": { - "version": "1.7.4", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz", - "integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==", + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.3.tgz", + "integrity": "sha512-iP4DebzoNlP/YN2dpwCgb8zoCmhtkajzS48JvwmkSkXvPI3DHc7m+XYL5tGnSlJtR6nImXZmdCuN5aP8dh1d8A==", "optional": true, "requires": { "follow-redirects": "^1.15.6", diff --git a/package.json b/package.json index dd6788400..51d66aa24 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.1", + "version": "14.0.0-beta.2", "description": "MultiversX SDK for JavaScript and TypeScript", "author": "MultiversX", "homepage": "https://multiversx.com", From b252b96e54446d0e2a70fd5ad632aebec8b68aad Mon Sep 17 00:00:00 2001 From: danielailie Date: Thu, 13 Mar 2025 15:34:35 +0200 Subject: [PATCH 213/214] Code review follow up --- src/core/interfaces.ts | 5 +---- src/core/message.ts | 4 ++-- src/core/tokens.ts | 2 +- src/entrypoints/entrypoints.ts | 4 ++-- 4 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts index fee8dc136..ff273b6a8 100644 --- a/src/core/interfaces.ts +++ b/src/core/interfaces.ts @@ -1,5 +1,4 @@ -import { Message, Transaction } from "."; -import { Address } from "./address"; +import { Address, Message, Transaction, TransactionOnNetwork } from "."; export interface IAccount { readonly address: Address; @@ -11,8 +10,6 @@ export interface IAccount { verifyMessageSignature(message: Message, signature: Uint8Array): Promise; } -import { TransactionOnNetwork } from "./transactionOnNetwork"; - export interface ITransactionFetcher { /** * Fetches the state of a {@link Transaction}. diff --git a/src/core/message.ts b/src/core/message.ts index e7452904b..fb291dd77 100644 --- a/src/core/message.ts +++ b/src/core/message.ts @@ -52,7 +52,7 @@ export class MessageComputer { } /** - * returns the result of `compute_bytes_for_signing() + * returns the result of `computeBytesForSigning` */ computeBytesForVerifying(message: Message): Uint8Array { return this.computeBytesForSigning(message); @@ -75,7 +75,7 @@ export class MessageComputer { } /** - * packed_message should be the one obtained from calling `pack_message()` + * packedMessage should be the one obtained from calling `packMessage()` * should treat both 'legacy message' and current message */ unpackMessage(packedMessage: { diff --git a/src/core/tokens.ts b/src/core/tokens.ts index f2ae30b27..e7567c50f 100644 --- a/src/core/tokens.ts +++ b/src/core/tokens.ts @@ -22,7 +22,7 @@ export type TokenType = "NFT" | "SFT" | "META" | "FNG"; export class Token { /** - * E.g. "FOO-abcdef", "EGLD". + * E.g. "FOO-abcdef", "EGLD-000000". */ readonly identifier: string; readonly nonce: bigint; diff --git a/src/entrypoints/entrypoints.ts b/src/entrypoints/entrypoints.ts index a9b0a6739..ffdcc7d95 100644 --- a/src/entrypoints/entrypoints.ts +++ b/src/entrypoints/entrypoints.ts @@ -91,7 +91,7 @@ class NetworkEntrypoint { } /** - * Function of the network provider, promoted to the facade. + * Function of the network provider, promoted to the entrypoint. * @param transactions */ sendTransactions(transactions: Transaction[]): Promise<[number, string[]]> { @@ -99,7 +99,7 @@ class NetworkEntrypoint { } /** - * Function of the network provider, promoted to the facade. + * Function of the network provider, promoted to the entrypoint. * @param transaction */ sendTransaction(transaction: Transaction): Promise { From bd2de73f2870e3d686ed0bf6125a9cee50bd3694 Mon Sep 17 00:00:00 2001 From: danielailie Date: Tue, 18 Mar 2025 11:06:28 +0200 Subject: [PATCH 214/214] bump version --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 946cadc84..1d40a9d65 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.2", + "version": "14.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.2", + "version": "14.0.0", "license": "MIT", "dependencies": { "@multiversx/sdk-transaction-decoder": "1.0.2", diff --git a/package.json b/package.json index 51d66aa24..0aad3fb9c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@multiversx/sdk-core", - "version": "14.0.0-beta.2", + "version": "14.0.0", "description": "MultiversX SDK for JavaScript and TypeScript", "author": "MultiversX", "homepage": "https://multiversx.com",