From e4829be4235f306b68a5407ebf12576c2ecea51b Mon Sep 17 00:00:00 2001 From: Steven Liu Date: Wed, 8 Apr 2020 12:17:55 +0100 Subject: [PATCH 1/5] v0.17.4 (#514) * Created `network` folder for network models * Fixed lint after files moved * Applied openAPI 0.8.7 changes * Added tests * Use UInt64 in retalFees * Fixed #455 Make namespace max depth configurable in idGenerator * - Fixed parser bug - Use rest json payload for unit testing * restored removed tests to cover models * Working on travis release process and ts-doc github deployments * Simplfied BlockHttp Added BlockHttp unit tests Changed travis to just report coveralls from one job * fixed travis * Uploading multiple versions of ts-docs into git hub pages * Improved ChainHttp, added unit tests * Removed maxDepth. Let server run the validation * Added unit tests * FIxed #493 * Added tests * useQuerystring on all https * Fixed github token env variable name Added escape skip flag to avoid republishing the same version Added missing git commit . after version increase * Update README links * Update README.md * Update release.sh * Update README.md * Installing typescript globally * Improved MetadataHttp, added unit tests * fixed #495 * Fixed #501 * fixed #503 * Refactored MosaicService unit test (#510) * Fixed #509 * Added mosaicHttp unit tests * Refactored mosaicHttp to use abstract caller * Add error trapping unit test * removed unused error catcher * add SimpleWallet.toDTO, fixes #504 (#508) * add SimpleWallet.toDTO, fixes #504 * add word2ua test * Update README.md (#512) * v0.17.4 release (#513) * v0.17.4 release * Updated md table header Co-authored-by: Fernando Boucquez Co-authored-by: David Garcia Co-authored-by: Decentraliser --- .travis.yml | 19 +- CHANGELOG.md | 35 +- README.md | 27 +- e2e/infrastructure/AccountHttp.spec.ts | 2 +- e2e/infrastructure/BlockHttp.spec.ts | 2 +- e2e/infrastructure/IntegrationTestHelper.ts | 5 +- e2e/infrastructure/Listener.spec.ts | 2 +- e2e/infrastructure/MetadataHttp.spec.ts | 2 +- e2e/infrastructure/MosaicHttp.spec.ts | 5 +- e2e/infrastructure/NetworkHttp.spec.ts | 25 +- e2e/infrastructure/RestrictionHttp.spec.ts | 2 +- e2e/infrastructure/TransactionHttp.spec.ts | 2 +- e2e/infrastructure/UnresolvedMapping.spec.ts | 2 +- e2e/service/BlockService.spec.ts | 2 +- .../MetadataTransactionService.spec.ts | 2 +- ...osaicRestrictionTransactionService.spec.ts | 2 +- e2e/service/MosaicService.spec.ts | 2 +- e2e/service/TransactionService.spec.ts | 2 +- ...TransactionService_AggregateBonded.spec.ts | 2 +- package-lock.json | 1428 ++++++++--------- package.json | 19 +- src/core/format/IdGenerator.ts | 1 + src/core/format/RawAddress.ts | 2 +- src/core/format/Utilities.ts | 4 - src/core/utils/UnresolvedMapping.ts | 2 +- src/infrastructure/AccountHttp.ts | 1 + src/infrastructure/BlockHttp.ts | 43 +- src/infrastructure/ChainHttp.ts | 19 +- src/infrastructure/Http.ts | 2 +- src/infrastructure/MetadataHttp.ts | 99 +- src/infrastructure/MosaicHttp.ts | 131 +- src/infrastructure/MultisigHttp.ts | 3 +- src/infrastructure/NamespaceHttp.ts | 3 +- src/infrastructure/NetworkHttp.ts | 99 +- src/infrastructure/NetworkRepository.ts | 40 +- src/infrastructure/NodeHttp.ts | 1 + src/infrastructure/ReceiptHttp.ts | 3 +- src/infrastructure/RepositoryFactory.ts | 2 +- src/infrastructure/RepositoryFactoryHttp.ts | 2 +- src/infrastructure/RestrictionAccountHttp.ts | 1 + src/infrastructure/RestrictionMosaicHttp.ts | 1 + src/infrastructure/TransactionHttp.ts | 2 + src/model/account/Account.ts | 2 +- src/model/account/Address.ts | 2 +- src/model/account/PublicAccount.ts | 2 +- src/model/blockchain/BlockInfo.ts | 2 +- src/model/message/EncryptedMessage.ts | 2 +- .../PersistentHarvestingDelegationMessage.ts | 2 +- src/model/model.ts | 24 +- .../network/AccountLinkNetworkProperties.ts | 24 + .../AccountRestrictionNetworkProperties.ts | 24 + .../network/AggregateNetworkProperties.ts | 32 + src/model/network/ChainProperties.ts | 66 + .../network/HashLockNetworkProperties.ts | 26 + .../network/MetadataNetworkProperties.ts | 24 + src/model/network/MosaicNetworkProperties.ts | 31 + .../MosaicRestrictionNetworkProperties.ts | 24 + .../network/MultisigNetworkProperties.ts | 28 + .../network/NamespaceNetworkProperties.ts | 42 + src/model/network/NetworkConfiguration.ts | 35 + .../{blockchain => network}/NetworkName.ts | 0 src/model/network/NetworkProperties.ts | 37 + .../{blockchain => network}/NetworkType.ts | 0 src/model/network/PluginProperties.ts | 60 + src/model/network/RentalFees.ts | 33 + .../network/SecretLockNetworkProperties.ts | 28 + .../TransactionFees.ts} | 8 +- .../network/TransferNetworkProperties.ts | 24 + src/model/node/NodeInfo.ts | 2 +- src/model/receipt/ResolutionStatement.ts | 2 +- .../AccountAddressRestrictionTransaction.ts | 10 +- .../transaction/AccountLinkTransaction.ts | 2 +- .../transaction/AccountMetadataTransaction.ts | 2 +- .../AccountMosaicRestrictionTransaction.ts | 10 +- .../AccountOperationRestrictionTransaction.ts | 2 +- .../AccountRestrictionTransaction.ts | 10 +- .../transaction/AddressAliasTransaction.ts | 2 +- src/model/transaction/AggregateTransaction.ts | 2 +- .../AggregateTransactionCosignature.ts | 2 +- src/model/transaction/AliasTransaction.ts | 2 +- src/model/transaction/LockFundsTransaction.ts | 2 +- .../MosaicAddressRestrictionTransaction.ts | 2 +- .../transaction/MosaicAliasTransaction.ts | 2 +- .../MosaicDefinitionTransaction.ts | 2 +- .../MosaicGlobalRestrictionTransaction.ts | 2 +- .../transaction/MosaicMetadataTransaction.ts | 2 +- .../MosaicSupplyChangeTransaction.ts | 2 +- .../MultisigAccountModificationTransaction.ts | 2 +- .../NamespaceMetadataTransaction.ts | 2 +- .../NamespaceRegistrationTransaction.ts | 2 +- .../PersistentDelegationRequestTransaction.ts | 2 +- .../transaction/SecretLockTransaction.ts | 2 +- .../transaction/SecretProofTransaction.ts | 2 +- src/model/transaction/SignedTransaction.ts | 2 +- src/model/transaction/Transaction.ts | 5 +- src/model/transaction/TransferTransaction.ts | 2 +- src/model/wallet/SimpleWallet.ts | 10 +- src/model/wallet/Wallet.ts | 2 +- src/service/MetadataTransactionService.ts | 2 +- .../MosaicRestrictionTransactionService.ts | 2 +- src/service/TransactionService.ts | 6 +- test/conf/conf.spec.ts | 2 +- test/core/crypto/keyPair.spec.ts | 2 +- test/core/crypto/utilities.spec.ts | 32 + test/core/format/Convert.spec.ts | 43 + test/core/format/IdGenerator.spec.ts | 7 - test/core/utils/TransactionMapping.spec.ts | 2 +- test/core/utils/UnresolvedMapping.spec.ts | 2 +- test/infrastructure/BlockHttp.spec.ts | 170 ++ test/infrastructure/ChainHttp.spec.ts | 56 + test/infrastructure/MetadataHttp.spec.ts | 216 +++ test/infrastructure/MosaicHttp.spec.ts | 143 ++ test/infrastructure/NetworkHttp.spec.ts | 161 +- test/infrastructure/NodeHttp.spec.ts | 4 +- test/infrastructure/RepositoryFactory.spec.ts | 2 +- .../SerializeTransactionToJSON.spec.ts | 2 +- test/infrastructure/TransactionHttp.spec.ts | 2 +- .../receipt/CreateReceiptFromDTO.spec.ts | 2 +- test/model/account/Account.spec.ts | 2 +- test/model/account/AccountInfo.spec.ts | 2 +- test/model/account/Address.spec.ts | 2 +- .../account/MultisigAccountGraphInfo.spec.ts | 2 +- .../model/account/MultisigAccountInfo.spec.ts | 2 +- test/model/account/PublicAccount.spec.ts | 2 +- ...sistentHarvestingDelegationMessage.spec.ts | 2 +- test/model/mosaic/MosaicAmountView.spec.ts | 2 +- test/model/mosaic/MosaicId.spec.ts | 9 +- test/model/mosaic/MosaicInfo.spec.ts | 2 +- test/model/mosaic/MosaicView.spec.ts | 2 +- test/model/namespace/Alias.spec.ts | 2 +- test/model/namespace/NamespaceInfo.spec.ts | 2 +- .../NetworkType.spec.ts | 2 +- test/model/receipt/Receipt.spec.ts | 2 +- .../model/receipt/ResolutionStatement.spec.ts | 2 +- test/model/receipt/Statement.spec.ts | 2 +- .../AccountLinkTransaction.spec.ts | 2 +- .../AccountMetadataTransaction.spec.ts | 2 +- .../AccountRestrictionTransaction.spec.ts | 2 +- .../AddressAliasTransaction.spec.ts | 2 +- .../transaction/AggregateTransaction.spec.ts | 2 +- .../CosignatureTransaction.spec.ts | 2 +- .../transaction/HashLockTransaction.spec.ts | 2 +- .../transaction/LockFundsTransaction.spec.ts | 2 +- ...osaicAddressRestrictionTransaction.spec.ts | 2 +- .../MosaicAliasTransaction.spec.ts | 2 +- .../MosaicDefinitionTransaction.spec.ts | 2 +- ...MosaicGlobalRestrictionTransaction.spec.ts | 2 +- .../MosaicMetadataTransaction.spec.ts | 2 +- .../MosaicSupplyChangeTransaction.spec.ts | 2 +- ...isigAccountModificationTransaction.spec.ts | 2 +- .../MultisigCosignatoryModification.spec.ts | 2 +- .../NamespaceMetadataTransaction.spec.ts | 2 +- .../NamespaceRegistrationTransaction.spec.ts | 2 +- ...istentDelegationRequestTransaction.spec.ts | 2 +- .../transaction/SecretLockTransaction.spec.ts | 2 +- .../SecretProofTransaction.spec.ts | 2 +- .../transaction/SignedTransaction.spec.ts | 2 +- test/model/transaction/Transaction.spec.ts | 2 +- .../transaction/TransferTransaction.spec.ts | 2 +- test/model/wallet/SimpleWallet.spec.ts | 10 +- test/resource/TestResources.ts | 91 ++ .../AggregateTransactionService.spec.ts | 2 +- test/service/BlockService.spec.ts | 2 +- .../MetadataTransactionservice.spec.ts | 2 +- ...osaicRestrictionTransactionservice.spec.ts | 2 +- test/service/MosaicService.spec.ts | 78 +- test/service/NamespaceService.spec.ts | 2 +- test/service/TransactionService.spec.ts | 2 +- .npmrc.template => travis/.npmrc | 0 travis/github-pages.sh | 21 + travis/release.sh | 60 + travis/uploadArchives.sh | 2 +- 172 files changed, 2797 insertions(+), 1151 deletions(-) create mode 100644 src/model/network/AccountLinkNetworkProperties.ts create mode 100644 src/model/network/AccountRestrictionNetworkProperties.ts create mode 100644 src/model/network/AggregateNetworkProperties.ts create mode 100644 src/model/network/ChainProperties.ts create mode 100644 src/model/network/HashLockNetworkProperties.ts create mode 100644 src/model/network/MetadataNetworkProperties.ts create mode 100644 src/model/network/MosaicNetworkProperties.ts create mode 100644 src/model/network/MosaicRestrictionNetworkProperties.ts create mode 100644 src/model/network/MultisigNetworkProperties.ts create mode 100644 src/model/network/NamespaceNetworkProperties.ts create mode 100644 src/model/network/NetworkConfiguration.ts rename src/model/{blockchain => network}/NetworkName.ts (100%) create mode 100644 src/model/network/NetworkProperties.ts rename src/model/{blockchain => network}/NetworkType.ts (100%) create mode 100644 src/model/network/PluginProperties.ts create mode 100644 src/model/network/RentalFees.ts create mode 100644 src/model/network/SecretLockNetworkProperties.ts rename src/model/{blockchain/NetworkFees.ts => network/TransactionFees.ts} (80%) create mode 100644 src/model/network/TransferNetworkProperties.ts create mode 100644 test/core/crypto/utilities.spec.ts create mode 100644 test/infrastructure/BlockHttp.spec.ts create mode 100644 test/infrastructure/ChainHttp.spec.ts create mode 100644 test/infrastructure/MetadataHttp.spec.ts create mode 100644 test/infrastructure/MosaicHttp.spec.ts rename test/model/{blockchain => network}/NetworkType.spec.ts (94%) create mode 100644 test/resource/TestResources.ts rename .npmrc.template => travis/.npmrc (100%) create mode 100644 travis/github-pages.sh create mode 100644 travis/release.sh diff --git a/.travis.yml b/.travis.yml index 3b830b24ba..208c848e41 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,20 +10,27 @@ before_script: - npm run build script: - npm run test:cov - - npm run coveralls-report - - npm install --global typedoc - - typedoc --out ts-docs src + - npm install --global typedoc typescript + - CURRENT_VERSION=$(npm run version --silent) + - typedoc --out "ts-docs/$CURRENT_VERSION" src - touch ./ts-docs/.nojekyll + - if [ "$TRAVIS_NODE_VERSION" = "8" ]; then npm run coveralls-report; fi deploy: - - provider: pages + - provider: script skip_cleanup: true - local_dir: ts-docs - github_token: $GITHUB_TOKEN + script: /bin/sh travis/github-pages.sh on: branch: master + node_js: "9" - provider: script skip_cleanup: true script: /bin/sh travis/uploadArchives.sh on: branch: master node_js: "8" + - provider: script + skip_cleanup: true + script: /bin/sh travis/release.sh + on: + branch: $RELEASE_BRANCH + node_js: "8" diff --git a/CHANGELOG.md b/CHANGELOG.md index eaf781f87c..f4e2eef843 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,10 +3,28 @@ All notable changes to this project will be documented in this file. The changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). +## [0.17.4] - 07-Apr-2020 + +**Milestone**: Fushicho.4(RC3 0.9.3.2) + Package | Version | Link +---|---|--- +SDK Core| v0.17.4 | https://www.npmjs.com/package/symbol-sdk +Catbuffer | v0.0.11 | https://www.npmjs.com/package/catbuffer-typescript +Client Library | v0.8.9 | https://www.npmjs.com/package/symbol-openapi-typescript-node-client + +- Added `SimpleWallet.toDTO()` method which returns JSON serialized object. +- Applied latest Symbol OpenAPI generated code (`v0.8.9`). +- Added automated release scripts for Travis. +- Added multiple version spport for TS-Doc. +- Optimised unit tests and improved test coverage. +- Changed internal method `getSigningByte` to public. +- Removed constant of namespace `MaxDepth (default: 3)` which can be retrieved from network properties endpoint. +- Fixed Github security alert on `minimist` package. + ## [0.17.3] - 04-Mar-2020 **Milestone**: Fushicho.4(RC3 0.9.3.1) - Versions | | + Package | Version | Link ---|---|--- SDK Core| v0.17.3 | https://www.npmjs.com/package/symbol-sdk Catbuffer | v0.0.11 | https://www.npmjs.com/package/catbuffer-typescript @@ -18,7 +36,7 @@ Client Library | v0.8.5 | https://www.npmjs.com/package/symbol-openapi-typescri ## [0.17.2] - 02-Mar-2020 **Milestone**: Fushicho.4(RC3 0.9.3.1) - Versions | | + Package | Version | Link ---|---|--- SDK Core| v0.17.2 | https://www.npmjs.com/package/symbol-sdk Catbuffer | v0.0.11 | https://www.npmjs.com/package/catbuffer-typescript @@ -33,7 +51,7 @@ Client Library | v0.8.5 | https://www.npmjs.com/package/symbol-openapi-typescri ## [0.17.1] - 24-Feb-2020 **Milestone**: Fushicho.4(RC3 0.9.3.1) - Versions | | + Package | Version | Link ---|---|--- SDK Core| v0.17.1 | https://www.npmjs.com/package/symbol-sdk Catbuffer | v0.0.11 | https://www.npmjs.com/package/catbuffer-typescript @@ -47,7 +65,7 @@ Client Library | v0.8.5 | https://www.npmjs.com/package/symbol-openapi-typescri ## [0.17.0] - 17-Feb-2020 **Milestone**: Fushicho.4(RC3 0.9.3.1) - Versions | | + Package | Version | Link ---|---|--- SDK Core | v0.17.0 | https://www.npmjs.com/package/nem2-sdk catbuffer | v0.0.11 | https://www.npmjs.com/package/catbuffer @@ -67,7 +85,7 @@ Client Library | v0.8.4 | https://www.npmjs.com/package/nem2-sdk-openapi-typesc ## [0.16.5] - 30-Jan-2020 **Milestone**: Fushicho.4(RC3) - Versions | | + Package | Version | Link ---|---|--- SDK Core| v0.16.5 | https://www.npmjs.com/package/nem2-sdk catbuffer Library| v0.0.11 | https://www.npmjs.com/package/catbuffer @@ -78,7 +96,7 @@ Client Library | v0.7.20-beta.7 | https://www.npmjs.com/package/nem2-sdk-openap ## [0.16.4] - 30-Jan-2020 **Milestone**: Fushicho.4(RC3) - Versions | | + Package | Version | Link ---|---|--- SDK Core| v0.16.4 | https://www.npmjs.com/package/nem2-sdk catbuffer Library| v0.0.11 | https://www.npmjs.com/package/catbuffer @@ -96,7 +114,7 @@ Client Library | v0.7.20-beta.7 | https://www.npmjs.com/package/nem2-sdk-openap ## [0.16.3] - 09-Jan-2020 **Milestone**: Fushicho.3 - Versions | | + Package | Version | Link ---|---|--- SDK Core| v0.16.3 | https://www.npmjs.com/package/nem2-sdk catbuffer Library| v0.0.7 | https://www.npmjs.com/package/catbuffer @@ -107,7 +125,7 @@ Client Library | v0.7.20-beta.6 | https://www.npmjs.com/package/nem2-sdk-openap ## [0.16.2] - 06-Jan-2020 **Milestone**: Fushicho.3 - Versions | | + Package | Version | Link ---|---|--- SDK Core| v0.16.2 | https://www.npmjs.com/package/nem2-sdk catbuffer Library| v0.0.7 | https://www.npmjs.com/package/catbuffer @@ -419,6 +437,7 @@ Client Library | v0.7.20-alpha.6 | https://www.npmjs.com/package/nem2-sdk-opena - Initial code release. +[0.17.4]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.3...v0.17.4 [0.17.3]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.2...v0.17.3 [0.17.2]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.1...v0.17.2 [0.17.1]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.0...v0.17.1 diff --git a/README.md b/README.md index 89d4bf24ba..a892167259 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Symbol SDK for TypeScript and JavaScript [![npm version](https://badge.fury.io/js/symbol-sdk.svg)](https://badge.fury.io/js/symbol-sdk) -[![Build Status](https://api.travis-ci.org/nemtech/symbol-sdk-typescript-javascript.svg?branch=master)](https://travis-ci.org/nemtech/symbol-sdk-typescript-javascript) +[![Build Status](https://api.travis-ci.com/nemtech/symbol-sdk-typescript-javascript.svg?branch=master)](https://travis-ci.com/nemtech/symbol-sdk-typescript-javascript) [![Coverage Status](https://coveralls.io/repos/github/nemtech/symbol-sdk-typescript-javascript/badge.svg)](https://coveralls.io/github/nemtech/symbol-sdk-typescript-javascript?branch=travis-ci) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) @@ -9,15 +9,15 @@ The Symbol SDK for TypeScript / JavaScript allows you to develop web, mobile, an ## Important Notes -### _Fushicho_ Network Compatibility (catapult-server@0.9.3.1) +### _Fushicho_ Network Compatibility (catapult-server@0.9.3.2) **!!! Please be noted that the NEM2-SDK is rebranded to SYMBOL-SDK now**. -Due to a network upgrade with [catapult-server@Fushicho](https://github.com/nemtech/catapult-server/releases/tag/v0.9.3.1) version, **it is recommended to use this package's 0.17.3 version and upwards to use this package with Fushicho versioned networks**. +Due to a network upgrade with [catapult-server@Fushicho](https://github.com/nemtech/catapult-server/releases/tag/v0.9.3.2) version, **it is recommended to use this package's 0.17.4 version and upwards to use this package with Fushicho versioned networks**. -The upgrade to this package's [version v0.17.3](https://github.com/nemtech/symbol-sdk-typescript-javascript/releases/tag/v0.17.3) is mandatory for **fushicho compatibility**. +The upgrade to this package's [version v0.17.4](https://github.com/nemtech/symbol-sdk-typescript-javascript/releases/tag/v0.17.4) is mandatory for **fushicho compatibility**. -You can find the complete changelog [here](CHANGELOG.md). +Find the complete release notes [here](CHANGELOG.md). ## Requirements @@ -35,7 +35,8 @@ npm install symbol-sdk rxjs ## Usage -Surf the [NEM Developer Center][docs] to get started into NEM development. You will find self-paced guides and useful code snippets using the TypeScript/Javascript SDK. +Surf the [documentation][docs] to get started into Symbol development. +You will find self-paced guides and useful code snippets using the TypeScript/Javascript SDK. To get the full description of the available classes and their functions, check the [SDK reference][sdk-ref]. @@ -43,24 +44,28 @@ To get the full description of the available classes and their functions, check Use the following available resources to get help: -- [Symbol SDK Typescript/Javascript Reference][docs] +- [Symbol Documentation][docs] +- [Symbol SDK Typescript/Javascript Reference][sdk-ref] +- Join the community [slack group (#sig-api)][slack] - If you found a bug, [open a new issue][issues] ## Contributing -This project is developed and maintained by NEM Foundation. Contributions are welcome and appreciated. You can find [symbol-sdk on GitHub][self]. +This project is developed and maintained by NEM Foundation. -Feel free to start an issue or create a pull request. Check [CONTRIBUTING](CONTRIBUTING.md) before start. +Contributions are welcome and appreciated. +Check [CONTRIBUTING](CONTRIBUTING.md) for information on how to contribute. You can also find useful notes for developers under our documentation [guidelines][guidelines] section. ## License -Copyright (c) 2018-2019 NEM +Copyright (c) 2018-present NEM Licensed under the [Apache License 2.0](LICENSE) [self]: https://github.com/nemtech/symbol-sdk-typescript-javascript [docs]: http://nemtech.github.io/getting-started/setup-workstation.html [issues]: https://github.com/nemtech/symbol-sdk-typescript-javascript/issues -[sdk-ref]: http://nemtech.github.io/symbol-sdk-typescript-javascript +[sdk-ref]: https://nemtech.github.io/references/typescript-sdk.html [guidelines]: https://nemtech.github.io/contribute/contributing.html#sdk +[slack]: https://join.slack.com/t/nem2/shared_invite/enQtMzY4MDc2NTg0ODgyLWZmZWRiMjViYTVhZjEzOTA0MzUyMTA1NTA5OWQ0MWUzNTA4NjM5OTJhOGViOTBhNjkxYWVhMWRiZDRkOTE0YmU diff --git a/e2e/infrastructure/AccountHttp.spec.ts b/e2e/infrastructure/AccountHttp.spec.ts index 5f8d79d5fc..8ec542f0f2 100644 --- a/e2e/infrastructure/AccountHttp.spec.ts +++ b/e2e/infrastructure/AccountHttp.spec.ts @@ -23,11 +23,11 @@ import { QueryParams } from '../../src/infrastructure/QueryParams'; import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; import { PublicAccount } from '../../src/model/account/PublicAccount'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AddressAliasTransaction } from '../../src/model/transaction/AddressAliasTransaction'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; diff --git a/e2e/infrastructure/BlockHttp.spec.ts b/e2e/infrastructure/BlockHttp.spec.ts index d0a3b6fadb..43afb52e4f 100644 --- a/e2e/infrastructure/BlockHttp.spec.ts +++ b/e2e/infrastructure/BlockHttp.spec.ts @@ -21,9 +21,9 @@ import { BlockRepository } from '../../src/infrastructure/BlockRepository'; import { QueryParams } from '../../src/infrastructure/QueryParams'; import { ReceiptRepository } from '../../src/infrastructure/ReceiptRepository'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { Deadline } from '../../src/model/transaction/Deadline'; import { TransactionInfo } from '../../src/model/transaction/TransactionInfo'; import { TransferTransaction } from '../../src/model/transaction/TransferTransaction'; diff --git a/e2e/infrastructure/IntegrationTestHelper.ts b/e2e/infrastructure/IntegrationTestHelper.ts index cdf9ae56b3..31939327c2 100644 --- a/e2e/infrastructure/IntegrationTestHelper.ts +++ b/e2e/infrastructure/IntegrationTestHelper.ts @@ -19,7 +19,7 @@ import { IListener } from '../../src/infrastructure/IListener'; import { RepositoryFactory } from '../../src/infrastructure/RepositoryFactory'; import { RepositoryFactoryHttp } from '../../src/infrastructure/RepositoryFactoryHttp'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { SignedTransaction } from '../../src/model/transaction/SignedTransaction'; import { Transaction } from '../../src/model/transaction/Transaction'; import { UInt64 } from '../../src/model/UInt64'; @@ -57,7 +57,8 @@ export class IntegrationTestHelper { console.log(`Running tests against: ${json.apiUrl}`); this.apiUrl = json.apiUrl; this.repositoryFactory = new RepositoryFactoryHttp(json.apiUrl); - this.transactionService = new TransactionService(this.repositoryFactory.createTransactionRepository(), this.repositoryFactory.createReceiptRepository()); + this.transactionService = new TransactionService( + this.repositoryFactory.createTransactionRepository(), this.repositoryFactory.createReceiptRepository()); combineLatest(this.repositoryFactory.getGenerationHash(), this.repositoryFactory.getNetworkType()).subscribe(([generationHash, networkType]) => { this.networkType = networkType; diff --git a/e2e/infrastructure/Listener.spec.ts b/e2e/infrastructure/Listener.spec.ts index 287c19a5b6..e9314050ca 100644 --- a/e2e/infrastructure/Listener.spec.ts +++ b/e2e/infrastructure/Listener.spec.ts @@ -20,12 +20,12 @@ import { AccountRepository } from '../../src/infrastructure/AccountRepository'; import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; import { TransactionRepository } from '../../src/infrastructure/TransactionRepository'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { Address, CosignatureTransaction, LockFundsTransaction, Mosaic, SignedTransaction, UInt64 } from '../../src/model/model'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { MultisigAccountModificationTransaction } from '../../src/model/transaction/MultisigAccountModificationTransaction'; diff --git a/e2e/infrastructure/MetadataHttp.spec.ts b/e2e/infrastructure/MetadataHttp.spec.ts index cd9296cc0a..ef5b10e433 100644 --- a/e2e/infrastructure/MetadataHttp.spec.ts +++ b/e2e/infrastructure/MetadataHttp.spec.ts @@ -18,11 +18,11 @@ import { expect } from 'chai'; import { MetadataRepository } from '../../src/infrastructure/MetadataRepository'; import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { MosaicNonce } from '../../src/model/mosaic/MosaicNonce'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AccountMetadataTransaction } from '../../src/model/transaction/AccountMetadataTransaction'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; diff --git a/e2e/infrastructure/MosaicHttp.spec.ts b/e2e/infrastructure/MosaicHttp.spec.ts index 2c5e490e5b..2cac52791b 100644 --- a/e2e/infrastructure/MosaicHttp.spec.ts +++ b/e2e/infrastructure/MosaicHttp.spec.ts @@ -17,12 +17,12 @@ import { expect } from 'chai'; import { MosaicRepository } from '../../src/infrastructure/MosaicRepository'; import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { MosaicNonce } from '../../src/model/mosaic/MosaicNonce'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { Deadline } from '../../src/model/transaction/Deadline'; import { MosaicAliasTransaction } from '../../src/model/transaction/MosaicAliasTransaction'; import { MosaicDefinitionTransaction } from '../../src/model/transaction/MosaicDefinitionTransaction'; @@ -87,7 +87,8 @@ describe('MosaicHttp', () => { expect(mosaicDefinitionTransaction.nonce).to.deep.equal(listenedTransaction.nonce); expect(mosaicDefinitionTransaction.getMosaicNonceIntValue()).to.be.equal(listenedTransaction.getMosaicNonceIntValue()); - const savedTransaction = await helper.repositoryFactory.createTransactionRepository().getTransaction(signedTransaction.hash).toPromise() as MosaicDefinitionTransaction; + const savedTransaction = await helper.repositoryFactory.createTransactionRepository() + .getTransaction(signedTransaction.hash).toPromise() as MosaicDefinitionTransaction; expect(mosaicDefinitionTransaction.nonce.toHex()).to.be.equal(savedTransaction.nonce.toHex()); expect(mosaicDefinitionTransaction.nonce).to.deep.equal(savedTransaction.nonce); expect(mosaicDefinitionTransaction.getMosaicNonceIntValue()).to.be.equal(savedTransaction.getMosaicNonceIntValue()); diff --git a/e2e/infrastructure/NetworkHttp.spec.ts b/e2e/infrastructure/NetworkHttp.spec.ts index c0859b2feb..38fe4ed11d 100644 --- a/e2e/infrastructure/NetworkHttp.spec.ts +++ b/e2e/infrastructure/NetworkHttp.spec.ts @@ -15,7 +15,7 @@ */ import { expect } from 'chai'; import { NetworkRepository } from '../../src/infrastructure/NetworkRepository'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { IntegrationTestHelper } from './IntegrationTestHelper'; describe('NetworkHttp', () => { @@ -45,13 +45,30 @@ describe('NetworkHttp', () => { }); }); - describe('getNetworkFees', () => { - it('should return network fees', async () => { - const fees = await networkRepository.getNetworkFees().toPromise(); + describe('getTransactionFees', () => { + it('should return transaction fees', async () => { + const fees = await networkRepository.getTransactionFees().toPromise(); expect(fees.averageFeeMultiplier).to.be.not.null; expect(fees.highestFeeMultiplier).to.be.not.null; expect(fees.lowestFeeMultiplier).to.be.not.null; expect(fees.medianFeeMultiplier).to.be.not.null; }); }); + describe('getRentalFees', () => { + it('should return rental fees', async () => { + const fees = await networkRepository.getRentalFees().toPromise(); + expect(fees.effectiveChildNamespaceRentalFee).to.be.not.null; + expect(fees.effectiveMosaicRentalFee).to.be.not.null; + expect(fees.effectiveRootNamespaceRentalFeePerBlock).to.be.not.null; + }); + }); + + describe('getNetworkProperties', () => { + it('should return network configuration', async () => { + const config = await networkRepository.getNetworkProperties().toPromise(); + expect(config.network).to.be.not.null; + expect(config.chain).to.be.not.null; + expect(config.plugins).to.be.not.null; + }); + }); }); diff --git a/e2e/infrastructure/RestrictionHttp.spec.ts b/e2e/infrastructure/RestrictionHttp.spec.ts index 2a612b35ac..d1dc9511bc 100644 --- a/e2e/infrastructure/RestrictionHttp.spec.ts +++ b/e2e/infrastructure/RestrictionHttp.spec.ts @@ -20,10 +20,10 @@ import { RestrictionAccountRepository } from '../../src/infrastructure/Restricti import { RestrictionMosaicRepository } from '../../src/infrastructure/RestrictionMosaicRepository'; import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { MosaicNonce } from '../../src/model/mosaic/MosaicNonce'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AccountRestrictionFlags } from '../../src/model/restriction/AccountRestrictionType'; import { MosaicRestrictionEntryType } from '../../src/model/restriction/MosaicRestrictionEntryType'; import { MosaicRestrictionType } from '../../src/model/restriction/MosaicRestrictionType'; diff --git a/e2e/infrastructure/TransactionHttp.spec.ts b/e2e/infrastructure/TransactionHttp.spec.ts index f7c8aabddd..01c29ccbc4 100644 --- a/e2e/infrastructure/TransactionHttp.spec.ts +++ b/e2e/infrastructure/TransactionHttp.spec.ts @@ -28,7 +28,6 @@ import { TransactionRepository } from '../../src/infrastructure/TransactionRepos import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; import { PublicAccount } from '../../src/model/account/PublicAccount'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { Mosaic } from '../../src/model/mosaic/Mosaic'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; @@ -38,6 +37,7 @@ import { MosaicSupplyChangeAction } from '../../src/model/mosaic/MosaicSupplyCha import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AccountRestrictionModificationAction } from '../../src/model/restriction/AccountRestrictionModificationAction'; import { AccountRestrictionFlags } from '../../src/model/restriction/AccountRestrictionType'; import { MosaicRestrictionType } from '../../src/model/restriction/MosaicRestrictionType'; diff --git a/e2e/infrastructure/UnresolvedMapping.spec.ts b/e2e/infrastructure/UnresolvedMapping.spec.ts index e8713e202b..88367eb169 100644 --- a/e2e/infrastructure/UnresolvedMapping.spec.ts +++ b/e2e/infrastructure/UnresolvedMapping.spec.ts @@ -19,7 +19,6 @@ import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepositor import { TransactionHttp } from '../../src/infrastructure/TransactionHttp'; import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; @@ -27,6 +26,7 @@ import { MosaicNonce } from '../../src/model/mosaic/MosaicNonce'; import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { MosaicRestrictionType } from '../../src/model/restriction/MosaicRestrictionType'; import { AddressAliasTransaction } from '../../src/model/transaction/AddressAliasTransaction'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; diff --git a/e2e/service/BlockService.spec.ts b/e2e/service/BlockService.spec.ts index 675510c51e..f7343864b7 100644 --- a/e2e/service/BlockService.spec.ts +++ b/e2e/service/BlockService.spec.ts @@ -18,9 +18,9 @@ import { assert, expect } from 'chai'; import { ReceiptRepository } from '../../src/infrastructure/ReceiptRepository'; import { TransactionRepository } from '../../src/infrastructure/TransactionRepository'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { Deadline } from '../../src/model/transaction/Deadline'; import { TransferTransaction } from '../../src/model/transaction/TransferTransaction'; import { UInt64 } from '../../src/model/UInt64'; diff --git a/e2e/service/MetadataTransactionService.spec.ts b/e2e/service/MetadataTransactionService.spec.ts index 87e59c74e1..25d5794c92 100644 --- a/e2e/service/MetadataTransactionService.spec.ts +++ b/e2e/service/MetadataTransactionService.spec.ts @@ -2,12 +2,12 @@ import { expect } from 'chai'; import { Convert } from '../../src/core/format'; import { MetadataRepository } from '../../src/infrastructure/MetadataRepository'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { MetadataType } from '../../src/model/metadata/MetadataType'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { MosaicNonce } from '../../src/model/mosaic/MosaicNonce'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { MosaicDefinitionTransaction } from '../../src/model/transaction/MosaicDefinitionTransaction'; diff --git a/e2e/service/MosaicRestrictionTransactionService.spec.ts b/e2e/service/MosaicRestrictionTransactionService.spec.ts index 8f1e2f8239..c05f8d6819 100644 --- a/e2e/service/MosaicRestrictionTransactionService.spec.ts +++ b/e2e/service/MosaicRestrictionTransactionService.spec.ts @@ -3,12 +3,12 @@ import { KeyGenerator } from '../../src/core/format/KeyGenerator'; import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; import { RestrictionMosaicRepository } from '../../src/infrastructure/RestrictionMosaicRepository'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { MosaicNonce } from '../../src/model/mosaic/MosaicNonce'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { MosaicRestrictionType } from '../../src/model/restriction/MosaicRestrictionType'; import { AddressAliasTransaction } from '../../src/model/transaction/AddressAliasTransaction'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; diff --git a/e2e/service/MosaicService.spec.ts b/e2e/service/MosaicService.spec.ts index f094dab832..981699a7b8 100644 --- a/e2e/service/MosaicService.spec.ts +++ b/e2e/service/MosaicService.spec.ts @@ -17,7 +17,7 @@ import { AccountRepository } from '../../src/infrastructure/AccountRepository'; import { MosaicRepository } from '../../src/infrastructure/MosaicRepository'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { MosaicService } from '../../src/service/MosaicService'; import { IntegrationTestHelper } from '../infrastructure/IntegrationTestHelper'; diff --git a/e2e/service/TransactionService.spec.ts b/e2e/service/TransactionService.spec.ts index 19aadb7c3c..11ef791cd9 100644 --- a/e2e/service/TransactionService.spec.ts +++ b/e2e/service/TransactionService.spec.ts @@ -19,7 +19,6 @@ import { Convert } from '../../src/core/format/Convert'; import { TransactionRepository } from '../../src/infrastructure/TransactionRepository'; import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { Mosaic } from '../../src/model/mosaic/Mosaic'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; @@ -29,6 +28,7 @@ import { MosaicSupplyChangeAction } from '../../src/model/mosaic/MosaicSupplyCha import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AddressAliasTransaction } from '../../src/model/transaction/AddressAliasTransaction'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; diff --git a/e2e/service/TransactionService_AggregateBonded.spec.ts b/e2e/service/TransactionService_AggregateBonded.spec.ts index b4c4ec81d6..d8e114517b 100644 --- a/e2e/service/TransactionService_AggregateBonded.spec.ts +++ b/e2e/service/TransactionService_AggregateBonded.spec.ts @@ -19,12 +19,12 @@ import { ChronoUnit } from 'js-joda'; import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { Mosaic } from '../../src/model/mosaic/Mosaic'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { LockFundsTransaction } from '../../src/model/transaction/LockFundsTransaction'; diff --git a/package-lock.json b/package-lock.json index cbea3a59bc..008ad5d7b2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "symbol-sdk", - "version": "0.17.3", + "version": "0.17.4", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -13,45 +13,125 @@ "@babel/highlight": "^7.0.0" } }, + "@babel/core": { + "version": "7.8.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.8.7.tgz", + "integrity": "sha512-rBlqF3Yko9cynC5CCFy6+K/w2N+Sq/ff2BPy+Krp7rHlABIr5epbA7OxVeKoMHB39LZOp1UY5SuLjy6uWi35yA==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.8.3", + "@babel/generator": "^7.8.7", + "@babel/helpers": "^7.8.4", + "@babel/parser": "^7.8.7", + "@babel/template": "^7.8.6", + "@babel/traverse": "^7.8.6", + "@babel/types": "^7.8.7", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.1", + "json5": "^2.1.0", + "lodash": "^4.17.13", + "resolve": "^1.3.2", + "semver": "^5.4.1", + "source-map": "^0.5.0" + }, + "dependencies": { + "@babel/code-frame": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", + "dev": true, + "requires": { + "@babel/highlight": "^7.8.3" + } + }, + "@babel/highlight": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.8.3.tgz", + "integrity": "sha512-PX4y5xQUvy0fnEVHrYOarRPXVWafSjTW9T0Hab8gVIawpl2Sj0ORyrygANq+KjcNlSSTw0YCLSNA8OyZ1I4yEg==", + "dev": true, + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + } + }, + "convert-source-map": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", + "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.1" + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "json5": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.1.tgz", + "integrity": "sha512-l+3HXD0GEI3huGq1njuqtzYK8OYJyXMkOLtQ53pjWh89tvWS2h6l+1zMkYWqlb57+SiQodKZyvMEFb2X+KrFhQ==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + } + } + }, "@babel/generator": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.6.2.tgz", - "integrity": "sha512-j8iHaIW4gGPnViaIHI7e9t/Hl8qLjERI6DcV9kEpAIDJsAOrcnXqRS7t+QbhL76pwbtqP+QCQLL0z1CyVmtjjQ==", + "version": "7.8.7", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.8.7.tgz", + "integrity": "sha512-DQwjiKJqH4C3qGiyQCAExJHoZssn49JTMJgZ8SANGgVFdkupcUhLOdkAeoC6kmHZCPfoDG5M0b6cFlSN5wW7Ew==", "dev": true, "requires": { - "@babel/types": "^7.6.0", + "@babel/types": "^7.8.7", "jsesc": "^2.5.1", "lodash": "^4.17.13", "source-map": "^0.5.0" } }, "@babel/helper-function-name": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz", - "integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.8.3.tgz", + "integrity": "sha512-BCxgX1BC2hD/oBlIFUgOCQDOPV8nSINxCwM3o93xP4P9Fq6aV5sgv2cOOITDMtCfQ+3PvHp3l689XZvAM9QyOA==", "dev": true, "requires": { - "@babel/helper-get-function-arity": "^7.0.0", - "@babel/template": "^7.1.0", - "@babel/types": "^7.0.0" + "@babel/helper-get-function-arity": "^7.8.3", + "@babel/template": "^7.8.3", + "@babel/types": "^7.8.3" } }, "@babel/helper-get-function-arity": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz", - "integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.8.3.tgz", + "integrity": "sha512-FVDR+Gd9iLjUMY1fzE2SR0IuaJToR4RkCDARVfsBBPSP53GEqSFjD8gNyxg246VUyc/ALRxFaAK8rVG7UT7xRA==", "dev": true, "requires": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.8.3" } }, "@babel/helper-split-export-declaration": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz", - "integrity": "sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.8.3.tgz", + "integrity": "sha512-3x3yOeyBhW851hroze7ElzdkeRXQYQbFIb7gLK1WQYsw2GWDay5gAJNw1sWJ0VFP6z5J1whqeXH/WCdCjZv6dA==", + "dev": true, + "requires": { + "@babel/types": "^7.8.3" + } + }, + "@babel/helpers": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.8.4.tgz", + "integrity": "sha512-VPbe7wcQ4chu4TDQjimHv/5tj73qz88o12EPkO2ValS2QiQS/1F2SsjyIGNnAD0vF/nZS6Cf9i+vW6HIlnaR8w==", "dev": true, "requires": { - "@babel/types": "^7.4.4" + "@babel/template": "^7.8.3", + "@babel/traverse": "^7.8.4", + "@babel/types": "^7.8.3" } }, "@babel/highlight": { @@ -109,43 +189,99 @@ } }, "@babel/parser": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.6.2.tgz", - "integrity": "sha512-mdFqWrSPCmikBoaBYMuBulzTIKuXVPtEISFbRRVNwMWpCms/hmE2kRq0bblUHaNRKrjRlmVbx1sDHmjmRgD2Xg==", + "version": "7.8.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.8.7.tgz", + "integrity": "sha512-9JWls8WilDXFGxs0phaXAZgpxTZhSk/yOYH2hTHC0X1yC7Z78IJfvR1vJ+rmJKq3I35td2XzXzN6ZLYlna+r/A==", "dev": true }, "@babel/template": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.6.0.tgz", - "integrity": "sha512-5AEH2EXD8euCk446b7edmgFdub/qfH1SN6Nii3+fyXP807QRx9Q73A2N5hNwRRslC2H9sNzaFhsPubkS4L8oNQ==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.8.6.tgz", + "integrity": "sha512-zbMsPMy/v0PWFZEhQJ66bqjhH+z0JgMoBWuikXybgG3Gkd/3t5oQ1Rw2WQhnSrsOmsKXnZOx15tkC4qON/+JPg==", "dev": true, "requires": { - "@babel/code-frame": "^7.0.0", - "@babel/parser": "^7.6.0", - "@babel/types": "^7.6.0" + "@babel/code-frame": "^7.8.3", + "@babel/parser": "^7.8.6", + "@babel/types": "^7.8.6" + }, + "dependencies": { + "@babel/code-frame": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", + "dev": true, + "requires": { + "@babel/highlight": "^7.8.3" + } + }, + "@babel/highlight": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.8.3.tgz", + "integrity": "sha512-PX4y5xQUvy0fnEVHrYOarRPXVWafSjTW9T0Hab8gVIawpl2Sj0ORyrygANq+KjcNlSSTw0YCLSNA8OyZ1I4yEg==", + "dev": true, + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + } } }, "@babel/traverse": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.6.2.tgz", - "integrity": "sha512-8fRE76xNwNttVEF2TwxJDGBLWthUkHWSldmfuBzVRmEDWOtu4XdINTgN7TDWzuLg4bbeIMLvfMFD9we5YcWkRQ==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.8.6.tgz", + "integrity": "sha512-2B8l0db/DPi8iinITKuo7cbPznLCEk0kCxDoB9/N6gGNg/gxOXiR/IcymAFPiBwk5w6TtQ27w4wpElgp9btR9A==", "dev": true, "requires": { - "@babel/code-frame": "^7.5.5", - "@babel/generator": "^7.6.2", - "@babel/helper-function-name": "^7.1.0", - "@babel/helper-split-export-declaration": "^7.4.4", - "@babel/parser": "^7.6.2", - "@babel/types": "^7.6.0", + "@babel/code-frame": "^7.8.3", + "@babel/generator": "^7.8.6", + "@babel/helper-function-name": "^7.8.3", + "@babel/helper-split-export-declaration": "^7.8.3", + "@babel/parser": "^7.8.6", + "@babel/types": "^7.8.6", "debug": "^4.1.0", "globals": "^11.1.0", "lodash": "^4.17.13" + }, + "dependencies": { + "@babel/code-frame": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", + "dev": true, + "requires": { + "@babel/highlight": "^7.8.3" + } + }, + "@babel/highlight": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.8.3.tgz", + "integrity": "sha512-PX4y5xQUvy0fnEVHrYOarRPXVWafSjTW9T0Hab8gVIawpl2Sj0ORyrygANq+KjcNlSSTw0YCLSNA8OyZ1I4yEg==", + "dev": true, + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + } } }, "@babel/types": { - "version": "7.6.1", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.6.1.tgz", - "integrity": "sha512-X7gdiuaCmA0uRjCmRtYJNAVCc/q+5xSgsfKJHqMN4iNLILX39677fJE1O40arPMh0TTtS9ItH67yre6c7k6t0g==", + "version": "7.8.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.8.7.tgz", + "integrity": "sha512-k2TreEHxFA4CjGkL+GYjRyx35W0Mr7DP5+9q6WMkyKXB+904bYmG40syjMFV0oLlhhFCwWl0vA0DyzTDkwAiJw==", "dev": true, "requires": { "esutils": "^2.0.2", @@ -153,10 +289,52 @@ "to-fast-properties": "^2.0.0" } }, + "@istanbuljs/load-nyc-config": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.0.0.tgz", + "integrity": "sha512-ZR0rq/f/E4f4XcgnDvtMWXCUJpi8eO0rssVhmztsZqLIEFA9UUP9zmpE0VxlM+kv/E1ul2I876Fwil2ayptDVg==", + "dev": true, + "requires": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "dependencies": { + "camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + } + } + }, + "@istanbuljs/schema": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.2.tgz", + "integrity": "sha512-tsAQNx32a8CoFhjhijUIhI4kccIAgmGhy8LZMZgGfmXcpMbPRUqn5LWmgRttILi6yeGmBJd2xsPkFMs0PzgPCw==", + "dev": true + }, "@types/bluebird": { - "version": "3.5.29", - "resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.29.tgz", - "integrity": "sha512-kmVtnxTuUuhCET669irqQmPAez4KFnFVKvpleVRyfC3g+SHD1hIkFZcWLim9BVcwUBLO59o8VZE4yGCmTif8Yw==" + "version": "3.5.30", + "resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.30.tgz", + "integrity": "sha512-8LhzvcjIoqoi1TghEkRMkbbmM+jhHnBokPGkJWjclMK+Ks0MxEBow3/p2/iFTZ+OIbJHQDSfpgdZEb+af3gfVw==" }, "@types/caseless": { "version": "0.12.1", @@ -169,6 +347,12 @@ "integrity": "sha512-D8uQwKYUw2KESkorZ27ykzXgvkDJYXVEihGklgfp5I4HUP8D6IxtcdLTMB1emjQiWzV7WZ5ihm1cxIzVwjoleQ==", "dev": true }, + "@types/color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==", + "dev": true + }, "@types/crypto-js": { "version": "3.1.43", "resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-3.1.43.tgz", @@ -246,6 +430,16 @@ "@types/node": "*" } }, + "aggregate-error": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.0.1.tgz", + "integrity": "sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA==", + "dev": true, + "requires": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + } + }, "ajv": { "version": "6.10.2", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.2.tgz", @@ -315,12 +509,12 @@ } }, "append-transform": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-1.0.0.tgz", - "integrity": "sha512-P009oYkeHyU742iSZJzZZywj4QRJdnTWffaKuJQLablCZ1uz6/cW4yaRgcDaoQ+uwOxxnt0gRUcwfsNP2ri0gw==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-2.0.0.tgz", + "integrity": "sha512-7yeyCEurROLQJFv5Xj4lEGTy0borxepjFv1g22oAdqFu//SrAlDl1O1Nxx15SH1RoliUml6p8dwJW9jvZughhg==", "dev": true, "requires": { - "default-require-extensions": "^2.0.0" + "default-require-extensions": "^3.0.0" } }, "archy": { @@ -329,6 +523,12 @@ "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", "dev": true }, + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true + }, "argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", @@ -446,12 +646,6 @@ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", "dev": true }, - "arrify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", - "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", - "dev": true - }, "asn1": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", @@ -509,11 +703,6 @@ "integrity": "sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==", "dev": true }, - "async-limiter": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", - "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==" - }, "async-settle": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/async-settle/-/async-settle-1.0.0.tgz", @@ -855,9 +1044,9 @@ "dev": true }, "bluebird": { - "version": "3.5.5", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.5.tgz", - "integrity": "sha512-5am6HnnfN+urzt4yfg7IgTbotDjIT/u8AJpEt0sIU9FtXfVeezXAPKswrG+xKUCOYAINpSdgZVDU6QFh+cuH3w==" + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" }, "brace-expansion": { "version": "1.1.11", @@ -944,15 +1133,15 @@ } }, "caching-transform": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/caching-transform/-/caching-transform-3.0.2.tgz", - "integrity": "sha512-Mtgcv3lh3U0zRii/6qVgQODdPA4G3zhG+jtbCWj39RXuUFTMzH0vcdMtaJS1jPowd+It2Pqr6y3NJMQqOqCE2w==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/caching-transform/-/caching-transform-4.0.0.tgz", + "integrity": "sha512-kpqOvwXnjjN44D89K5ccQC+RUrsy7jB/XLlRrx0D7/2HNcTPqzsb6XgYoErwko6QsV184CA2YgS1fxDiiDZMWA==", "dev": true, "requires": { - "hasha": "^3.0.0", - "make-dir": "^2.0.0", - "package-hash": "^3.0.0", - "write-file-atomic": "^2.4.2" + "hasha": "^5.0.0", + "make-dir": "^3.0.0", + "package-hash": "^4.0.0", + "write-file-atomic": "^3.0.0" } }, "camelcase": { @@ -1053,6 +1242,12 @@ } } }, + "clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "dev": true + }, "cliui": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", @@ -1219,169 +1414,40 @@ "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, "coveralls": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/coveralls/-/coveralls-3.0.6.tgz", - "integrity": "sha512-Pgh4v3gCI4T/9VijVrm8Ym5v0OgjvGLKj3zTUwkvsCiwqae/p6VLzpsFNjQS2i6ewV7ef+DjFJ5TSKxYt/mCrA==", + "version": "3.0.9", + "resolved": "https://registry.npmjs.org/coveralls/-/coveralls-3.0.9.tgz", + "integrity": "sha512-nNBg3B1+4iDox5A5zqHKzUTiwl2ey4k2o0NEcVZYvl+GOSJdKBj4AJGKLv6h3SvWch7tABHePAQOSZWM9E2hMg==", "dev": true, "requires": { - "growl": "~> 1.10.0", "js-yaml": "^3.13.1", - "lcov-parse": "^0.0.10", + "lcov-parse": "^1.0.0", "log-driver": "^1.2.7", "minimist": "^1.2.0", - "request": "^2.86.0" - }, - "dependencies": { - "ajv": { - "version": "6.10.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.2.tgz", - "integrity": "sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw==", - "dev": true, - "requires": { - "fast-deep-equal": "^2.0.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - } - }, - "aws4": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", - "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==", - "dev": true - }, - "fast-deep-equal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", - "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", - "dev": true - }, - "har-validator": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz", - "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==", - "dev": true, - "requires": { - "ajv": "^6.5.5", - "har-schema": "^2.0.0" - } - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true - }, - "mime-db": { - "version": "1.40.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz", - "integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==", - "dev": true - }, - "mime-types": { - "version": "2.1.24", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz", - "integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==", - "dev": true, - "requires": { - "mime-db": "1.40.0" - } - }, - "oauth-sign": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", - "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", - "dev": true - }, - "qs": { - "version": "6.5.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", - "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", - "dev": true - }, - "request": { - "version": "2.88.0", - "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", - "integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==", - "dev": true, - "requires": { - "aws-sign2": "~0.7.0", - "aws4": "^1.8.0", - "caseless": "~0.12.0", - "combined-stream": "~1.0.6", - "extend": "~3.0.2", - "forever-agent": "~0.6.1", - "form-data": "~2.3.2", - "har-validator": "~5.1.0", - "http-signature": "~1.2.0", - "is-typedarray": "~1.0.0", - "isstream": "~0.1.2", - "json-stringify-safe": "~5.0.1", - "mime-types": "~2.1.19", - "oauth-sign": "~0.9.0", - "performance-now": "^2.1.0", - "qs": "~6.5.2", - "safe-buffer": "^5.1.2", - "tough-cookie": "~2.4.3", - "tunnel-agent": "^0.6.0", - "uuid": "^3.3.2" - } - }, - "safe-buffer": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", - "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", - "dev": true - }, - "tough-cookie": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", - "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", - "dev": true, - "requires": { - "psl": "^1.1.24", - "punycode": "^1.4.1" - } - }, - "uuid": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.3.tgz", - "integrity": "sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ==", - "dev": true - } + "request": "^2.88.0" } }, - "cp-file": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/cp-file/-/cp-file-6.2.0.tgz", - "integrity": "sha512-fmvV4caBnofhPe8kOcitBwSn2f39QLjnAnGq3gO9dfd75mUytzKNZB1hde6QHunW2Rt+OwuBOMc3i1tNElbszA==", + "cross-spawn": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz", + "integrity": "sha512-u7v4o84SwFpD32Z8IIcPZ6z1/ie24O6RU3RbtL5Y316l3KuHVPx9ItBgWQ6VlfAFnRnTtMUrsQ9MUUTuEZjogg==", "dev": true, "requires": { - "graceful-fs": "^4.1.2", - "make-dir": "^2.0.0", - "nested-error-stacks": "^2.0.0", - "pify": "^4.0.1", - "safe-buffer": "^5.0.1" + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" }, "dependencies": { - "pify": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", - "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", - "dev": true + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } } } }, - "cross-spawn": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-4.0.2.tgz", - "integrity": "sha1-e5JHYhwjrf3ThWAEqCPL45dCTUE=", - "dev": true, - "requires": { - "lru-cache": "^4.0.1", - "which": "^1.2.9" - } - }, "crypto-js": { "version": "3.1.9-1", "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-3.1.9-1.tgz", @@ -1460,18 +1526,18 @@ } }, "default-require-extensions": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-2.0.0.tgz", - "integrity": "sha1-9fj7sYp9bVCyH2QfZJ67Uiz+JPc=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-3.0.0.tgz", + "integrity": "sha512-ek6DpXq/SCpvjhpFsLFRVtIxJCRw6fUR42lYMVZuUMK7n8eMz4Uh5clckdBjEpLhn/gEBZo7hDJnJcwdKLKQjg==", "dev": true, "requires": { - "strip-bom": "^3.0.0" + "strip-bom": "^4.0.0" }, "dependencies": { "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", "dev": true } } @@ -1588,9 +1654,9 @@ } }, "emoji-regex": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", - "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, "end-of-stream": { @@ -1872,14 +1938,14 @@ } }, "find-cache-dir": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.1.0.tgz", - "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.1.tgz", + "integrity": "sha512-t2GDMt3oGC/v+BMwzmllWDuJF/xcDtE5j/fCGbqDD7OLuJkj0cfh1YSA5VKPvwMeLFLNDBkwOKZ2X85jGLVftQ==", "dev": true, "requires": { "commondir": "^1.0.1", - "make-dir": "^2.0.0", - "pkg-dir": "^3.0.0" + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" } }, "find-up": { @@ -1949,13 +2015,13 @@ } }, "foreground-child": { - "version": "1.5.6", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-1.5.6.tgz", - "integrity": "sha1-T9ca0t/elnibmApcCilZN8svXOk=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-2.0.0.tgz", + "integrity": "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==", "dev": true, "requires": { - "cross-spawn": "^4", - "signal-exit": "^3.0.0" + "cross-spawn": "^7.0.0", + "signal-exit": "^3.0.2" } }, "forever-agent": { @@ -1982,6 +2048,12 @@ "map-cache": "^0.2.2" } }, + "fromentries": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fromentries/-/fromentries-1.2.0.tgz", + "integrity": "sha512-33X7H/wdfO99GdRLLgkjUrD4geAFdq/Uv0kl3HD4da6HDixd2GUg8Mw7dahLCV9r/EARkmtYBB6Tch4EEokFTQ==", + "dev": true + }, "fs-mkdirp-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz", @@ -2564,6 +2636,12 @@ "resolved": "https://registry.npmjs.org/futoin-hkdf/-/futoin-hkdf-1.3.1.tgz", "integrity": "sha512-k1DvCXIFAIx3hK8CSwApotX3JUDwA2Wb55zxyIgqwQpCBF2ZHgVqfHpyjG8mRpmsjRH7SWS1N/vj8EdSF9zBhw==" }, + "gensync": { + "version": "1.0.0-beta.1", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.1.tgz", + "integrity": "sha512-r8EC6NO1sngH/zdD9fiRDLdcgnbayXah+mLgManTaIZJqEC1MZstmnox8KpnI2/fxQwrp5OpCOYWLp4rBl4Jcg==", + "dev": true + }, "get-caller-file": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", @@ -2794,26 +2872,6 @@ "glogg": "^1.0.0" } }, - "handlebars": { - "version": "4.5.3", - "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.5.3.tgz", - "integrity": "sha512-3yPecJoJHK/4c6aZhSvxOyG4vJKDshV36VHp0iVCDVh7o9w2vwi3NSnL2MMPj3YdduqaBcu7cGbggJQM0br9xA==", - "dev": true, - "requires": { - "neo-async": "^2.6.0", - "optimist": "^0.6.1", - "source-map": "^0.6.1", - "uglify-js": "^3.1.4" - }, - "dependencies": { - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true - } - } - }, "har-schema": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", @@ -2890,12 +2948,13 @@ } }, "hasha": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/hasha/-/hasha-3.0.0.tgz", - "integrity": "sha1-UqMvq4Vp1BymmmH/GiFPjrfIvTk=", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/hasha/-/hasha-5.2.0.tgz", + "integrity": "sha512-2W+jKdQbAdSIrggA8Q35Br8qKadTrqCTC8+XZvBWepKDK6m9XkX6Iz1a2yh2KP01kzAR/dpuMeUnocoLYDcskw==", "dev": true, "requires": { - "is-stream": "^1.0.1" + "is-stream": "^2.0.0", + "type-fest": "^0.8.0" } }, "he": { @@ -2928,6 +2987,12 @@ "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==", "dev": true }, + "html-escaper": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.0.tgz", + "integrity": "sha512-a4u9BeERWGu/S8JiWEAQcdrg9v4QArtP9keViQjGMdff20fBdd8waotXaNmODqBe6uZ3Nafi7K/ho4gCQHV3Ig==", + "dev": true + }, "http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -2944,6 +3009,12 @@ "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", "dev": true }, + "indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true + }, "inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -3155,9 +3226,9 @@ } }, "is-stream": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", - "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", "dev": true }, "is-typedarray": { @@ -3216,33 +3287,33 @@ "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" }, "istanbul-lib-coverage": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz", - "integrity": "sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz", + "integrity": "sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg==", "dev": true }, "istanbul-lib-hook": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-2.0.7.tgz", - "integrity": "sha512-vrRztU9VRRFDyC+aklfLoeXyNdTfga2EI3udDGn4cZ6fpSXpHLV9X6CHvfoMCPtggg8zvDDmC4b9xfu0z6/llA==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-3.0.0.tgz", + "integrity": "sha512-Pt/uge1Q9s+5VAZ+pCo16TYMWPBIl+oaNIjgLQxcX0itS6ueeaA+pEfThZpH8WxhFgCiEb8sAJY6MdUKgiIWaQ==", "dev": true, "requires": { - "append-transform": "^1.0.0" + "append-transform": "^2.0.0" } }, "istanbul-lib-instrument": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-3.3.0.tgz", - "integrity": "sha512-5nnIN4vo5xQZHdXno/YDXJ0G+I3dAm4XgzfSVTPLQpj/zAV2dV6Juy0yaf10/zrJOJeHoN3fraFe+XRq2bFVZA==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.1.tgz", + "integrity": "sha512-imIchxnodll7pvQBYOqUu88EufLCU56LMeFPZZM/fJZ1irYcYdqroaV+ACK1Ila8ls09iEYArp+nqyC6lW1Vfg==", "dev": true, "requires": { - "@babel/generator": "^7.4.0", - "@babel/parser": "^7.4.3", - "@babel/template": "^7.4.0", - "@babel/traverse": "^7.4.3", - "@babel/types": "^7.4.0", - "istanbul-lib-coverage": "^2.0.5", - "semver": "^6.0.0" + "@babel/core": "^7.7.5", + "@babel/parser": "^7.7.5", + "@babel/template": "^7.7.4", + "@babel/traverse": "^7.7.4", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.0.0", + "semver": "^6.3.0" }, "dependencies": { "semver": { @@ -3253,44 +3324,57 @@ } } }, + "istanbul-lib-processinfo": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-processinfo/-/istanbul-lib-processinfo-2.0.2.tgz", + "integrity": "sha512-kOwpa7z9hme+IBPZMzQ5vdQj8srYgAtaRqeI48NGmAQ+/5yKiHLV0QbYqQpxsdEF0+w14SoB8YbnHKcXE2KnYw==", + "dev": true, + "requires": { + "archy": "^1.0.0", + "cross-spawn": "^7.0.0", + "istanbul-lib-coverage": "^3.0.0-alpha.1", + "make-dir": "^3.0.0", + "p-map": "^3.0.0", + "rimraf": "^3.0.0", + "uuid": "^3.3.3" + } + }, "istanbul-lib-report": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-2.0.8.tgz", - "integrity": "sha512-fHBeG573EIihhAblwgxrSenp0Dby6tJMFR/HvlerBsrCTD5bkUuoNtn3gVh29ZCS824cGGBPn7Sg7cNk+2xUsQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", "dev": true, "requires": { - "istanbul-lib-coverage": "^2.0.5", - "make-dir": "^2.1.0", - "supports-color": "^6.1.0" + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" }, "dependencies": { "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, "supports-color": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", - "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", + "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", "dev": true, "requires": { - "has-flag": "^3.0.0" + "has-flag": "^4.0.0" } } } }, "istanbul-lib-source-maps": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz", - "integrity": "sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.0.tgz", + "integrity": "sha512-c16LpFRkR8vQXyHZ5nLpY35JZtzj1PQY1iZmesUbf1FZHbIupcWfjgOXBY9YHkLEQ6puz1u4Dgj6qmU/DisrZg==", "dev": true, "requires": { "debug": "^4.1.1", - "istanbul-lib-coverage": "^2.0.5", - "make-dir": "^2.1.0", - "rimraf": "^2.6.3", + "istanbul-lib-coverage": "^3.0.0", "source-map": "^0.6.1" }, "dependencies": { @@ -3303,12 +3387,13 @@ } }, "istanbul-reports": { - "version": "2.2.6", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-2.2.6.tgz", - "integrity": "sha512-SKi4rnMyLBKe0Jy2uUdx28h8oG7ph2PPuQPvIAh31d+Ci+lSiEu4C+h3oBPuJ9+mPKhOyW0M8gY4U5NM1WLeXA==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.0.0.tgz", + "integrity": "sha512-2osTcC8zcOSUkImzN2EWQta3Vdi4WjjKw99P2yWx5mLnigAM0Rd5uYFn1cf2i/Ois45GkNjaoTqc5CxgMSX80A==", "dev": true, "requires": { - "handlebars": "^4.1.2" + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" } }, "js-joda": { @@ -3358,12 +3443,6 @@ "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", "dev": true }, - "json-parse-better-errors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", - "dev": true - }, "json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", @@ -3442,9 +3521,9 @@ } }, "lcov-parse": { - "version": "0.0.10", - "resolved": "https://registry.npmjs.org/lcov-parse/-/lcov-parse-0.0.10.tgz", - "integrity": "sha1-GwuP+ayceIklBYK3C3ExXZ2m2aM=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lcov-parse/-/lcov-parse-1.0.0.tgz", + "integrity": "sha1-6w1GtUER68VhrLTECO+TY73I9+A=", "dev": true }, "lead": { @@ -3486,21 +3565,12 @@ } }, "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - }, - "dependencies": { - "path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true - } + "p-locate": "^4.1.0" } }, "lodash": { @@ -3533,44 +3603,27 @@ "js-tokens": "^3.0.0 || ^4.0.0" } }, - "lru-cache": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", - "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", - "dev": true, - "requires": { - "pseudomap": "^1.0.2", - "yallist": "^2.1.2" - } - }, "make-dir": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", - "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz", + "integrity": "sha512-rYKABKutXa6vXTXhoV18cBE7PaewPXHe/Bdq4v+ZLMhxbWApkFFplT0LcbMW+6BbjnQXzZ/sAvSE/JdguApG5w==", "dev": true, "requires": { - "pify": "^4.0.1", - "semver": "^5.6.0" + "semver": "^6.0.0" }, "dependencies": { - "pify": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", - "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", - "dev": true - }, "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", "dev": true } } }, "make-error": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.4.tgz", - "integrity": "sha512-0Dab5btKVPhibSalc9QGXb559ED7G7iLjFXBaj9Wq8O3vorueR5K5jaE3hkG6ZQINyhA/JgG6Qk4qdFQjsYV6g==", + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", "dev": true }, "make-iterator": { @@ -3632,23 +3685,6 @@ } } }, - "merge-source-map": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/merge-source-map/-/merge-source-map-1.1.0.tgz", - "integrity": "sha512-Qkcp7P2ygktpMPh2mCQZaf3jhN6D3Z/qVZHSdWvQ+2Ef5HgRAPBO57A77+ENm0CPx2+1Ce/MYKi3ymqdfuqibw==", - "dev": true, - "requires": { - "source-map": "^0.6.1" - }, - "dependencies": { - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true - } - } - }, "merkle-lib": { "version": "2.0.10", "resolved": "https://registry.npmjs.org/merkle-lib/-/merkle-lib-2.0.10.tgz", @@ -3716,10 +3752,9 @@ } }, "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "dev": true + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" }, "mixin-deep": { "version": "1.3.2", @@ -3837,24 +3872,21 @@ "to-regex": "^3.0.1" } }, - "neo-async": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.1.tgz", - "integrity": "sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==", - "dev": true - }, - "nested-error-stacks": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/nested-error-stacks/-/nested-error-stacks-2.1.0.tgz", - "integrity": "sha512-AO81vsIO1k1sM4Zrd6Hu7regmJN1NSiAja10gc4bX3F0wd+9rQmcuHQaHVQCYIEC8iFXnE+mavh23GOt7wBgug==", - "dev": true - }, "next-tick": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=", "dev": true }, + "node-preload": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/node-preload/-/node-preload-0.2.1.tgz", + "integrity": "sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==", + "dev": true, + "requires": { + "process-on-spawn": "^1.0.0" + } + }, "normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", @@ -3909,51 +3941,55 @@ "dev": true }, "nyc": { - "version": "14.1.1", - "resolved": "https://registry.npmjs.org/nyc/-/nyc-14.1.1.tgz", - "integrity": "sha512-OI0vm6ZGUnoGZv/tLdZ2esSVzDwUC88SNs+6JoSOMVxA+gKMB8Tk7jBwgemLx4O40lhhvZCVw1C+OYLOBOPXWw==", - "dev": true, - "requires": { - "archy": "^1.0.0", - "caching-transform": "^3.0.2", - "convert-source-map": "^1.6.0", - "cp-file": "^6.2.0", - "find-cache-dir": "^2.1.0", - "find-up": "^3.0.0", - "foreground-child": "^1.5.6", - "glob": "^7.1.3", - "istanbul-lib-coverage": "^2.0.5", - "istanbul-lib-hook": "^2.0.7", - "istanbul-lib-instrument": "^3.3.0", - "istanbul-lib-report": "^2.0.8", - "istanbul-lib-source-maps": "^3.0.6", - "istanbul-reports": "^2.2.4", + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/nyc/-/nyc-15.0.0.tgz", + "integrity": "sha512-qcLBlNCKMDVuKb7d1fpxjPR8sHeMVX0CHarXAVzrVWoFrigCkYR8xcrjfXSPi5HXM7EU78L6ywO7w1c5rZNCNg==", + "dev": true, + "requires": { + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "caching-transform": "^4.0.0", + "convert-source-map": "^1.7.0", + "decamelize": "^1.2.0", + "find-cache-dir": "^3.2.0", + "find-up": "^4.1.0", + "foreground-child": "^2.0.0", + "glob": "^7.1.6", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-hook": "^3.0.0", + "istanbul-lib-instrument": "^4.0.0", + "istanbul-lib-processinfo": "^2.0.2", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.0.0", "js-yaml": "^3.13.1", - "make-dir": "^2.1.0", - "merge-source-map": "^1.1.0", - "resolve-from": "^4.0.0", - "rimraf": "^2.6.3", + "make-dir": "^3.0.0", + "node-preload": "^0.2.0", + "p-map": "^3.0.0", + "process-on-spawn": "^1.0.0", + "resolve-from": "^5.0.0", + "rimraf": "^3.0.0", "signal-exit": "^3.0.2", - "spawn-wrap": "^1.4.2", - "test-exclude": "^5.2.3", - "uuid": "^3.3.2", - "yargs": "^13.2.2", - "yargs-parser": "^13.0.0" + "spawn-wrap": "^2.0.0", + "test-exclude": "^6.0.0", + "uuid": "^3.3.3", + "yargs": "^15.0.2" }, "dependencies": { "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", "dev": true }, "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", "dev": true, "requires": { - "color-convert": "^1.9.0" + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" } }, "camelcase": { @@ -3963,23 +3999,48 @@ "dev": true }, "cliui": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", - "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dev": true, + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "convert-source-map": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", + "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", "dev": true, "requires": { - "string-width": "^3.1.0", - "strip-ansi": "^5.2.0", - "wrap-ansi": "^5.1.0" + "safe-buffer": "~5.1.1" } }, "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { - "locate-path": "^3.0.0" + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" } }, "get-caller-file": { @@ -3989,9 +4050,9 @@ "dev": true }, "glob": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", - "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", "dev": true, "requires": { "fs.realpath": "^1.0.0", @@ -4003,9 +4064,15 @@ } }, "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true }, "require-main-filename": { @@ -4015,46 +4082,40 @@ "dev": true }, "string-width": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", "dev": true, "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" } }, "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { - "ansi-regex": "^4.1.0" + "ansi-regex": "^5.0.0" } }, - "uuid": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.3.tgz", - "integrity": "sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ==", - "dev": true - }, "which-module": { "version": "2.0.0", - "resolved": "", + "resolved": false, "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, "wrap-ansi": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", - "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, "requires": { - "ansi-styles": "^3.2.0", - "string-width": "^3.0.0", - "strip-ansi": "^5.0.0" + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" } }, "y18n": { @@ -4064,27 +4125,28 @@ "dev": true }, "yargs": { - "version": "13.3.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.0.tgz", - "integrity": "sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA==", + "version": "15.3.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.3.0.tgz", + "integrity": "sha512-g/QCnmjgOl1YJjGsnUg2SatC7NUYEiLXJqxNOQU9qSpjzGtGXda9b+OKccr1kLTy8BN9yqEyqfq5lxlwdc13TA==", "dev": true, "requires": { - "cliui": "^5.0.0", - "find-up": "^3.0.0", + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", - "string-width": "^3.0.0", + "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", - "yargs-parser": "^13.1.1" + "yargs-parser": "^18.1.0" } }, "yargs-parser": { - "version": "13.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.1.tgz", - "integrity": "sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ==", + "version": "18.1.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.0.tgz", + "integrity": "sha512-o/Jr6JBOv6Yx3pL+5naWSoIA2jJ+ZkMYQG/ie9qFbukBe4uzmBatlXFOiu/tNKRWEtyf+n5w7jc/O16ufqOTdQ==", "dev": true, "requires": { "camelcase": "^5.0.0", @@ -4206,24 +4268,6 @@ "wrappy": "1" } }, - "optimist": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", - "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", - "dev": true, - "requires": { - "minimist": "~0.0.1", - "wordwrap": "~0.0.2" - }, - "dependencies": { - "minimist": { - "version": "0.0.10", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", - "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=", - "dev": true - } - } - }, "ordered-read-streams": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/ordered-read-streams/-/ordered-read-streams-1.0.1.tgz", @@ -4253,21 +4297,30 @@ "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" }, "p-limit": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.1.tgz", - "integrity": "sha512-85Tk+90UCVWvbDavCLKPOLC9vvY8OwEX/RtKF+/1OADJMVlFfEHOiMTPVyxg7mk/dKa+ipdHm0OUkTvCpMTuwg==", + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.2.tgz", + "integrity": "sha512-WGR+xHecKTr7EbUEhyLSh5Dube9JtdiG78ufaeLxTgpudf/20KqyMioIUZJAezlTIi6evxuoUs9YXc11cU+yzQ==", "dev": true, "requires": { "p-try": "^2.0.0" } }, "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + } + }, + "p-map": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-3.0.0.tgz", + "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", "dev": true, "requires": { - "p-limit": "^2.0.0" + "aggregate-error": "^3.0.0" } }, "p-try": { @@ -4277,13 +4330,13 @@ "dev": true }, "package-hash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/package-hash/-/package-hash-3.0.0.tgz", - "integrity": "sha512-lOtmukMDVvtkL84rJHI7dpTYq+0rli8N2wlnqUcBuDWCfVhRUfOmnR9SsoHFMLpACvEV60dX7rd0rFaYDZI+FA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/package-hash/-/package-hash-4.0.0.tgz", + "integrity": "sha512-whdkPIooSu/bASggZ96BWVvZTRMOFxnyUG5PnTSGKoJE2gd5mbVNmR2Nj20QFzxYYgAXpoqC+AiXzl+UMRh7zQ==", "dev": true, "requires": { "graceful-fs": "^4.1.15", - "hasha": "^3.0.0", + "hasha": "^5.0.0", "lodash.flattendeep": "^4.4.0", "release-zalgo": "^1.0.0" } @@ -4346,6 +4399,12 @@ "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, "path-parse": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", @@ -4411,22 +4470,29 @@ } }, "pkg-dir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", - "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, "requires": { - "find-up": "^3.0.0" + "find-up": "^4.0.0" }, "dependencies": { "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { - "locate-path": "^3.0.0" + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" } + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true } } }, @@ -4465,11 +4531,14 @@ "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", "dev": true }, - "pseudomap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", - "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", - "dev": true + "process-on-spawn": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/process-on-spawn/-/process-on-spawn-1.0.0.tgz", + "integrity": "sha512-1WsPDsUSMmZH5LeMLegqkPDrsGgsWwk1Exipy2hvB0o/F0ASzbpIctSCcZIK1ykJvtTJULEH+20WOFjMvGnCTg==", + "dev": true, + "requires": { + "fromentries": "^1.2.0" + } }, "psl": { "version": "1.4.0", @@ -4757,9 +4826,9 @@ } }, "resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "dev": true }, "resolve-options": { @@ -4793,18 +4862,18 @@ } }, "rimraf": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", - "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "dev": true, "requires": { "glob": "^7.1.3" }, "dependencies": { "glob": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", - "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", "dev": true, "requires": { "fs.realpath": "^1.0.0", @@ -4903,6 +4972,21 @@ } } }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, "signal-exit": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", @@ -5069,17 +5153,28 @@ "dev": true }, "spawn-wrap": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/spawn-wrap/-/spawn-wrap-1.4.3.tgz", - "integrity": "sha512-IgB8md0QW/+tWqcavuFgKYR/qIRvJkRLPJDFaoXtLLUaVcCDK0+HeFTkmQHj3eprcYhc+gOl0aEA1w7qZlYezw==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/spawn-wrap/-/spawn-wrap-2.0.0.tgz", + "integrity": "sha512-EeajNjfN9zMnULLwhZZQU3GWBoFNkbngTUPfaawT4RkMiviTxcX0qfhVbGey39mfctfDHkWtuecgQ8NJcyQWHg==", "dev": true, "requires": { - "foreground-child": "^1.5.6", - "mkdirp": "^0.5.0", - "os-homedir": "^1.0.1", - "rimraf": "^2.6.2", + "foreground-child": "^2.0.0", + "is-windows": "^1.0.2", + "make-dir": "^3.0.0", + "rimraf": "^3.0.0", "signal-exit": "^3.0.2", - "which": "^1.3.0" + "which": "^2.0.1" + }, + "dependencies": { + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } } }, "spdx-correct": { @@ -5261,9 +5356,9 @@ } }, "symbol-openapi-typescript-node-client": { - "version": "0.8.5", - "resolved": "https://registry.npmjs.org/symbol-openapi-typescript-node-client/-/symbol-openapi-typescript-node-client-0.8.5.tgz", - "integrity": "sha512-1o6qvkabi93xLRHr/C2A+uFhesaXF26EsFIRW6B51DLOGFOrDRPlobnKyahRkieJXEALTOj6MXimUGd/O6jdSw==", + "version": "0.8.9", + "resolved": "https://registry.npmjs.org/symbol-openapi-typescript-node-client/-/symbol-openapi-typescript-node-client-0.8.9.tgz", + "integrity": "sha512-JElZ2vA63oqFGaT2wdEe7L2P17i3NaTwQhoQO4Pk1zMrQ9D+dGI1iknTuAXj2+xqxj36vLJX4Vi1UugvSkfJCA==", "requires": { "@types/bluebird": "*", "@types/request": "*", @@ -5273,30 +5368,20 @@ } }, "test-exclude": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-5.2.3.tgz", - "integrity": "sha512-M+oxtseCFO3EDtAaGH7iiej3CBkzXqFMbzqYAACdzKui4eZA+pq3tZEwChvOdNfa7xxy8BfbmgJSIr43cC/+2g==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", "dev": true, "requires": { - "glob": "^7.1.3", - "minimatch": "^3.0.4", - "read-pkg-up": "^4.0.0", - "require-main-filename": "^2.0.0" + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" }, "dependencies": { - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, "glob": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", - "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", "dev": true, "requires": { "fs.realpath": "^1.0.0", @@ -5306,76 +5391,6 @@ "once": "^1.3.0", "path-is-absolute": "^1.0.0" } - }, - "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "^4.1.2", - "parse-json": "^4.0.0", - "pify": "^3.0.0", - "strip-bom": "^3.0.0" - } - }, - "parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", - "dev": true, - "requires": { - "error-ex": "^1.3.1", - "json-parse-better-errors": "^1.0.1" - } - }, - "path-type": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", - "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", - "dev": true, - "requires": { - "pify": "^3.0.0" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, - "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", - "dev": true, - "requires": { - "load-json-file": "^4.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^3.0.0" - } - }, - "read-pkg-up": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-4.0.0.tgz", - "integrity": "sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA==", - "dev": true, - "requires": { - "find-up": "^3.0.0", - "read-pkg": "^3.0.0" - } - }, - "require-main-filename": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", - "dev": true - }, - "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true } } }, @@ -5500,53 +5515,18 @@ } }, "ts-node": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-5.0.1.tgz", - "integrity": "sha512-XK7QmDcNHVmZkVtkiwNDWiERRHPyU8nBqZB1+iv2UhOG0q3RQ9HsZ2CMqISlFbxjrYFGfG2mX7bW4dAyxBVzUw==", + "version": "8.6.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-8.6.2.tgz", + "integrity": "sha512-4mZEbofxGqLL2RImpe3zMJukvEvcO1XP8bj8ozBPySdCUXEcU5cIRwR0aM3R+VoZq7iXc8N86NC0FspGRqP4gg==", "dev": true, "requires": { - "arrify": "^1.0.0", - "chalk": "^2.3.0", - "diff": "^3.1.0", + "arg": "^4.1.0", + "diff": "^4.0.1", "make-error": "^1.1.1", - "minimist": "^1.2.0", - "mkdirp": "^0.5.1", - "source-map-support": "^0.5.3", - "yn": "^2.0.0" + "source-map-support": "^0.5.6", + "yn": "3.1.1" }, "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.2.tgz", - "integrity": "sha512-ZM4j2/ld/YZDc3Ma8PgN7gyAk+kHMMMyzLNryCPGhWrsfAuDVeuid5bpRFTDgMH9JBK2lA4dyyAkkZYF/WcqDQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "diff": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", - "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", - "dev": true - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, "source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -5554,22 +5534,14 @@ "dev": true }, "source-map-support": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.4.tgz", - "integrity": "sha512-PETSPG6BjY1AHs2t64vS2aqAgu6dMIMXJULWFBGbh2Gr8nVLbCFDo6i/RMMvviIQ2h1Z8+5gQhVKSn2je9nmdg==", + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.16.tgz", + "integrity": "sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ==", "dev": true, "requires": { + "buffer-from": "^1.0.0", "source-map": "^0.6.0" } - }, - "supports-color": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.3.0.tgz", - "integrity": "sha512-0aP01LLIskjKs3lq52EC0aGBAJhLq7B2Rd8HC/DR/PtNNpcLilNmHC12O+hu0usQpo7wtHNRqtrhBwtDb0+dNg==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } } } }, @@ -5579,9 +5551,9 @@ "integrity": "sha512-f/qGG2tUkrISBlQZEjEqoZ3B2+npJjIf04H1wuAv9iA8i04Icp+61KRXxFdha22670NJopsZCIjhC3SnjPRKrQ==" }, "tslint": { - "version": "5.20.1", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.20.1.tgz", - "integrity": "sha512-EcMxhzCFt8k+/UP5r8waCf/lzmeSyVlqxqMEDQE7rWYiQky8KpIBz1JAoYXfROHrPZ1XXd43q8yQnULOLiBRQg==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-6.0.0.tgz", + "integrity": "sha512-9nLya8GBtlFmmFMW7oXXwoXS1NkrccqTqAtwXzdPV9e2mqSEvCki6iHL/Fbzi5oqbugshzgGPk7KBb2qNP1DSA==", "dev": true, "requires": { "@babel/code-frame": "^7.0.0", @@ -5595,14 +5567,14 @@ "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", - "tslib": "^1.8.0", + "tslib": "^1.10.0", "tsutils": "^2.29.0" }, "dependencies": { - "diff": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", - "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==", + "tslib": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", + "integrity": "sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA==", "dev": true } } @@ -5635,16 +5607,31 @@ "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", "dev": true }, + "type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true + }, "typedarray": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", "dev": true }, + "typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dev": true, + "requires": { + "is-typedarray": "^1.0.0" + } + }, "typescript": { - "version": "2.9.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.9.2.tgz", - "integrity": "sha512-Gr4p6nFNaoufRIY4NMdpQRNmgxVIGMs4Fcu/ujdYk3nAZqk7supzBE9idmvfZIlH/Cuj//dvi+019qEue9lV0w==", + "version": "3.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.8.3.tgz", + "integrity": "sha512-MYlEfn5VrLNsgudQTVJeNaQFUAI7DkhnOjdpAp4T+ku1TfQClewlbSuTVHiA+8skNBgaf02TL/kLOvig4y3G8w==", "dev": true }, "typescript-require": { @@ -5664,33 +5651,6 @@ } } }, - "uglify-js": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.7.2.tgz", - "integrity": "sha512-uhRwZcANNWVLrxLfNFEdltoPNhECUR3lc+UdJoG9CBpMcSnKyWA94tc3eAujB1GcMY5Uwq8ZMp4qWpxWYDQmaA==", - "dev": true, - "optional": true, - "requires": { - "commander": "~2.20.3", - "source-map": "~0.6.1" - }, - "dependencies": { - "commander": { - "version": "2.20.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", - "dev": true, - "optional": true - }, - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "optional": true - } - } - }, "unc-path-regex": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", @@ -5816,9 +5776,9 @@ "dev": true }, "utf8": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/utf8/-/utf8-2.1.2.tgz", - "integrity": "sha1-H6DZJw6b6FDZsFAn9jUZv0ZFfZY=" + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/utf8/-/utf8-3.0.0.tgz", + "integrity": "sha512-E8VjFIQ/TyQgp+TZfS6l8yp/xWppSAHzidGiRrqe4bK4XP9pTRyKFgGJpO3SN7zdX4DeomTrwaseCHovfpFcqQ==" }, "util": { "version": "0.10.3", @@ -5952,12 +5912,6 @@ "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=", "dev": true }, - "wordwrap": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", - "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", - "dev": true - }, "wrap-ansi": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", @@ -5975,23 +5929,21 @@ "dev": true }, "write-file-atomic": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", - "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", "dev": true, "requires": { - "graceful-fs": "^4.1.11", "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.2" + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" } }, "ws": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-5.2.0.tgz", - "integrity": "sha512-c18dMeW+PEQdDFzkhDsnBAlS4Z8KGStBQQUcQ5mf7Nf689jyGk0594L+i9RaQuf4gog6SvWLJorz2NfSaqxZ7w==", - "requires": { - "async-limiter": "~1.0.0" - } + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.2.3.tgz", + "integrity": "sha512-HTDl9G9hbkNDk98naoR/cHDws7+EyYMOdL1BmjsZXRUjf7d+MficC4B7HLUPlSiho0vg+CWKrGIt/VJBd1xunQ==" }, "xtend": { "version": "4.0.1", @@ -6005,12 +5957,6 @@ "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", "dev": true }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", - "dev": true - }, "yargs": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/yargs/-/yargs-7.1.0.tgz", @@ -6042,9 +5988,9 @@ } }, "yn": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/yn/-/yn-2.0.0.tgz", - "integrity": "sha1-5a2ryKz0CPY4X8dklWhMiOavaJo=", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", "dev": true } } diff --git a/package.json b/package.json index 653e9a7f81..8e49a2ce36 100644 --- a/package.json +++ b/package.json @@ -45,20 +45,20 @@ "@types/ws": "^3.2.0", "assert": "^1.4.1", "chai": "^4.1.2", - "coveralls": "^3.0.6", + "coveralls": "^3.0.9", "gulp": "^4.0.2", "gulp-typescript": "^5.0.1", "mocha": "^4.0.1", - "nyc": "^14.1.1", + "nyc": "^15.0.0", "secure-random": "^1.1.1", "ts-mockito": "^2.4.0", - "ts-node": "^5.0.1", - "tslint": "^5.20.1", - "typescript": "^2.9.2", + "ts-node": "^8.6.2", + "tslint": "^6.0.0", + "typescript": "^3.7.5", "typescript-require": "^0.2.10" }, "dependencies": { - "bluebird": "^3.5.5", + "bluebird": "^3.7.2", "catbuffer-typescript": "0.0.11", "crypto-js": "^3.1.9-1", "diff": "^4.0.2", @@ -69,15 +69,16 @@ "js-sha512": "^0.8.0", "long": "^4.0.0", "merkletreejs": "^0.1.7", + "minimist": "^1.2.5", "request": "^2.88.0", "request-promise-native": "^1.0.5", "ripemd160": "^2.0.2", "rxjs": "^6.5.3", "rxjs-compat": "^6.5.3", - "symbol-openapi-typescript-node-client": "0.8.5", + "symbol-openapi-typescript-node-client": "0.8.9", "tweetnacl": "^1.0.3", - "utf8": "^2.1.2", - "ws": "^5.2.0" + "utf8": "^3.0.0", + "ws": "^7.2.3" }, "peerDependencies": { "js-joda": "^1.6.2", diff --git a/src/core/format/IdGenerator.ts b/src/core/format/IdGenerator.ts index e0ab0967b3..957a6eceaf 100644 --- a/src/core/format/IdGenerator.ts +++ b/src/core/format/IdGenerator.ts @@ -15,6 +15,7 @@ */ import {sha3_256} from 'js-sha3'; import * as utilities from './Utilities'; +import { idGeneratorConst } from './Utilities'; export class IdGenerator { /** diff --git a/src/core/format/RawAddress.ts b/src/core/format/RawAddress.ts index 64daeb1858..d1245a2626 100644 --- a/src/core/format/RawAddress.ts +++ b/src/core/format/RawAddress.ts @@ -16,7 +16,7 @@ import { sha3_256 } from 'js-sha3'; import RIPEMD160 = require('ripemd160'); -import { NetworkType } from '../../model/blockchain/NetworkType'; +import { NetworkType } from '../../model/network/NetworkType'; import { Base32 } from './Base32'; import { Convert } from './Convert'; import { RawArray } from './RawArray'; diff --git a/src/core/format/Utilities.ts b/src/core/format/Utilities.ts index b1e04b2fba..4c52f72e25 100644 --- a/src/core/format/Utilities.ts +++ b/src/core/format/Utilities.ts @@ -94,7 +94,6 @@ export const tryParseUint = (str) => { export const idGeneratorConst = { namespace_base_id: [0, 0], - namespace_max_depth: 3, name_pattern: /^[a-z0-9][a-z0-9-_]*$/, }; @@ -114,9 +113,6 @@ export const extractPartName = (name, start, size) => { }; export const append = (path, id, name) => { - if (idGeneratorConst.namespace_max_depth === path.length) { - this.throwInvalidFqn('too many parts', name); - } path.push(id); }; diff --git a/src/core/utils/UnresolvedMapping.ts b/src/core/utils/UnresolvedMapping.ts index 1a8de4f376..f70f9d45c6 100644 --- a/src/core/utils/UnresolvedMapping.ts +++ b/src/core/utils/UnresolvedMapping.ts @@ -14,9 +14,9 @@ * limitations under the License. */ import { Address } from '../../model/account/Address'; -import { NetworkType } from '../../model/blockchain/NetworkType'; import { MosaicId } from '../../model/mosaic/MosaicId'; import { NamespaceId } from '../../model/namespace/NamespaceId'; +import { NetworkType } from '../../model/network/NetworkType'; import { Convert } from '../format/Convert'; import { RawAddress } from '../format/RawAddress'; diff --git a/src/infrastructure/AccountHttp.ts b/src/infrastructure/AccountHttp.ts index 7cb5edce53..514d91df72 100644 --- a/src/infrastructure/AccountHttp.ts +++ b/src/infrastructure/AccountHttp.ts @@ -49,6 +49,7 @@ export class AccountHttp extends Http implements AccountRepository { constructor(url: string) { super(url); this.accountRoutesApi = new AccountRoutesApi(url); + this.accountRoutesApi.useQuerystring = true; } /** diff --git a/src/infrastructure/BlockHttp.ts b/src/infrastructure/BlockHttp.ts index be209da207..0442305715 100644 --- a/src/infrastructure/BlockHttp.ts +++ b/src/infrastructure/BlockHttp.ts @@ -14,8 +14,7 @@ * limitations under the License. */ -import { from as observableFrom, Observable, throwError } from 'rxjs'; -import { catchError, map } from 'rxjs/operators'; +import { Observable } from 'rxjs'; import { BlockInfoDTO, BlockRoutesApi } from 'symbol-openapi-typescript-node-client'; import { PublicAccount } from '../model/account/PublicAccount'; import { BlockInfo } from '../model/blockchain/BlockInfo'; @@ -47,6 +46,7 @@ export class BlockHttp extends Http implements BlockRepository { constructor(url: string) { super(url); this.blockRoutesApi = new BlockRoutesApi(url); + this.blockRoutesApi.useQuerystring = true; } /** @@ -55,10 +55,7 @@ export class BlockHttp extends Http implements BlockRepository { * @returns Observable */ public getBlockByHeight(height: UInt64): Observable { - return observableFrom(this.blockRoutesApi.getBlockByHeight(height.toString())).pipe( - map(({body}) => this.toBlockInfo(body)), - catchError((error) => throwError(this.errorHandling(error))), - ); + return this.call(this.blockRoutesApi.getBlockByHeight(height.toString()), (body) => this.toBlockInfo(body)); } /** @@ -69,15 +66,12 @@ export class BlockHttp extends Http implements BlockRepository { */ public getBlockTransactions(height: UInt64, queryParams?: QueryParams): Observable { - return observableFrom( - this.blockRoutesApi.getBlockTransactions(height.toString(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering)) - .pipe(map(({body}) => body.map((transactionDTO) => { - return CreateTransactionFromDTO(transactionDTO); - })), - catchError((error) => throwError(this.errorHandling(error))), + return this.call(this.blockRoutesApi.getBlockTransactions(height.toString(), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering), (body) => body.map((transactionDTO) => { + return CreateTransactionFromDTO(transactionDTO); + }), ); } @@ -88,11 +82,8 @@ export class BlockHttp extends Http implements BlockRepository { * @returns Observable */ public getBlocksByHeightWithLimit(height: UInt64, limit: number): Observable { - return observableFrom( - this.blockRoutesApi.getBlocksByHeightWithLimit(height.toString(), limit)).pipe( - map(({body}) => body.map((blockDTO) => this.toBlockInfo(blockDTO))), - catchError((error) => throwError(this.errorHandling(error))), - ); + return this.call(this.blockRoutesApi.getBlocksByHeightWithLimit(height.toString(), limit), (body) => + body.map((blockDTO) => this.toBlockInfo(blockDTO))); } /** @@ -138,12 +129,10 @@ export class BlockHttp extends Http implements BlockRepository { * @return Observable */ public getMerkleTransaction(height: UInt64, hash: string): Observable { - return observableFrom( - this.blockRoutesApi.getMerkleTransaction(height.toString(), hash)).pipe( - map(({body}) => new MerkleProofInfo( - body.merklePath!.map((payload) => new MerklePathItem(payload.position, payload.hash)), - )), - catchError((error) => throwError(this.errorHandling(error))), - ); + return this.call( + this.blockRoutesApi.getMerkleTransaction(height.toString(), hash), (body) => new MerkleProofInfo( + body.merklePath!.map((payload) => new MerklePathItem(payload.position, payload.hash)), + )); } + } diff --git a/src/infrastructure/ChainHttp.ts b/src/infrastructure/ChainHttp.ts index afbbffcc1b..2613adba75 100644 --- a/src/infrastructure/ChainHttp.ts +++ b/src/infrastructure/ChainHttp.ts @@ -14,8 +14,7 @@ * limitations under the License. */ -import { from as observableFrom, Observable, throwError } from 'rxjs'; -import { catchError, map } from 'rxjs/operators'; +import { Observable } from 'rxjs'; import { ChainRoutesApi } from 'symbol-openapi-typescript-node-client'; import { BlockchainScore } from '../model/blockchain/BlockchainScore'; import { UInt64 } from '../model/UInt64'; @@ -41,6 +40,7 @@ export class ChainHttp extends Http implements ChainRepository { constructor(url: string) { super(url); this.chainRoutesApi = new ChainRoutesApi(url); + this.chainRoutesApi.useQuerystring = true; } /** @@ -48,10 +48,7 @@ export class ChainHttp extends Http implements ChainRepository { * @returns Observable */ public getBlockchainHeight(): Observable { - return observableFrom(this.chainRoutesApi.getChainHeight()).pipe( - map(({body}) => UInt64.fromNumericString(body.height)), - catchError((error) => throwError(this.errorHandling(error))), - ); + return this.call(this.chainRoutesApi.getChainHeight(), (body) => UInt64.fromNumericString(body.height)); } /** @@ -59,12 +56,10 @@ export class ChainHttp extends Http implements ChainRepository { * @returns Observable */ public getChainScore(): Observable { - return observableFrom(this.chainRoutesApi.getChainScore()).pipe( - map(({body}) => new BlockchainScore( - UInt64.fromNumericString(body.scoreLow), - UInt64.fromNumericString(body.scoreHigh), - )), - catchError((error) => throwError(this.errorHandling(error))), + return this.call(this.chainRoutesApi.getChainScore(), (body) => new BlockchainScore( + UInt64.fromNumericString(body.scoreLow), + UInt64.fromNumericString(body.scoreHigh), + ), ); } } diff --git a/src/infrastructure/Http.ts b/src/infrastructure/Http.ts index 238609b4c3..cfb8a86ee1 100644 --- a/src/infrastructure/Http.ts +++ b/src/infrastructure/Http.ts @@ -19,7 +19,7 @@ import * as http from 'http'; import { from as observableFrom, Observable, of as observableOf, throwError } from 'rxjs'; import { catchError, map, shareReplay } from 'rxjs/operators'; import { NodeRoutesApi } from 'symbol-openapi-typescript-node-client'; -import { NetworkType } from '../model/blockchain/NetworkType'; +import { NetworkType } from '../model/network/NetworkType'; import { QueryParams } from './QueryParams'; import { TransactionFilter } from './TransactionFilter'; diff --git a/src/infrastructure/MetadataHttp.ts b/src/infrastructure/MetadataHttp.ts index f3b646f0f8..23c1aa0b67 100644 --- a/src/infrastructure/MetadataHttp.ts +++ b/src/infrastructure/MetadataHttp.ts @@ -14,8 +14,7 @@ * limitations under the License. */ -import { from as observableFrom, Observable, throwError } from 'rxjs'; -import { catchError, map } from 'rxjs/operators'; +import { Observable } from 'rxjs'; import { MetadataDTO, MetadataRoutesApi } from 'symbol-openapi-typescript-node-client'; import { Convert } from '../core/format/Convert'; import { Address } from '../model/account/Address'; @@ -43,12 +42,12 @@ export class MetadataHttp extends Http implements MetadataRepository { /** * Constructor - * @param url - * @param networkType + * @param url the url. */ constructor(url: string) { super(url); this.metadataRoutesApi = new MetadataRoutesApi(url); + this.metadataRoutesApi.useQuerystring = true; } /** @@ -58,15 +57,12 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ public getAccountMetadata(address: Address, queryParams?: QueryParams): Observable { - return observableFrom( + return this.call( this.metadataRoutesApi.getAccountMetadata(address.plain(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering)).pipe( - map(({body}) => body.metadataEntries.map((metadataEntry) => { - return this.buildMetadata(metadataEntry); - })), - catchError((error) => throwError(this.errorHandling(error))), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering), + (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)) ); } @@ -77,12 +73,9 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getAccountMetadataByKey(address: Address, key: string): Observable { - return observableFrom( - this.metadataRoutesApi.getAccountMetadataByKey(address.plain(), key)).pipe( - map(({body}) => body.metadataEntries.map((metadataEntry) => { - return this.buildMetadata(metadataEntry); - })), - catchError((error) => throwError(this.errorHandling(error))), + return this.call( + this.metadataRoutesApi.getAccountMetadataByKey(address.plain(), key), + (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)) ); } @@ -94,10 +87,9 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getAccountMetadataByKeyAndSender(address: Address, key: string, publicKey: string): Observable { - return observableFrom( - this.metadataRoutesApi.getAccountMetadataByKeyAndSender(address.plain(), key, publicKey)).pipe( - map(({body}) => this.buildMetadata(body)), - catchError((error) => throwError(this.errorHandling(error))), + return this.call( + this.metadataRoutesApi.getAccountMetadataByKeyAndSender(address.plain(), key, publicKey), + (body) => this.buildMetadata(body) ); } @@ -108,15 +100,12 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getMosaicMetadata(mosaicId: MosaicId, queryParams?: QueryParams): Observable { - return observableFrom( + return this.call( this.metadataRoutesApi.getMosaicMetadata(mosaicId.toHex(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering)).pipe( - map(({body}) => body.metadataEntries.map((metadataEntry) => { - return this.buildMetadata(metadataEntry); - })), - catchError((error) => throwError(this.errorHandling(error))), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering), + (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)) ); } @@ -127,12 +116,9 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getMosaicMetadataByKey(mosaicId: MosaicId, key: string): Observable { - return observableFrom( - this.metadataRoutesApi.getMosaicMetadataByKey(mosaicId.toHex(), key)).pipe( - map(({body}) => body.metadataEntries.map((metadataEntry) => { - return this.buildMetadata(metadataEntry); - })), - catchError((error) => throwError(this.errorHandling(error))), + return this.call( + this.metadataRoutesApi.getMosaicMetadataByKey(mosaicId.toHex(), key), + (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)) ); } @@ -144,10 +130,8 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getMosaicMetadataByKeyAndSender(mosaicId: MosaicId, key: string, publicKey: string): Observable { - return observableFrom( - this.metadataRoutesApi.getMosaicMetadataByKeyAndSender(mosaicId.toHex(), key, publicKey)).pipe( - map(({body}) => this.buildMetadata(body)), - catchError((error) => throwError(this.errorHandling(error))), + return this.call( + this.metadataRoutesApi.getMosaicMetadataByKeyAndSender(mosaicId.toHex(), key, publicKey), this.buildMetadata ); } @@ -158,15 +142,11 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ public getNamespaceMetadata(namespaceId: NamespaceId, queryParams?: QueryParams): Observable { - return observableFrom( + return this.call( this.metadataRoutesApi.getNamespaceMetadata(namespaceId.toHex(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering)).pipe( - map(({body}) => body.metadataEntries.map((metadataEntry) => { - return this.buildMetadata(metadataEntry); - })), - catchError((error) => throwError(this.errorHandling(error))), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering), body => body.metadataEntries.map(this.buildMetadata) ); } @@ -177,12 +157,9 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ public getNamespaceMetadataByKey(namespaceId: NamespaceId, key: string): Observable { - return observableFrom( - this.metadataRoutesApi.getNamespaceMetadataByKey(namespaceId.toHex(), key)).pipe( - map(({body}) => body.metadataEntries.map((metadataEntry) => { - return this.buildMetadata(metadataEntry); - })), - catchError((error) => throwError(this.errorHandling(error))), + return this.call( + this.metadataRoutesApi.getNamespaceMetadataByKey(namespaceId.toHex(), key), + (body) => body.metadataEntries.map(this.buildMetadata) ); } @@ -194,18 +171,14 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ public getNamespaceMetadataByKeyAndSender(namespaceId: NamespaceId, key: string, publicKey: string): Observable { - return observableFrom( - this.metadataRoutesApi.getNamespaceMetadataByKeyAndSender(namespaceId.toHex(), key, publicKey)).pipe( - map(({body}) => this.buildMetadata(body)), - catchError((error) => throwError(this.errorHandling(error))), - ); + return this.call( + this.metadataRoutesApi.getNamespaceMetadataByKeyAndSender(namespaceId.toHex(), key, publicKey), this.buildMetadata); } /** - * Returns the mosaic metadata given a mosaic id. - * @param namespaceId - Namespace identifier. - * @param queryParams - Optional query parameters - * @returns Observable + * It maps MetadataDTO into a Metadata + * @param metadata - the dto + * @returns the model Metadata. */ private buildMetadata(metadata: MetadataDTO): Metadata { const metadataEntry = metadata.metadataEntry; diff --git a/src/infrastructure/MosaicHttp.ts b/src/infrastructure/MosaicHttp.ts index 2fc2490ebb..42491a23f1 100644 --- a/src/infrastructure/MosaicHttp.ts +++ b/src/infrastructure/MosaicHttp.ts @@ -14,15 +14,15 @@ * limitations under the License. */ -import { from as observableFrom, Observable, throwError } from 'rxjs'; -import { catchError, map, mergeMap } from 'rxjs/operators'; -import { MosaicRoutesApi } from 'symbol-openapi-typescript-node-client'; +import { Observable, throwError } from 'rxjs'; +import { catchError, mergeMap } from 'rxjs/operators'; +import { MosaicRoutesApi, MosaicIds, AccountIds, MosaicInfoDTO, MosaicDTO } from 'symbol-openapi-typescript-node-client'; import { Address } from '../model/account/Address'; import { PublicAccount } from '../model/account/PublicAccount'; -import { NetworkType } from '../model/blockchain/NetworkType'; import { MosaicFlags } from '../model/mosaic/MosaicFlags'; import { MosaicId } from '../model/mosaic/MosaicId'; import { MosaicInfo } from '../model/mosaic/MosaicInfo'; +import { NetworkType } from '../model/network/NetworkType'; import { UInt64 } from '../model/UInt64'; import { Http } from './Http'; import { MosaicRepository } from './MosaicRepository'; @@ -53,6 +53,7 @@ export class MosaicHttp extends Http implements MosaicRepository { super(url); this.mosaicRoutesApi = new MosaicRoutesApi(url); this.networkTypeObservable = this.createNetworkTypeObservable(networkType); + this.mosaicRoutesApi.useQuerystring = true; } /** @@ -62,21 +63,9 @@ export class MosaicHttp extends Http implements MosaicRepository { */ public getMosaic(mosaicId: MosaicId): Observable { return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.mosaicRoutesApi.getMosaic(mosaicId.toHex())).pipe( - map(({body}) => new MosaicInfo( - new MosaicId(body.mosaic.id), - UInt64.fromNumericString(body.mosaic.supply), - UInt64.fromNumericString(body.mosaic.startHeight), - PublicAccount.createFromPublicKey(body.mosaic.ownerPublicKey, networkType), - body.mosaic.revision, - new MosaicFlags(body.mosaic.flags), - body.mosaic.divisibility, - UInt64.fromNumericString(body.mosaic.duration), - )), - catchError((error) => throwError(this.errorHandling(error))), - )), - ); + mergeMap((networkType) => + this.call(this.mosaicRoutesApi.getMosaic(mosaicId.toHex()), (body) => this.toMosaicInfo(body, networkType))), + ); } /** @@ -85,27 +74,11 @@ export class MosaicHttp extends Http implements MosaicRepository { * @returns Observable */ public getMosaics(mosaicIds: MosaicId[]): Observable { - const mosaicIdsBody = { - mosaicIds: mosaicIds.map((id) => id.toHex()), - }; + const ids = new MosaicIds(); + ids.mosaicIds = mosaicIds.map((id) => id.toHex()); return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.mosaicRoutesApi.getMosaics(mosaicIdsBody)).pipe( - map(({body}) => body.map((mosaicInfoDTO) => { - return new MosaicInfo( - new MosaicId(mosaicInfoDTO.mosaic.id), - UInt64.fromNumericString(mosaicInfoDTO.mosaic.supply), - UInt64.fromNumericString(mosaicInfoDTO.mosaic.startHeight), - PublicAccount.createFromPublicKey(mosaicInfoDTO.mosaic.ownerPublicKey, networkType), - mosaicInfoDTO.mosaic.revision, - new MosaicFlags(mosaicInfoDTO.mosaic.flags), - mosaicInfoDTO.mosaic.divisibility, - UInt64.fromNumericString(mosaicInfoDTO.mosaic.duration), - ); - })), - catchError((error) => throwError(this.errorHandling(error))), - ), - ), + mergeMap((networkType) => + this.call(this.mosaicRoutesApi.getMosaics(ids), (body) => body.map((b) => this.toMosaicInfo(b, networkType)))), ); } @@ -116,20 +89,9 @@ export class MosaicHttp extends Http implements MosaicRepository { */ public getMosaicsFromAccount(address: Address): Observable { return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.mosaicRoutesApi.getMosaicsFromAccount(address.plain())).pipe( - map(({body}) => body.mosaics.map((mosaicInfo) => - new MosaicInfo( - new MosaicId(mosaicInfo.id), - UInt64.fromNumericString(mosaicInfo.supply), - UInt64.fromNumericString(mosaicInfo.startHeight), - PublicAccount.createFromPublicKey(mosaicInfo.ownerPublicKey, networkType), - mosaicInfo.revision, - new MosaicFlags(mosaicInfo.flags), - mosaicInfo.divisibility, - UInt64.fromNumericString(mosaicInfo.duration)))), - catchError((error) => throwError(this.errorHandling(error))), - )), + mergeMap((networkType) => + this.call(this.mosaicRoutesApi.getMosaicsFromAccount(address.plain()), + (body) => body.mosaics.map((b) => this.toMosaicInfoFromMosaicDto(b, networkType)))), ); } @@ -139,27 +101,50 @@ export class MosaicHttp extends Http implements MosaicRepository { * @param addresses Array of addresses */ public getMosaicsFromAccounts(addresses: Address[]): Observable { - const accountIdsBody = { - addresses: addresses.map((address) => address.plain()), - }; + const accountIds = new AccountIds(); + accountIds.addresses = addresses.map((address) => address.plain()); return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.mosaicRoutesApi.getMosaicsFromAccounts(accountIdsBody)).pipe( - map(({body}) => body.mosaics.map((mosaicInfoDTO) => { - return new MosaicInfo( - new MosaicId(mosaicInfoDTO.id), - UInt64.fromNumericString(mosaicInfoDTO.supply), - UInt64.fromNumericString(mosaicInfoDTO.startHeight), - PublicAccount.createFromPublicKey(mosaicInfoDTO.ownerPublicKey, networkType), - mosaicInfoDTO.revision, - new MosaicFlags(mosaicInfoDTO.flags), - mosaicInfoDTO.divisibility, - UInt64.fromNumericString(mosaicInfoDTO.duration), - ); - })), - catchError((error) => throwError(this.errorHandling(error))), - ), - ), + mergeMap((networkType) => + this.call(this.mosaicRoutesApi.getMosaicsFromAccounts(accountIds), + (body) => body.mosaics.map((b) => this.toMosaicInfoFromMosaicDto(b, networkType)))), + ); + } + + /** + * Maps MosaicInfoDTO to MosaicInfo + * + * @param mosaicInfo the dto object. + * @returns the model object + */ + private toMosaicInfo(mosaicInfo: MosaicInfoDTO, networkType: NetworkType): MosaicInfo { + return new MosaicInfo( + new MosaicId(mosaicInfo.mosaic.id), + UInt64.fromNumericString(mosaicInfo.mosaic.supply), + UInt64.fromNumericString(mosaicInfo.mosaic.startHeight), + PublicAccount.createFromPublicKey(mosaicInfo.mosaic.ownerPublicKey, networkType), + mosaicInfo.mosaic.revision, + new MosaicFlags(mosaicInfo.mosaic.flags), + mosaicInfo.mosaic.divisibility, + UInt64.fromNumericString(mosaicInfo.mosaic.duration), + ); + } + + /** + * Maps MosaicDTO to MosaicInfo + * + * @param mosaicInfo the dto object. + * @returns the model object + */ + private toMosaicInfoFromMosaicDto(mosaicInfo: MosaicDTO, networkType: NetworkType): MosaicInfo { + return new MosaicInfo( + new MosaicId(mosaicInfo.id), + UInt64.fromNumericString(mosaicInfo.supply), + UInt64.fromNumericString(mosaicInfo.startHeight), + PublicAccount.createFromPublicKey(mosaicInfo.ownerPublicKey, networkType), + mosaicInfo.revision, + new MosaicFlags(mosaicInfo.flags), + mosaicInfo.divisibility, + UInt64.fromNumericString(mosaicInfo.duration), ); } } diff --git a/src/infrastructure/MultisigHttp.ts b/src/infrastructure/MultisigHttp.ts index 9017022ed6..fa056718ae 100644 --- a/src/infrastructure/MultisigHttp.ts +++ b/src/infrastructure/MultisigHttp.ts @@ -21,7 +21,7 @@ import { Address } from '../model/account/Address'; import { MultisigAccountGraphInfo } from '../model/account/MultisigAccountGraphInfo'; import { MultisigAccountInfo } from '../model/account/MultisigAccountInfo'; import { PublicAccount } from '../model/account/PublicAccount'; -import { NetworkType } from '../model/blockchain/NetworkType'; +import { NetworkType } from '../model/network/NetworkType'; import { Http } from './Http'; import { MultisigRepository } from './MultisigRepository'; @@ -50,6 +50,7 @@ export class MultisigHttp extends Http implements MultisigRepository { super(url); this.multisigRoutesApi = new MultisigRoutesApi(url); this.networkTypeObservable = this.createNetworkTypeObservable(networkType); + this.multisigRoutesApi.useQuerystring = true; } /** diff --git a/src/infrastructure/NamespaceHttp.ts b/src/infrastructure/NamespaceHttp.ts index 4333724a24..152a97ef6c 100644 --- a/src/infrastructure/NamespaceHttp.ts +++ b/src/infrastructure/NamespaceHttp.ts @@ -20,7 +20,6 @@ import { Convert as convert, RawAddress as AddressLibrary } from '../core/format import { AccountNames } from '../model/account/AccountNames'; import { Address } from '../model/account/Address'; import { PublicAccount } from '../model/account/PublicAccount'; -import { NetworkType } from '../model/blockchain/NetworkType'; import { MosaicId } from '../model/mosaic/MosaicId'; import { MosaicNames } from '../model/mosaic/MosaicNames'; import { AddressAlias } from '../model/namespace/AddressAlias'; @@ -31,6 +30,7 @@ import { MosaicAlias } from '../model/namespace/MosaicAlias'; import { NamespaceId } from '../model/namespace/NamespaceId'; import { NamespaceInfo } from '../model/namespace/NamespaceInfo'; import { NamespaceName } from '../model/namespace/NamespaceName'; +import { NetworkType } from '../model/network/NetworkType'; import { UInt64 } from '../model/UInt64'; import { Http } from './Http'; import { NamespaceRepository } from './NamespaceRepository'; @@ -62,6 +62,7 @@ export class NamespaceHttp extends Http implements NamespaceRepository { super(url); this.namespaceRoutesApi = new NamespaceRoutesApi(url); this.networkTypeObservable = this.createNetworkTypeObservable(networkType); + this.namespaceRoutesApi.useQuerystring = true; } /** diff --git a/src/infrastructure/NetworkHttp.ts b/src/infrastructure/NetworkHttp.ts index f4e6758182..fc89966d07 100644 --- a/src/infrastructure/NetworkHttp.ts +++ b/src/infrastructure/NetworkHttp.ts @@ -16,14 +16,31 @@ import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; -import { NetworkRoutesApi } from 'symbol-openapi-typescript-node-client'; -import { NetworkFees } from '../model/blockchain/NetworkFees'; -import { NetworkName } from '../model/blockchain/NetworkName'; -import { NetworkType } from '../model/blockchain/NetworkType'; +import { NetworkConfigurationDTO, NetworkRoutesApi } from 'symbol-openapi-typescript-node-client'; +import { AccountLinkNetworkProperties } from '../model/network/AccountLinkNetworkProperties'; +import { AccountRestrictionNetworkProperties } from '../model/network/AccountRestrictionNetworkProperties'; +import { AggregateNetworkProperties } from '../model/network/AggregateNetworkProperties'; +import { ChainProperties } from '../model/network/ChainProperties'; +import { HashLockNetworkProperties } from '../model/network/HashLockNetworkProperties'; +import { MetadataNetworkProperties } from '../model/network/MetadataNetworkProperties'; +import { MosaicNetworkProperties } from '../model/network/MosaicNetworkProperties'; +import { MosaicRestrictionNetworkProperties } from '../model/network/MosaicRestrictionNetworkProperties'; +import { MultisigNetworkProperties } from '../model/network/MultisigNetworkProperties'; +import { NamespaceNetworkProperties } from '../model/network/NamespaceNetworkProperties'; +import { NetworkConfiguration } from '../model/network/NetworkConfiguration'; +import { NetworkName } from '../model/network/NetworkName'; +import { NetworkProperties } from '../model/network/NetworkProperties'; +import { NetworkType } from '../model/network/NetworkType'; +import { PluginProperties } from '../model/network/PluginProperties'; +import { RentalFees } from '../model/network/RentalFees'; +import { SecretLockNetworkProperties } from '../model/network/SecretLockNetworkProperties'; +import { TransactionFees } from '../model/network/TransactionFees'; +import { TransferNetworkProperties } from '../model/network/TransferNetworkProperties'; import { NodeInfo } from '../model/node/NodeInfo'; import { Http } from './Http'; import { NetworkRepository } from './NetworkRepository'; import { NodeHttp } from './NodeHttp'; +import { UInt64 } from '../model/UInt64'; /** * Network http repository. @@ -46,6 +63,7 @@ export class NetworkHttp extends Http implements NetworkRepository { super(url); this.nodeHttp = new NodeHttp(url); this.networkRoutesApi = new NetworkRoutesApi(url); + this.networkRoutesApi.useQuerystring = true; } @@ -67,14 +85,81 @@ export class NetworkHttp extends Http implements NetworkRepository { return this.call(this.networkRoutesApi.getNetworkType(), (body) => new NetworkName(body.name, body.description)); } + /** + * Returns the content from a catapult-server network configuration file (resources/config-network.properties). + * To enable this feature, the REST setting \"network.propertiesFilePath\" must define where the file is located. + * This is adjustable via the configuration file (rest/resources/rest.json) per REST instance. + * @summary Get the network properties + */ + public getNetworkProperties(): Observable { + return this.call(this.networkRoutesApi.getNetworkProperties(), (body) => + this.mapNetworkConfigurationDto(body), + ); + } + + /** + * Returns the estimated effective rental fees for namespaces and mosaics. This endpoint is only available + * if the REST instance has access to catapult-server ``resources/config-network.properties`` file. + * To activate this feature, add the setting \"network.propertiesFilePath\" in the configuration file (rest/resources/rest.json). + * @summary Get rental fees information + */ + public getRentalFees(): Observable { + return this.call(this.networkRoutesApi.getRentalFees(), (body) => + new RentalFees(UInt64.fromNumericString(body.effectiveRootNamespaceRentalFeePerBlock), + UInt64.fromNumericString(body.effectiveChildNamespaceRentalFee), + UInt64.fromNumericString(body.effectiveMosaicRentalFee))); + } + /** * Returns information about the average, median, highest and lower fee multiplier over the last * \"numBlocksTransactionFeeStats\". The setting \"numBlocksTransactionFeeStats\" is adjustable * via a configuration file (rest/resources/rest.json) per REST instance. * @summary Get transaction fees information */ - public getNetworkFees(): Observable { - return this.call(this.networkRoutesApi.getNetworkFees(), (body) => - new NetworkFees(body.averageFeeMultiplier, body.medianFeeMultiplier, body.highestFeeMultiplier, body.lowestFeeMultiplier)); + public getTransactionFees(): Observable { + return this.call(this.networkRoutesApi.getTransactionFees(), (body) => + new TransactionFees(body.averageFeeMultiplier, body.medianFeeMultiplier, body.highestFeeMultiplier, body.lowestFeeMultiplier)); + } + + /** + * Map dto to sdk models + * @param dto dto object returned from rest + */ + private mapNetworkConfigurationDto(dto: NetworkConfigurationDTO): NetworkConfiguration { + return new NetworkConfiguration( + new NetworkProperties(dto.network.identifier, dto.network.nodeEqualityStrategy, + dto.network.publicKey, dto.network.generationHash, dto.network.epochAdjustment), + new ChainProperties(dto.chain.enableVerifiableState, dto.chain.enableVerifiableReceipts, + dto.chain.currencyMosaicId, dto.chain.harvestingMosaicId, dto.chain.blockGenerationTargetTime, + dto.chain.blockTimeSmoothingFactor, dto.chain.importanceGrouping, dto.chain.importanceActivityPercentage, + dto.chain.maxRollbackBlocks, dto.chain.maxDifficultyBlocks, dto.chain.defaultDynamicFeeMultiplier, + dto.chain.maxTransactionLifetime, dto.chain.maxBlockFutureTime, dto.chain.initialCurrencyAtomicUnits, + dto.chain.maxMosaicAtomicUnits, dto.chain.totalChainImportance, dto.chain.minHarvesterBalance, + dto.chain.maxHarvesterBalance, dto.chain.harvestBeneficiaryPercentage, dto.chain.blockPruneInterval, + dto.chain.maxTransactionsPerBlock), + new PluginProperties( + new AccountLinkNetworkProperties(dto.plugins.accountlink?.dummy), + new AggregateNetworkProperties(dto.plugins.aggregate?.maxTransactionsPerAggregate, + dto.plugins.aggregate?.maxCosignaturesPerAggregate, dto.plugins.aggregate?.enableStrictCosignatureCheck, + dto.plugins.aggregate?.enableBondedAggregateSupport, dto.plugins.aggregate?.maxBondedTransactionLifetime), + new HashLockNetworkProperties(dto.plugins.lockhash?.lockedFundsPerAggregate, dto.plugins.lockhash?.maxHashLockDuration), + new SecretLockNetworkProperties(dto.plugins.locksecret?.maxSecretLockDuration, dto.plugins.locksecret?.minProofSize, + dto.plugins.locksecret?.maxProofSize), + new MetadataNetworkProperties(dto.plugins.metadata?.maxValueSize), + new MosaicNetworkProperties(dto.plugins.mosaic?.maxMosaicsPerAccount, dto.plugins.mosaic?.maxMosaicDuration, + dto.plugins.mosaic?.maxMosaicDivisibility, dto.plugins.mosaic?.mosaicRentalFeeSinkPublicKey, + dto.plugins.mosaic?.mosaicRentalFee), + new MultisigNetworkProperties(dto.plugins.multisig?.maxMultisigDepth, dto.plugins.multisig?.maxCosignatoriesPerAccount, + dto.plugins.multisig?.maxCosignedAccountsPerAccount), + new NamespaceNetworkProperties(dto.plugins.namespace?.maxNameSize, dto.plugins.namespace?.maxChildNamespaces, + dto.plugins.namespace?.maxNamespaceDepth, dto.plugins.namespace?.minNamespaceDuration, + dto.plugins.namespace?.maxNamespaceDuration, dto.plugins.namespace?.namespaceGracePeriodDuration, + dto.plugins.namespace?.reservedRootNamespaceNames, dto.plugins.namespace?.namespaceRentalFeeSinkPublicKey, + dto.plugins.namespace?.rootNamespaceRentalFeePerBlock, dto.plugins.namespace?.childNamespaceRentalFee), + new AccountRestrictionNetworkProperties(dto.plugins.restrictionaccount?.maxAccountRestrictionValues), + new MosaicRestrictionNetworkProperties(dto.plugins.restrictionmosaic?.maxMosaicRestrictionValues), + new TransferNetworkProperties(dto.plugins.transfer?.maxMessageSize), + ), + ); } } diff --git a/src/infrastructure/NetworkRepository.ts b/src/infrastructure/NetworkRepository.ts index 0c4f661f16..60c3020ff2 100644 --- a/src/infrastructure/NetworkRepository.ts +++ b/src/infrastructure/NetworkRepository.ts @@ -15,9 +15,11 @@ */ import {Observable} from 'rxjs'; -import { NetworkFees } from '../model/blockchain/NetworkFees'; -import { NetworkName } from '../model/blockchain/NetworkName'; -import {NetworkType} from '../model/blockchain/NetworkType'; +import { NetworkConfiguration } from '../model/network/NetworkConfiguration'; +import { NetworkName } from '../model/network/NetworkName'; +import {NetworkType} from '../model/network/NetworkType'; +import { RentalFees } from '../model/network/RentalFees'; +import { TransactionFees } from '../model/network/TransactionFees'; /** * Network interface repository. @@ -26,6 +28,21 @@ import {NetworkType} from '../model/blockchain/NetworkType'; */ export interface NetworkRepository { + /** + * Get current network type name and description + * + * @return current network type name and description + */ + getNetworkName(): Observable; + + /** + * Returns the content from a catapult-server network configuration file (resources/config-network.properties). + * To enable this feature, the REST setting \"network.propertiesFilePath\" must define where the file is located. + * This is adjustable via the configuration file (rest/resources/rest.json) per REST instance. + * @summary Get the network properties + */ + getNetworkProperties(): Observable; + /** * Get current network type. * @return network type enum. @@ -33,16 +50,17 @@ export interface NetworkRepository { getNetworkType(): Observable; /** - * Get current network type name and description - * - * @return current network type name and description + * Returns the estimated effective rental fees for namespaces and mosaics. This endpoint is only available + * if the REST instance has access to catapult-server ``resources/config-network.properties`` file. + * To activate this feature, add the setting \"network.propertiesFilePath\" in the configuration file (rest/resources/rest.json). + * @summary Get rental fees information */ - getNetworkName(): Observable; + getRentalFees(): Observable; /** - * Returns information about the average, median, highest and lower fee multiplier over the last "numBlocksTransactionFeeStats". - * @return the NetworkFees + * Returns the average, median, highest and lower fee multiplier over the last \"numBlocksTransactionFeeStats\". + * The setting \"numBlocksTransactionFeeStats\" is adjustable via the configuration file (rest/resources/rest.json) per REST instance. + * @summary Get transaction fees information */ - getNetworkFees(): Observable ; - + getTransactionFees(): Observable; } diff --git a/src/infrastructure/NodeHttp.ts b/src/infrastructure/NodeHttp.ts index ead8c00555..db30197731 100644 --- a/src/infrastructure/NodeHttp.ts +++ b/src/infrastructure/NodeHttp.ts @@ -44,6 +44,7 @@ export class NodeHttp extends Http implements NodeRepository { constructor(url: string) { super(url); this.nodeRoutesApi = new NodeRoutesApi(url); + this.nodeRoutesApi.useQuerystring = true; } diff --git a/src/infrastructure/ReceiptHttp.ts b/src/infrastructure/ReceiptHttp.ts index bd5ceaecc7..bfd20782d7 100644 --- a/src/infrastructure/ReceiptHttp.ts +++ b/src/infrastructure/ReceiptHttp.ts @@ -19,7 +19,7 @@ import { catchError, map, mergeMap } from 'rxjs/operators'; import { ReceiptRoutesApi } from 'symbol-openapi-typescript-node-client'; import { MerklePathItem } from '../model/blockchain/MerklePathItem'; import { MerkleProofInfo } from '../model/blockchain/MerkleProofInfo'; -import { NetworkType } from '../model/blockchain/NetworkType'; +import { NetworkType } from '../model/network/NetworkType'; import { Statement } from '../model/receipt/Statement'; import { UInt64 } from '../model/UInt64'; import { Http } from './Http'; @@ -53,6 +53,7 @@ export class ReceiptHttp extends Http implements ReceiptRepository { super(url); this.receiptRoutesApi = new ReceiptRoutesApi(url); this.networkTypeObservable = this.createNetworkTypeObservable(networkType); + this.receiptRoutesApi.useQuerystring = true; } /** diff --git a/src/infrastructure/RepositoryFactory.ts b/src/infrastructure/RepositoryFactory.ts index 51c294eb85..877b5265d6 100644 --- a/src/infrastructure/RepositoryFactory.ts +++ b/src/infrastructure/RepositoryFactory.ts @@ -15,7 +15,7 @@ */ import { Observable } from 'rxjs'; -import { NetworkType } from '../model/blockchain/NetworkType'; +import { NetworkType } from '../model/network/NetworkType'; import { AccountRepository } from './AccountRepository'; import { BlockRepository } from './BlockRepository'; import { ChainRepository } from './ChainRepository'; diff --git a/src/infrastructure/RepositoryFactoryHttp.ts b/src/infrastructure/RepositoryFactoryHttp.ts index 30e91b2f83..4d691e5ff0 100644 --- a/src/infrastructure/RepositoryFactoryHttp.ts +++ b/src/infrastructure/RepositoryFactoryHttp.ts @@ -16,7 +16,7 @@ import { Observable, of as observableOf } from 'rxjs'; import { map, share, shareReplay } from 'rxjs/operators'; -import { NetworkType } from '../model/blockchain/NetworkType'; +import { NetworkType } from '../model/network/NetworkType'; import { UInt64 } from '../model/UInt64'; import { AccountHttp } from './AccountHttp'; import { AccountRepository } from './AccountRepository'; diff --git a/src/infrastructure/RestrictionAccountHttp.ts b/src/infrastructure/RestrictionAccountHttp.ts index 168f27f41d..f5918d3e1a 100644 --- a/src/infrastructure/RestrictionAccountHttp.ts +++ b/src/infrastructure/RestrictionAccountHttp.ts @@ -41,6 +41,7 @@ export class RestrictionAccountHttp extends Http implements RestrictionAccountRe constructor(url: string) { super(url); this.restrictionAccountRoutesApi = new RestrictionAccountRoutesApi(url); + this.restrictionAccountRoutesApi.useQuerystring = true; } /** diff --git a/src/infrastructure/RestrictionMosaicHttp.ts b/src/infrastructure/RestrictionMosaicHttp.ts index 7138c3322c..1758f0dfb2 100644 --- a/src/infrastructure/RestrictionMosaicHttp.ts +++ b/src/infrastructure/RestrictionMosaicHttp.ts @@ -48,6 +48,7 @@ export class RestrictionMosaicHttp extends Http implements RestrictionMosaicRepo constructor(url: string) { super(url); this.restrictionMosaicRoutesApi = new RestrictionMosaicRoutesApi(url); + this.restrictionMosaicRoutesApi.useQuerystring = true; } diff --git a/src/infrastructure/TransactionHttp.ts b/src/infrastructure/TransactionHttp.ts index 22dd13e60e..ac8ee7c0f6 100644 --- a/src/infrastructure/TransactionHttp.ts +++ b/src/infrastructure/TransactionHttp.ts @@ -57,6 +57,8 @@ export class TransactionHttp extends Http implements TransactionRepository { super(url); this.transactionRoutesApi = new TransactionRoutesApi(url); this.blockRoutesApi = new BlockRoutesApi(url); + this.transactionRoutesApi.useQuerystring = true; + this.blockRoutesApi.useQuerystring = true; } /** diff --git a/src/model/account/Account.ts b/src/model/account/Account.ts index 80acb4472c..b72eb53915 100644 --- a/src/model/account/Account.ts +++ b/src/model/account/Account.ts @@ -17,9 +17,9 @@ import {Crypto, KeyPair} from '../../core/crypto'; import {SHA3Hasher} from '../../core/crypto/SHA3Hasher'; import {Convert, RawAddress} from '../../core/format'; -import {NetworkType} from '../blockchain/NetworkType'; import {EncryptedMessage} from '../message/EncryptedMessage'; import {PlainMessage} from '../message/PlainMessage'; +import {NetworkType} from '../network/NetworkType'; import {AggregateTransaction} from '../transaction/AggregateTransaction'; import {CosignatureSignedTransaction} from '../transaction/CosignatureSignedTransaction'; import {CosignatureTransaction} from '../transaction/CosignatureTransaction'; diff --git a/src/model/account/Address.ts b/src/model/account/Address.ts index ca7ff14fc3..fb2b161991 100644 --- a/src/model/account/Address.ts +++ b/src/model/account/Address.ts @@ -14,7 +14,7 @@ * limitations under the License. */ import { Convert, RawAddress } from '../../core/format'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; /** * The address structure describes an address with its network diff --git a/src/model/account/PublicAccount.ts b/src/model/account/PublicAccount.ts index 257af759b7..1117a95a23 100644 --- a/src/model/account/PublicAccount.ts +++ b/src/model/account/PublicAccount.ts @@ -16,7 +16,7 @@ import { KeyPair } from '../../core/crypto'; import { Convert } from '../../core/format'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { Address } from './Address'; const Hash512 = 64; diff --git a/src/model/blockchain/BlockInfo.ts b/src/model/blockchain/BlockInfo.ts index 67dc6c3e58..c9a4b1d91a 100644 --- a/src/model/blockchain/BlockInfo.ts +++ b/src/model/blockchain/BlockInfo.ts @@ -15,8 +15,8 @@ */ import {PublicAccount} from '../account/PublicAccount'; +import {NetworkType} from '../network/NetworkType'; import {UInt64} from '../UInt64'; -import {NetworkType} from './NetworkType'; /** * The block info structure describes basic information of a block. diff --git a/src/model/message/EncryptedMessage.ts b/src/model/message/EncryptedMessage.ts index c4aba84240..8133f87f5e 100644 --- a/src/model/message/EncryptedMessage.ts +++ b/src/model/message/EncryptedMessage.ts @@ -16,7 +16,7 @@ import {Crypto, SHA3Hasher} from '../../core/crypto'; import {PublicAccount} from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import {Message} from './Message'; import {MessageType} from './MessageType'; import {PlainMessage} from './PlainMessage'; diff --git a/src/model/message/PersistentHarvestingDelegationMessage.ts b/src/model/message/PersistentHarvestingDelegationMessage.ts index 0cf489e0d4..c51d897f8f 100644 --- a/src/model/message/PersistentHarvestingDelegationMessage.ts +++ b/src/model/message/PersistentHarvestingDelegationMessage.ts @@ -17,7 +17,7 @@ import {Crypto, SHA3Hasher} from '../../core/crypto'; import { Convert } from '../../core/format/Convert'; import { Account } from '../account/Account'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { Message } from './Message'; import { MessageMarker } from './MessageMarker'; import { MessageType } from './MessageType'; diff --git a/src/model/model.ts b/src/model/model.ts index 4f97aa7e4a..75d93ee10f 100644 --- a/src/model/model.ts +++ b/src/model/model.ts @@ -32,10 +32,8 @@ export * from './account/AccountNames'; export * from './blockchain/BlockchainScore'; export * from './blockchain/StorageInfo'; export * from './blockchain/BlockInfo'; -export * from './blockchain/NetworkType'; export * from './blockchain/MerklePathItem'; export * from './blockchain/MerkleProofInfo'; -export * from './blockchain/NetworkName'; // Diagnostic export * from './node/ServerInfo'; @@ -72,6 +70,28 @@ export * from './namespace/NamespaceRegistrationType'; export * from './namespace/AliasAction'; export * from './namespace/EmptyAlias'; +// Network + +export * from './network/AccountLinkNetworkProperties'; +export * from './network/AccountRestrictionNetworkProperties'; +export * from './network/AggregateNetworkProperties'; +export * from './network/ChainProperties'; +export * from './network/HashLockNetworkProperties'; +export * from './network/MetadataNetworkProperties'; +export * from './network/MosaicNetworkProperties'; +export * from './network/MosaicRestrictionNetworkProperties'; +export * from './network/MultisigNetworkProperties'; +export * from './network/NamespaceNetworkProperties'; +export * from './network/NetworkConfiguration'; +export * from './network/NetworkName'; +export * from './network/NetworkProperties'; +export * from './network/NetworkType'; +export * from './network/PluginProperties'; +export * from './network/RentalFees'; +export * from './network/SecretLockNetworkProperties'; +export * from './network/TransactionFees'; +export * from './network/TransferNetworkProperties'; + // Node export * from './node/NodeInfo'; export * from './node/NodeTime'; diff --git a/src/model/network/AccountLinkNetworkProperties.ts b/src/model/network/AccountLinkNetworkProperties.ts new file mode 100644 index 0000000000..f7616dc256 --- /dev/null +++ b/src/model/network/AccountLinkNetworkProperties.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class AccountLinkNetworkProperties { + + /** + * @param dummy - to trigger plugin load. + */ + constructor(public readonly dummy?: string) { + } +} diff --git a/src/model/network/AccountRestrictionNetworkProperties.ts b/src/model/network/AccountRestrictionNetworkProperties.ts new file mode 100644 index 0000000000..d6a29dcbbc --- /dev/null +++ b/src/model/network/AccountRestrictionNetworkProperties.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class AccountRestrictionNetworkProperties { + + /** + * @param maxAccountRestrictionValues - Maximum number of account restriction values. + */ + constructor(public readonly maxAccountRestrictionValues?: string) { + } +} diff --git a/src/model/network/AggregateNetworkProperties.ts b/src/model/network/AggregateNetworkProperties.ts new file mode 100644 index 0000000000..ae3f8f1dcb --- /dev/null +++ b/src/model/network/AggregateNetworkProperties.ts @@ -0,0 +1,32 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + // tslint:disable: max-line-length +export class AggregateNetworkProperties { + /** + * @param maxTransactionsPerAggregate - Maximum number of transactions per aggregate. + * @param maxCosignaturesPerAggregate - Maximum number of cosignatures per aggregate. + * @param enableStrictCosignatureCheck - Set to true if cosignatures must exactly match component signers. Set to false if cosignatures should be validated externally. + * @param enableBondedAggregateSupport - Set to true if bonded aggregates should be allowed. Set to false if bonded aggregates should be rejected. + * @param maxBondedTransactionLifetime - Maximum lifetime a bonded transaction can have before it expires. + */ + constructor(public readonly maxTransactionsPerAggregate?: string, + public readonly maxCosignaturesPerAggregate?: string, + public readonly enableStrictCosignatureCheck?: boolean, + public readonly enableBondedAggregateSupport?: boolean, + public readonly maxBondedTransactionLifetime?: string) { + } +} diff --git a/src/model/network/ChainProperties.ts b/src/model/network/ChainProperties.ts new file mode 100644 index 0000000000..6de1d92b5b --- /dev/null +++ b/src/model/network/ChainProperties.ts @@ -0,0 +1,66 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License: string, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing: string, software + * distributed under the License is distributed on an "AS IS" BASIS: string, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND: string, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// tslint:disable: max-line-length +/** + * Chain related configuration properties. + */ +export class ChainProperties { + /** + * @param enableVerifiableState - Set to true if block chain should calculate state hashes so that state is fully verifiable at each block. + * @param enableVerifiableReceipts - Set to true if block chain should calculate receipts so that state changes are fully verifiable at each block. + * @param currencyMosaicId - Mosaic id used as primary chain currency. + * @param harvestingMosaicId - Mosaic id used to provide harvesting ability. + * @param blockGenerationTargetTime - Targeted time between blocks. + * @param blockTimeSmoothingFactor - A higher value makes the network more biased. + * @param importanceGrouping - Number of blocks that should be treated as a group for importance purposes. + * @param importanceActivityPercentage - Percentage of importance resulting from fee generation and beneficiary usage. + * @param maxRollbackBlocks - Maximum number of blocks that can be rolled back. + * @param maxDifficultyBlocks - Maximum number of blocks to use in a difficulty calculation. + * @param defaultDynamicFeeMultiplier - Default multiplier to use for dynamic fees. + * @param maxTransactionLifetime - Maximum lifetime a transaction can have before it expires. + * @param maxBlockFutureTime - Maximum future time of a block that can be accepted. + * @param initialCurrencyAtomicUnits - Initial currency atomic units available in the network. + * @param maxMosaicAtomicUnits - Maximum atomic units (total-supply * 10 ^ divisibility) of a mosaic allowed in the network. + * @param totalChainImportance - Total whole importance units available in the network. + * @param minHarvesterBalance - Minimum number of harvesting mosaic atomic units needed for an account to be eligible for harvesting. + * @param maxHarvesterBalance - Maximum number of harvesting mosaic atomic units needed for an account to be eligible for harvesting. + * @param harvestBeneficiaryPercentage - Percentage of the harvested fee that is collected by the beneficiary account. + * @param blockPruneInterval - Number of blocks between cache pruning. + * @param maxTransactionsPerBlock - Maximum number of transactions per block. + */ + constructor(public readonly enableVerifiableState?: boolean, + public readonly enableVerifiableReceipts?: boolean, + public readonly currencyMosaicId?: string, + public readonly harvestingMosaicId?: string, + public readonly blockGenerationTargetTime?: string, + public readonly blockTimeSmoothingFactor?: string, + public readonly importanceGrouping?: string, + public readonly importanceActivityPercentage?: string, + public readonly maxRollbackBlocks?: string, + public readonly maxDifficultyBlocks?: string, + public readonly defaultDynamicFeeMultiplier?: string, + public readonly maxTransactionLifetime?: string, + public readonly maxBlockFutureTime?: string, + public readonly initialCurrencyAtomicUnits?: string, + public readonly maxMosaicAtomicUnits?: string, + public readonly totalChainImportance?: string, + public readonly minHarvesterBalance?: string, + public readonly maxHarvesterBalance?: string, + public readonly harvestBeneficiaryPercentage?: string, + public readonly blockPruneInterval?: string, + public readonly maxTransactionsPerBlock?: string) { + } +} diff --git a/src/model/network/HashLockNetworkProperties.ts b/src/model/network/HashLockNetworkProperties.ts new file mode 100644 index 0000000000..006354741c --- /dev/null +++ b/src/model/network/HashLockNetworkProperties.ts @@ -0,0 +1,26 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class HashLockNetworkProperties { + + /** + * @param lockedFundsPerAggregate - Amount that has to be locked per aggregate in partial cache. + * @param maxHashLockDuration - Maximum number of blocks for which a hash lock can exist. + */ + constructor(public readonly lockedFundsPerAggregate?: string, + public readonly maxHashLockDuration?: string) { + } +} diff --git a/src/model/network/MetadataNetworkProperties.ts b/src/model/network/MetadataNetworkProperties.ts new file mode 100644 index 0000000000..6cb37e0291 --- /dev/null +++ b/src/model/network/MetadataNetworkProperties.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class MetadataNetworkProperties { + + /** + * @param maxValueSize - Maximum metadata value size. + */ + constructor(public readonly maxValueSize?: string) { + } +} diff --git a/src/model/network/MosaicNetworkProperties.ts b/src/model/network/MosaicNetworkProperties.ts new file mode 100644 index 0000000000..0e2dc7d15c --- /dev/null +++ b/src/model/network/MosaicNetworkProperties.ts @@ -0,0 +1,31 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + export class MosaicNetworkProperties { + /** + * @param maxMosaicsPerAccount - Maximum number of mosaics that an account can own. + * @param maxMosaicDuration - Maximum mosaic duration. + * @param maxMosaicDivisibility - Maximum mosaic divisibility. + * @param mosaicRentalFeeSinkPublicKey - Public key of the mosaic rental fee sink account. + * @param mosaicRentalFee - Mosaic rental fee. + */ + constructor(public readonly maxMosaicsPerAccount?: string, + public readonly maxMosaicDuration?: string, + public readonly maxMosaicDivisibility?: string, + public readonly mosaicRentalFeeSinkPublicKey?: string, + public readonly mosaicRentalFee?: string) { + } +} diff --git a/src/model/network/MosaicRestrictionNetworkProperties.ts b/src/model/network/MosaicRestrictionNetworkProperties.ts new file mode 100644 index 0000000000..c1565a59f1 --- /dev/null +++ b/src/model/network/MosaicRestrictionNetworkProperties.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class MosaicRestrictionNetworkProperties { + + /** + * @param maxMosaicRestrictionValues - Maximum number of mosaic restriction values. + */ + constructor(public readonly maxMosaicRestrictionValues?: string) { + } +} diff --git a/src/model/network/MultisigNetworkProperties.ts b/src/model/network/MultisigNetworkProperties.ts new file mode 100644 index 0000000000..9cc4342983 --- /dev/null +++ b/src/model/network/MultisigNetworkProperties.ts @@ -0,0 +1,28 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class MultisigNetworkProperties { + + /** + * @param maxMultisigDepth - Maximum number of multisig levels. + * @param maxCosignatoriesPerAccount - Maximum number of cosignatories per account. + * @param maxCosignedAccountsPerAccount - Maximum number of accounts a single account can cosign. + */ + constructor(public readonly maxMultisigDepth?: string, + public readonly maxCosignatoriesPerAccount?: string, + public readonly maxCosignedAccountsPerAccount?: string) { + } +} diff --git a/src/model/network/NamespaceNetworkProperties.ts b/src/model/network/NamespaceNetworkProperties.ts new file mode 100644 index 0000000000..74c1e1f776 --- /dev/null +++ b/src/model/network/NamespaceNetworkProperties.ts @@ -0,0 +1,42 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class NamespaceNetworkProperties { + + /** + * @param maxNameSize - Maximum namespace name size. + * @param maxChildNamespaces - Maximum number of children for a root namespace. + * @param maxNamespaceDepth - Maximum namespace depth. + * @param minNamespaceDuration - Minimum namespace duration. + * @param maxNamespaceDuration - Maximum namespace duration. + * @param namespaceGracePeriodDuration - Grace period during which time only the previous owner can renew an expired namespace. + * @param reservedRootNamespaceNames - Reserved root namespaces that cannot be claimed. + * @param namespaceRentalFeeSinkPublicKey - Public key of the namespace rental fee sink account. + * @param rootNamespaceRentalFeePerBlock - Root namespace rental fee per block. + * @param childNamespaceRentalFee - Child namespace rental fee. + */ + constructor(public readonly maxNameSize?: string, + public readonly maxChildNamespaces?: string, + public readonly maxNamespaceDepth?: string, + public readonly minNamespaceDuration?: string, + public readonly maxNamespaceDuration?: string, + public readonly namespaceGracePeriodDuration?: string, + public readonly reservedRootNamespaceNames?: string, + public readonly namespaceRentalFeeSinkPublicKey?: string, + public readonly rootNamespaceRentalFeePerBlock?: string, + public readonly childNamespaceRentalFee?: string) { + } +} diff --git a/src/model/network/NetworkConfiguration.ts b/src/model/network/NetworkConfiguration.ts new file mode 100644 index 0000000000..56c9cec4ab --- /dev/null +++ b/src/model/network/NetworkConfiguration.ts @@ -0,0 +1,35 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ChainProperties } from './ChainProperties'; +import { NetworkProperties } from './NetworkProperties'; +import { PluginProperties } from './PluginProperties'; + +/** + * Network Configuration + */ +export class NetworkConfiguration { + + /** + * @param network - Network related configuration properties. + * @param chain - Chain related configuration properties. + * @param plugins - Plugin related configuration properties. + */ + constructor(public readonly network: NetworkProperties, + public readonly chain: ChainProperties, + public readonly plugins: PluginProperties) { + } +} diff --git a/src/model/blockchain/NetworkName.ts b/src/model/network/NetworkName.ts similarity index 100% rename from src/model/blockchain/NetworkName.ts rename to src/model/network/NetworkName.ts diff --git a/src/model/network/NetworkProperties.ts b/src/model/network/NetworkProperties.ts new file mode 100644 index 0000000000..c32e2e94b6 --- /dev/null +++ b/src/model/network/NetworkProperties.ts @@ -0,0 +1,37 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NodeIdentityEqualityStrategy } from 'symbol-openapi-typescript-node-client'; + +/** + * Network related configuration properties. + */ +export class NetworkProperties { + + /** + * @param identifier - Network identifier. + * @param nodeEqualityStrategy - Node equality strategy. Defines if the identifier for the node must be its public key or host. + * @param publicKey - Nemesis public key. + * @param generationHash - Nemesis generation hash. + * @param epochAdjustment - Nemesis epoch time adjustment. + */ + constructor(public readonly identifier?: string, + public readonly nodeEqualityStrategy?: NodeIdentityEqualityStrategy, + public readonly publicKey?: string, + public readonly generationHash?: string, + public readonly epochAdjustment?: string) { + } +} diff --git a/src/model/blockchain/NetworkType.ts b/src/model/network/NetworkType.ts similarity index 100% rename from src/model/blockchain/NetworkType.ts rename to src/model/network/NetworkType.ts diff --git a/src/model/network/PluginProperties.ts b/src/model/network/PluginProperties.ts new file mode 100644 index 0000000000..3fd8d90b7d --- /dev/null +++ b/src/model/network/PluginProperties.ts @@ -0,0 +1,60 @@ +/* +import { AccountLinkNetworkProperties } from './AccountLinkNetworkProperties'; + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AccountLinkNetworkProperties } from './AccountLinkNetworkProperties'; +import { AccountRestrictionNetworkProperties } from './AccountRestrictionNetworkProperties'; +import { AggregateNetworkProperties } from './AggregateNetworkProperties'; +import { HashLockNetworkProperties } from './HashLockNetworkProperties'; +import { MetadataNetworkProperties } from './MetadataNetworkProperties'; +import { MosaicNetworkProperties } from './MosaicNetworkProperties'; +import { MosaicRestrictionNetworkProperties } from './MosaicRestrictionNetworkProperties'; +import { MultisigNetworkProperties } from './MultisigNetworkProperties'; +import { NamespaceNetworkProperties } from './NamespaceNetworkProperties'; +import { SecretLockNetworkProperties } from './SecretLockNetworkProperties'; +import { TransferNetworkProperties } from './TransferNetworkProperties'; + +/** + * Network related configuration properties. + */ +export class PluginProperties { + + /** + * @param accountlink - Network identifier. + * @param aggregate - Nemesis public key. + * @param lockhash - Nemesis generation hash. + * @param locksecret - Nemesis epoch time adjustment. + * @param metadata - + * @param mosaic - + * @param multisig - + * @param namespace - + * @param restrictionaccount - + * @param restrictionmosaic - + * @param transfer - + */ + constructor(public readonly accountlink?: AccountLinkNetworkProperties, + public readonly aggregate?: AggregateNetworkProperties, + public readonly lockhash?: HashLockNetworkProperties, + public readonly locksecret?: SecretLockNetworkProperties, + public readonly metadata?: MetadataNetworkProperties, + public readonly mosaic?: MosaicNetworkProperties, + public readonly multisig?: MultisigNetworkProperties, + public readonly namespace?: NamespaceNetworkProperties, + public readonly restrictionaccount?: AccountRestrictionNetworkProperties, + public readonly restrictionmosaic?: MosaicRestrictionNetworkProperties, + public readonly transfer?: TransferNetworkProperties) { + } +} diff --git a/src/model/network/RentalFees.ts b/src/model/network/RentalFees.ts new file mode 100644 index 0000000000..601dcce0c8 --- /dev/null +++ b/src/model/network/RentalFees.ts @@ -0,0 +1,33 @@ +/* + * Copyright 2019 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + import { UInt64 } from '../UInt64'; + +/** + * Rental Fees + */ +export class RentalFees { + // tslint:disable: max-line-length + /** + * @param effectiveRootNamespaceRentalFeePerBlock - Absolute amount. An amount of 123456789 (absolute) for a mosaic with divisibility 6 means 123.456789 (relative). + * @param effectiveChildNamespaceRentalFee - Absolute amount. An amount of 123456789 (absolute) for a mosaic with divisibility 6 means 123.456789 (relative). + * @param effectiveMosaicRentalFee - bsolute amount. An amount of 123456789 (absolute) for a mosaic with divisibility 6 means 123.456789 (relative). + */ + constructor(public readonly effectiveRootNamespaceRentalFeePerBlock: UInt64, + public readonly effectiveChildNamespaceRentalFee: UInt64, + public readonly effectiveMosaicRentalFee: UInt64) { + } +} diff --git a/src/model/network/SecretLockNetworkProperties.ts b/src/model/network/SecretLockNetworkProperties.ts new file mode 100644 index 0000000000..002cb9e214 --- /dev/null +++ b/src/model/network/SecretLockNetworkProperties.ts @@ -0,0 +1,28 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class SecretLockNetworkProperties { + + /** + * @param maxSecretLockDuration - Maximum number of blocks for which a secret lock can exist. + * @param minProofSize - Minimum size of a proof in bytes. + * @param maxProofSize - Maximum size of a proof in bytes. + */ + constructor(public readonly maxSecretLockDuration?: string, + public readonly minProofSize?: string, + public readonly maxProofSize?: string) { + } +} diff --git a/src/model/blockchain/NetworkFees.ts b/src/model/network/TransactionFees.ts similarity index 80% rename from src/model/blockchain/NetworkFees.ts rename to src/model/network/TransactionFees.ts index fb39b430fd..25c3b75ba3 100644 --- a/src/model/blockchain/NetworkFees.ts +++ b/src/model/network/TransactionFees.ts @@ -15,15 +15,15 @@ */ /** - * Network Fees + * Transacation Fees */ -export class NetworkFees { +export class TransactionFees { /** * @param averageFeeMultiplier - Average fee multiplier over the last \"numBlocksTransactionFeeStats\". * @param medianFeeMultiplier - Median fee multiplier over the last \"numBlocksTransactionFeeStats\". - * @param highestFeeMultiplier - Fee multiplier applied to transactions contained in block. - * @param lowestFeeMultiplier - Fee multiplier applied to transactions contained in block. + * @param highestFeeMultiplier - Highest fee multiplier over the last "numBlocksTransactionFeeStats". + * @param lowestFeeMultiplier - Lowest fee multiplier over the last "numBlocksTransactionFeeStats". */ constructor(public readonly averageFeeMultiplier: number, public readonly medianFeeMultiplier: number, diff --git a/src/model/network/TransferNetworkProperties.ts b/src/model/network/TransferNetworkProperties.ts new file mode 100644 index 0000000000..bac679f0d6 --- /dev/null +++ b/src/model/network/TransferNetworkProperties.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class TransferNetworkProperties { + + /** + * @param maxMessageSize - Maximum transaction message size. + */ + constructor(public readonly maxMessageSize?: string) { + } +} diff --git a/src/model/node/NodeInfo.ts b/src/model/node/NodeInfo.ts index 1d0632366d..e4f8198b02 100644 --- a/src/model/node/NodeInfo.ts +++ b/src/model/node/NodeInfo.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { RoleType } from './RoleType'; /** * The node info structure describes basic information of a node. diff --git a/src/model/receipt/ResolutionStatement.ts b/src/model/receipt/ResolutionStatement.ts index 9884464d4c..ed2e536b8a 100644 --- a/src/model/receipt/ResolutionStatement.ts +++ b/src/model/receipt/ResolutionStatement.ts @@ -26,9 +26,9 @@ import { sha3_256 } from 'js-sha3'; import { RawAddress } from '../../core/format/RawAddress'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { Address } from '../account/Address'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { ReceiptType } from './ReceiptType'; import { ReceiptVersion } from './ReceiptVersion'; diff --git a/src/model/transaction/AccountAddressRestrictionTransaction.ts b/src/model/transaction/AccountAddressRestrictionTransaction.ts index 293caa4eff..000878411b 100644 --- a/src/model/transaction/AccountAddressRestrictionTransaction.ts +++ b/src/model/transaction/AccountAddressRestrictionTransaction.ts @@ -29,8 +29,8 @@ import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { Address } from '../account/Address'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { AccountRestrictionFlags } from '../restriction/AccountRestrictionType'; import { UInt64 } from '../UInt64'; @@ -55,8 +55,8 @@ export class AccountAddressRestrictionTransaction extends Transaction { */ public static create(deadline: Deadline, restrictionFlags: AccountRestrictionFlags, - restrictionAdditions: Array
, - restrictionDeletions: Array
, + restrictionAdditions: (Address | NamespaceId)[], + restrictionDeletions: (Address | NamespaceId)[], networkType: NetworkType, maxFee: UInt64 = new UInt64([0, 0])): AccountAddressRestrictionTransaction { return new AccountAddressRestrictionTransaction(networkType, @@ -85,8 +85,8 @@ export class AccountAddressRestrictionTransaction extends Transaction { deadline: Deadline, maxFee: UInt64, public readonly restrictionFlags: AccountRestrictionFlags, - public readonly restrictionAdditions: Array
, - public readonly restrictionDeletions: Array
, + public readonly restrictionAdditions: (Address | NamespaceId)[], + public readonly restrictionDeletions: (Address | NamespaceId)[], signature?: string, signer?: PublicAccount, transactionInfo?: TransactionInfo) { diff --git a/src/model/transaction/AccountLinkTransaction.ts b/src/model/transaction/AccountLinkTransaction.ts index eb64861a4d..784b408b41 100644 --- a/src/model/transaction/AccountLinkTransaction.ts +++ b/src/model/transaction/AccountLinkTransaction.ts @@ -25,7 +25,7 @@ import { } from 'catbuffer-typescript'; import { Convert } from '../../core/format'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { InnerTransaction } from './InnerTransaction'; diff --git a/src/model/transaction/AccountMetadataTransaction.ts b/src/model/transaction/AccountMetadataTransaction.ts index 327627bda1..684aad60cf 100644 --- a/src/model/transaction/AccountMetadataTransaction.ts +++ b/src/model/transaction/AccountMetadataTransaction.ts @@ -25,7 +25,7 @@ import { } from 'catbuffer-typescript'; import { Convert } from '../../core/format'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { InnerTransaction } from './InnerTransaction'; diff --git a/src/model/transaction/AccountMosaicRestrictionTransaction.ts b/src/model/transaction/AccountMosaicRestrictionTransaction.ts index 8a07ecaca5..5680e4d091 100644 --- a/src/model/transaction/AccountMosaicRestrictionTransaction.ts +++ b/src/model/transaction/AccountMosaicRestrictionTransaction.ts @@ -28,9 +28,9 @@ import { Convert } from '../../core/format'; import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { AccountRestrictionFlags } from '../restriction/AccountRestrictionType'; import { UInt64 } from '../UInt64'; @@ -55,8 +55,8 @@ export class AccountMosaicRestrictionTransaction extends Transaction { */ public static create(deadline: Deadline, restrictionFlags: AccountRestrictionFlags, - restrictionAdditions: Array, - restrictionDeletions: Array, + restrictionAdditions: (MosaicId | NamespaceId)[], + restrictionDeletions: (MosaicId | NamespaceId)[], networkType: NetworkType, maxFee: UInt64 = new UInt64([0, 0])): AccountMosaicRestrictionTransaction { return new AccountMosaicRestrictionTransaction(networkType, @@ -85,8 +85,8 @@ export class AccountMosaicRestrictionTransaction extends Transaction { deadline: Deadline, maxFee: UInt64, public readonly restrictionFlags: AccountRestrictionFlags, - public readonly restrictionAdditions: Array, - public readonly restrictionDeletions: Array, + public readonly restrictionAdditions: (MosaicId | NamespaceId)[], + public readonly restrictionDeletions: (MosaicId | NamespaceId)[], signature?: string, signer?: PublicAccount, transactionInfo?: TransactionInfo) { diff --git a/src/model/transaction/AccountOperationRestrictionTransaction.ts b/src/model/transaction/AccountOperationRestrictionTransaction.ts index 2da59c8fc2..7a3d334dc6 100644 --- a/src/model/transaction/AccountOperationRestrictionTransaction.ts +++ b/src/model/transaction/AccountOperationRestrictionTransaction.ts @@ -25,7 +25,7 @@ import { } from 'catbuffer-typescript'; import { Convert } from '../../core/format'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { AccountRestrictionFlags } from '../restriction/AccountRestrictionType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; diff --git a/src/model/transaction/AccountRestrictionTransaction.ts b/src/model/transaction/AccountRestrictionTransaction.ts index 7b5ff5638b..5b198ae189 100644 --- a/src/model/transaction/AccountRestrictionTransaction.ts +++ b/src/model/transaction/AccountRestrictionTransaction.ts @@ -15,9 +15,9 @@ */ import { Address } from '../account/Address'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { AccountRestrictionFlags } from '../restriction/AccountRestrictionType'; import { UInt64 } from '../UInt64'; import { AccountAddressRestrictionTransaction } from './AccountAddressRestrictionTransaction'; @@ -41,8 +41,8 @@ export class AccountRestrictionTransaction { public static createAddressRestrictionModificationTransaction( deadline: Deadline, restrictionFlags: AccountRestrictionFlags, - restrictionAdditions: Array
, - restrictionDeletions: Array
, + restrictionAdditions: (Address | NamespaceId)[], + restrictionDeletions: (Address | NamespaceId)[], networkType: NetworkType, maxFee: UInt64 = new UInt64([0, 0]), ): AccountAddressRestrictionTransaction { @@ -75,8 +75,8 @@ export class AccountRestrictionTransaction { public static createMosaicRestrictionModificationTransaction( deadline: Deadline, restrictionFlags: AccountRestrictionFlags, - restrictionAdditions: Array, - restrictionDeletions: Array, + restrictionAdditions: (MosaicId | NamespaceId)[], + restrictionDeletions: (MosaicId | NamespaceId)[], networkType: NetworkType, maxFee: UInt64 = new UInt64([0, 0]), ): AccountMosaicRestrictionTransaction { diff --git a/src/model/transaction/AddressAliasTransaction.ts b/src/model/transaction/AddressAliasTransaction.ts index d5f7593d32..4174d8e92a 100644 --- a/src/model/transaction/AddressAliasTransaction.ts +++ b/src/model/transaction/AddressAliasTransaction.ts @@ -28,9 +28,9 @@ import { import { Convert, RawAddress } from '../../core/format'; import { Address } from '../account/Address'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { AliasAction } from '../namespace/AliasAction'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { InnerTransaction } from './InnerTransaction'; diff --git a/src/model/transaction/AggregateTransaction.ts b/src/model/transaction/AggregateTransaction.ts index 60790dd3d6..16fa41fe4a 100644 --- a/src/model/transaction/AggregateTransaction.ts +++ b/src/model/transaction/AggregateTransaction.ts @@ -33,7 +33,7 @@ import { DtoMapping } from '../../core/utils/DtoMapping'; import { CreateTransactionFromPayload } from '../../infrastructure/transaction/CreateTransactionFromPayload'; import { Account } from '../account/Account'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { AggregateTransactionCosignature } from './AggregateTransactionCosignature'; diff --git a/src/model/transaction/AggregateTransactionCosignature.ts b/src/model/transaction/AggregateTransactionCosignature.ts index 4e9fc3a33b..55a0e09345 100644 --- a/src/model/transaction/AggregateTransactionCosignature.ts +++ b/src/model/transaction/AggregateTransactionCosignature.ts @@ -15,7 +15,7 @@ */ import {PublicAccount} from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; /** * Model representing cosignature of an aggregate transaction. */ diff --git a/src/model/transaction/AliasTransaction.ts b/src/model/transaction/AliasTransaction.ts index 4b023a0575..321f3e012c 100644 --- a/src/model/transaction/AliasTransaction.ts +++ b/src/model/transaction/AliasTransaction.ts @@ -15,10 +15,10 @@ */ import { Address } from '../account/Address'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { AliasAction } from '../namespace/AliasAction'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { AddressAliasTransaction } from './AddressAliasTransaction'; import { Deadline } from './Deadline'; diff --git a/src/model/transaction/LockFundsTransaction.ts b/src/model/transaction/LockFundsTransaction.ts index 7b9395c3bb..27145c6c6c 100644 --- a/src/model/transaction/LockFundsTransaction.ts +++ b/src/model/transaction/LockFundsTransaction.ts @@ -30,9 +30,9 @@ import { import { Convert } from '../../core/format'; import { DtoMapping } from '../../core/utils/DtoMapping'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { Mosaic } from '../mosaic/Mosaic'; import { MosaicId } from '../mosaic/MosaicId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; diff --git a/src/model/transaction/MosaicAddressRestrictionTransaction.ts b/src/model/transaction/MosaicAddressRestrictionTransaction.ts index b9fc59f7fb..598342da18 100644 --- a/src/model/transaction/MosaicAddressRestrictionTransaction.ts +++ b/src/model/transaction/MosaicAddressRestrictionTransaction.ts @@ -30,9 +30,9 @@ import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { Address } from '../account/Address'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; diff --git a/src/model/transaction/MosaicAliasTransaction.ts b/src/model/transaction/MosaicAliasTransaction.ts index 2a29713330..420c975590 100644 --- a/src/model/transaction/MosaicAliasTransaction.ts +++ b/src/model/transaction/MosaicAliasTransaction.ts @@ -27,10 +27,10 @@ import { } from 'catbuffer-typescript'; import { Convert } from '../../core/format'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { AliasAction } from '../namespace/AliasAction'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { InnerTransaction } from './InnerTransaction'; diff --git a/src/model/transaction/MosaicDefinitionTransaction.ts b/src/model/transaction/MosaicDefinitionTransaction.ts index 4c537560ab..ba5fee1622 100644 --- a/src/model/transaction/MosaicDefinitionTransaction.ts +++ b/src/model/transaction/MosaicDefinitionTransaction.ts @@ -28,10 +28,10 @@ import { } from 'catbuffer-typescript'; import { Convert } from '../../core/format'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicFlags } from '../mosaic/MosaicFlags'; import { MosaicId } from '../mosaic/MosaicId'; import { MosaicNonce } from '../mosaic/MosaicNonce'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { InnerTransaction } from './InnerTransaction'; diff --git a/src/model/transaction/MosaicGlobalRestrictionTransaction.ts b/src/model/transaction/MosaicGlobalRestrictionTransaction.ts index eacc12a23c..8eaabb8ccf 100644 --- a/src/model/transaction/MosaicGlobalRestrictionTransaction.ts +++ b/src/model/transaction/MosaicGlobalRestrictionTransaction.ts @@ -28,9 +28,9 @@ import { Convert } from '../../core/format'; import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { MosaicRestrictionType } from '../restriction/MosaicRestrictionType'; import { UInt64 } from '../UInt64'; diff --git a/src/model/transaction/MosaicMetadataTransaction.ts b/src/model/transaction/MosaicMetadataTransaction.ts index fccf89c2a9..41e21d2214 100644 --- a/src/model/transaction/MosaicMetadataTransaction.ts +++ b/src/model/transaction/MosaicMetadataTransaction.ts @@ -28,9 +28,9 @@ import { Convert } from '../../core/format'; import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; diff --git a/src/model/transaction/MosaicSupplyChangeTransaction.ts b/src/model/transaction/MosaicSupplyChangeTransaction.ts index b742da2266..a2cee6f602 100644 --- a/src/model/transaction/MosaicSupplyChangeTransaction.ts +++ b/src/model/transaction/MosaicSupplyChangeTransaction.ts @@ -28,10 +28,10 @@ import { Convert } from '../../core/format'; import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { MosaicId } from '../mosaic/MosaicId'; import { MosaicSupplyChangeAction } from '../mosaic/MosaicSupplyChangeAction'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; diff --git a/src/model/transaction/MultisigAccountModificationTransaction.ts b/src/model/transaction/MultisigAccountModificationTransaction.ts index dfd68c2f5e..399d329a92 100644 --- a/src/model/transaction/MultisigAccountModificationTransaction.ts +++ b/src/model/transaction/MultisigAccountModificationTransaction.ts @@ -25,7 +25,7 @@ import { } from 'catbuffer-typescript'; import { Convert } from '../../core/format'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { InnerTransaction } from './InnerTransaction'; diff --git a/src/model/transaction/NamespaceMetadataTransaction.ts b/src/model/transaction/NamespaceMetadataTransaction.ts index 4bcd502c11..a2e6df2457 100644 --- a/src/model/transaction/NamespaceMetadataTransaction.ts +++ b/src/model/transaction/NamespaceMetadataTransaction.ts @@ -26,8 +26,8 @@ import { } from 'catbuffer-typescript'; import { Convert } from '../../core/format'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { InnerTransaction } from './InnerTransaction'; diff --git a/src/model/transaction/NamespaceRegistrationTransaction.ts b/src/model/transaction/NamespaceRegistrationTransaction.ts index 3490fe9e08..9bb4e98643 100644 --- a/src/model/transaction/NamespaceRegistrationTransaction.ts +++ b/src/model/transaction/NamespaceRegistrationTransaction.ts @@ -28,9 +28,9 @@ import { import { Convert, Convert as convert } from '../../core/format'; import { NamespaceMosaicIdGenerator } from '../../infrastructure/transaction/NamespaceMosaicIdGenerator'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { NamespaceId } from '../namespace/NamespaceId'; import { NamespaceRegistrationType } from '../namespace/NamespaceRegistrationType'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { InnerTransaction } from './InnerTransaction'; diff --git a/src/model/transaction/PersistentDelegationRequestTransaction.ts b/src/model/transaction/PersistentDelegationRequestTransaction.ts index 93e52137f6..d971c30acc 100644 --- a/src/model/transaction/PersistentDelegationRequestTransaction.ts +++ b/src/model/transaction/PersistentDelegationRequestTransaction.ts @@ -15,8 +15,8 @@ */ import { Address } from '../account/Address'; -import { NetworkType } from '../blockchain/NetworkType'; import { PersistentHarvestingDelegationMessage } from '../message/PersistentHarvestingDelegationMessage'; +import { NetworkType } from '../network/NetworkType'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; import { TransferTransaction } from './TransferTransaction'; diff --git a/src/model/transaction/SecretLockTransaction.ts b/src/model/transaction/SecretLockTransaction.ts index 3adeaeb0bd..3dc82dab84 100644 --- a/src/model/transaction/SecretLockTransaction.ts +++ b/src/model/transaction/SecretLockTransaction.ts @@ -32,9 +32,9 @@ import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { Address } from '../account/Address'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { Mosaic } from '../mosaic/Mosaic'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; diff --git a/src/model/transaction/SecretProofTransaction.ts b/src/model/transaction/SecretProofTransaction.ts index 4869ed51e0..5f4db4f18c 100644 --- a/src/model/transaction/SecretProofTransaction.ts +++ b/src/model/transaction/SecretProofTransaction.ts @@ -30,8 +30,8 @@ import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { Address } from '../account/Address'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; diff --git a/src/model/transaction/SignedTransaction.ts b/src/model/transaction/SignedTransaction.ts index e8a9010d8d..8644b47fed 100644 --- a/src/model/transaction/SignedTransaction.ts +++ b/src/model/transaction/SignedTransaction.ts @@ -16,7 +16,7 @@ import { Address } from '../account/Address'; import { PublicAccount } from '../account/PublicAccount'; -import {NetworkType} from '../blockchain/NetworkType'; +import {NetworkType} from '../network/NetworkType'; import { TransactionType } from './TransactionType'; /** diff --git a/src/model/transaction/Transaction.ts b/src/model/transaction/Transaction.ts index 2ae1fde1c3..d6595853a6 100644 --- a/src/model/transaction/Transaction.ts +++ b/src/model/transaction/Transaction.ts @@ -21,7 +21,7 @@ import { DtoMapping } from '../../core/utils/DtoMapping'; import { SerializeTransactionToJSON } from '../../infrastructure/transaction/SerializeTransactionToJSON'; import { Account } from '../account/Account'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { AggregateTransactionInfo } from './AggregateTransactionInfo'; @@ -235,12 +235,11 @@ export abstract class Transaction { } /** - * @internal * Generate signing bytes * @param payloadBytes Payload buffer * @param generationHashBytes GenerationHash buffer */ - protected getSigningBytes(payloadBytes: number[], generationHashBytes: number[]) { + public getSigningBytes(payloadBytes: number[], generationHashBytes: number[]) { const byteBufferWithoutHeader = payloadBytes.slice(4 + 64 + 32 + 8); if (this.type === TransactionType.AGGREGATE_BONDED || this.type === TransactionType.AGGREGATE_COMPLETE) { return generationHashBytes.concat(byteBufferWithoutHeader.slice(0, 52)); diff --git a/src/model/transaction/TransferTransaction.ts b/src/model/transaction/TransferTransaction.ts index a8f20fa4ed..26464ef947 100644 --- a/src/model/transaction/TransferTransaction.ts +++ b/src/model/transaction/TransferTransaction.ts @@ -33,13 +33,13 @@ import { DtoMapping } from '../../core/utils/DtoMapping'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { Address } from '../account/Address'; import { PublicAccount } from '../account/PublicAccount'; -import { NetworkType } from '../blockchain/NetworkType'; import { EncryptedMessage } from '../message/EncryptedMessage'; import { Message } from '../message/Message'; import { MessageType } from '../message/MessageType'; import { PlainMessage } from '../message/PlainMessage'; import { Mosaic } from '../mosaic/Mosaic'; import { NamespaceId } from '../namespace/NamespaceId'; +import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; diff --git a/src/model/wallet/SimpleWallet.ts b/src/model/wallet/SimpleWallet.ts index 8e55d8c023..f5673ccf3c 100644 --- a/src/model/wallet/SimpleWallet.ts +++ b/src/model/wallet/SimpleWallet.ts @@ -19,7 +19,7 @@ import {Crypto, KeyPair, SHA3Hasher} from '../../core/crypto'; import {Convert as convert} from '../../core/format'; import {Account} from '../account/Account'; import {Address} from '../account/Address'; -import {NetworkType} from '../blockchain/NetworkType'; +import {NetworkType} from '../network/NetworkType'; import {EncryptedPrivateKey} from './EncryptedPrivateKey'; import {ISimpleWalletDTO} from './ISimpleWalletDTO'; import {Password} from './Password'; @@ -122,6 +122,14 @@ export class SimpleWallet extends Wallet { ); } + /** + * Creates a SimpleWallet DTO + * @returns {ISimpleWalletDTO} + */ + public toDTO(): ISimpleWalletDTO { + return JSON.parse(JSON.stringify(this)) + } + /** * Open a wallet and generate an Account * @param password - Password to decrypt private key diff --git a/src/model/wallet/Wallet.ts b/src/model/wallet/Wallet.ts index b8ed8cca04..e7ae15ae3f 100644 --- a/src/model/wallet/Wallet.ts +++ b/src/model/wallet/Wallet.ts @@ -17,7 +17,7 @@ import {LocalDateTime} from 'js-joda'; import {Account} from '../account/Account'; import {Address} from '../account/Address'; -import {NetworkType} from '../blockchain/NetworkType'; +import {NetworkType} from '../network/NetworkType'; import {Password} from './Password'; /** diff --git a/src/service/MetadataTransactionService.ts b/src/service/MetadataTransactionService.ts index dc4d1acf5c..59a8554536 100644 --- a/src/service/MetadataTransactionService.ts +++ b/src/service/MetadataTransactionService.ts @@ -20,11 +20,11 @@ import { Convert } from '../core/format/Convert'; import { MetadataRepository } from '../infrastructure/MetadataRepository'; import { Address } from '../model/account/Address'; import { PublicAccount } from '../model/account/PublicAccount'; -import { NetworkType } from '../model/blockchain/NetworkType'; import { Metadata } from '../model/metadata/Metadata'; import { MetadataType } from '../model/metadata/MetadataType'; import { MosaicId } from '../model/mosaic/MosaicId'; import { NamespaceId } from '../model/namespace/NamespaceId'; +import { NetworkType } from '../model/network/NetworkType'; import { AccountMetadataTransaction } from '../model/transaction/AccountMetadataTransaction'; import { Deadline } from '../model/transaction/Deadline'; import { MosaicMetadataTransaction } from '../model/transaction/MosaicMetadataTransaction'; diff --git a/src/service/MosaicRestrictionTransactionService.ts b/src/service/MosaicRestrictionTransactionService.ts index e068ea4df9..d522de89d0 100644 --- a/src/service/MosaicRestrictionTransactionService.ts +++ b/src/service/MosaicRestrictionTransactionService.ts @@ -21,9 +21,9 @@ import { mergeMap } from 'rxjs/operators'; import { NamespaceRepository } from '../infrastructure/NamespaceRepository'; import { RestrictionMosaicRepository } from '../infrastructure/RestrictionMosaicRepository'; import { Address } from '../model/account/Address'; -import { NetworkType } from '../model/blockchain/NetworkType'; import { MosaicId } from '../model/mosaic/MosaicId'; import { NamespaceId } from '../model/namespace/NamespaceId'; +import { NetworkType } from '../model/network/NetworkType'; import { MosaicGlobalRestriction } from '../model/restriction/MosaicGlobalRestriction'; import { MosaicGlobalRestrictionItem } from '../model/restriction/MosaicGlobalRestrictionItem'; import { MosaicRestrictionType } from '../model/restriction/MosaicRestrictionType'; diff --git a/src/service/TransactionService.ts b/src/service/TransactionService.ts index 8946d809ca..c0fd3bf768 100644 --- a/src/service/TransactionService.ts +++ b/src/service/TransactionService.ts @@ -112,14 +112,16 @@ export class TransactionService implements ITransactionService { /** * @internal * - * This method publishes an error if the listener receives an error code for the given address and transaction hash. Otherwise, it returns the passed transactionObservable + * This method publishes an error if the listener receives an error code for the given address & transaction hash. + * Otherwise, it returns the passed transactionObservable * * @param listener the listener. * @param address the signer address * @param transactionHash the transaction hash * @param transactionObservable the observable with the valid transaction */ - private getTransactionOrRaiseError(listener: IListener, address: Address, transactionHash: string, transactionObservable: Observable): Observable { + private getTransactionOrRaiseError(listener: IListener, address: Address, transactionHash: string, + transactionObservable: Observable): Observable { const errorObservable = listener.status(address).pipe(filter((t) => t.hash.toUpperCase() === transactionHash.toUpperCase())); return merge(transactionObservable, errorObservable).pipe(first(), map((errorOrTransaction) => { if (errorOrTransaction instanceof TransactionStatusError) { diff --git a/test/conf/conf.spec.ts b/test/conf/conf.spec.ts index 10c755fad5..d3b6c76927 100644 --- a/test/conf/conf.spec.ts +++ b/test/conf/conf.spec.ts @@ -15,7 +15,7 @@ */ import {Account} from '../../src/model/account/Account'; -import {NetworkType} from '../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../src/model/network/NetworkType'; export const TestingAccount = Account.createFromPrivateKey( '26b64cb10f005e5988a36744ca19e20d835ccc7c105aaa5f3b212da593180930', diff --git a/test/core/crypto/keyPair.spec.ts b/test/core/crypto/keyPair.spec.ts index 42ad183b5e..ba8d8477f6 100644 --- a/test/core/crypto/keyPair.spec.ts +++ b/test/core/crypto/keyPair.spec.ts @@ -17,7 +17,7 @@ import { expect } from 'chai'; import { Crypto, KeyPair } from '../../../src/core/crypto'; import * as Utility from '../../../src/core/crypto/Utilities'; import { Convert } from '../../../src/core/format/Convert'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; describe('key pair', () => { const randomKeyPair = () => diff --git a/test/core/crypto/utilities.spec.ts b/test/core/crypto/utilities.spec.ts new file mode 100644 index 0000000000..06f9d5eb0f --- /dev/null +++ b/test/core/crypto/utilities.spec.ts @@ -0,0 +1,32 @@ +/* + * Copyright 2019 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import {expect} from 'chai'; +import {words2ua} from '../../../src/core/crypto/Utilities'; +import {Convert} from '../../../src/core/format'; + +describe('crypto utilities', () => { + it('words2ua creates an ua from a word array', () => { + // Arrange: + const key = '4344645752e57065f814b51713d05810' + const words = [ 1128555607, 1390768229, -132860649, 332421136 ]; + + // Act: + const ua = words2ua(new Uint8Array(16), {words}) + + // Assert: + expect(ua).deep.equal(Convert.hexToUint8(key)); + }); +}); diff --git a/test/core/format/Convert.spec.ts b/test/core/format/Convert.spec.ts index a0b0e41469..75ae48ef65 100644 --- a/test/core/format/Convert.spec.ts +++ b/test/core/format/Convert.spec.ts @@ -147,6 +147,49 @@ describe('convert', () => { }); }); + describe('hexToUint8Reverse', () => { + it('can parse empty hex string into array', () => { + // Act: + const actual = convert.hexToUint8Reverse(''); + + // Assert: + const expected = Uint8Array.of(); + expect(actual).to.deep.equal(expected); + }); + + it('can parse valid hex string into array', () => { + // Act: + const actual = convert.hexToUint8Reverse('026ee415fc15'); + + // Assert: + const expected = Uint8Array.of(0x15, 0xFC, 0x15, 0xE4, 0x6E, 0x02); + expect(actual).to.deep.equal(expected); + }); + + it('can parse valid hex string containing all valid hex characters into array', () => { + // Act: + const actual = convert.hexToUint8Reverse('abcdef0123456789ABCDEF'); + + // Assert: + const expected = Uint8Array.of(0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB); + expect(actual).to.deep.equal(expected); + }); + + it('cannot parse hex string with invalid characters into array', () => { + // Assert: + expect(() => { + convert.hexToUint8Reverse('abcdef012345G789ABCDEF'); + }).to.throw('unrecognized hex char'); + }); + + it('cannot parse hex string with invalid size into array', () => { + // Assert: + expect(() => { + convert.hexToUint8Reverse('abcdef012345G789ABCDE'); + }).to.throw('hex string has unexpected size'); + }); + }); + describe('uint8ToHex', () => { it('can format empty array into hex string', () => { // Act: diff --git a/test/core/format/IdGenerator.spec.ts b/test/core/format/IdGenerator.spec.ts index f81cbc14c4..96d6a55ef6 100644 --- a/test/core/format/IdGenerator.spec.ts +++ b/test/core/format/IdGenerator.spec.ts @@ -234,18 +234,11 @@ describe('id generator', () => { expect(idGenerator.generateNamespacePath('foo.bar.baz')).to.deep.equal(expected); }); - it('rejects names with too many parts', () => { - // Assert: - ['a.b.c.d', 'a.b.c.d.e'].forEach((name) => - expect(() => idGenerator.generateNamespacePath(name), `name ${name}`).to.throw('too many parts')); - }); - it('rejects improper qualified names', () => { // Assert: ['a:b:c', 'a::b'].forEach((name) => expect(() => idGenerator.generateNamespacePath(name), `name ${name}`).to.throw('invalid part name')); }); - addBasicTests(idGenerator.generateNamespacePath); }); }); diff --git a/test/core/utils/TransactionMapping.spec.ts b/test/core/utils/TransactionMapping.spec.ts index 5bf7987125..e161b42e75 100644 --- a/test/core/utils/TransactionMapping.spec.ts +++ b/test/core/utils/TransactionMapping.spec.ts @@ -22,7 +22,6 @@ import { TransactionMapping } from '../../../src/core/utils/TransactionMapping'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; import { PublicAccount } from '../../../src/model/account/PublicAccount'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { EncryptedMessage } from '../../../src/model/message/EncryptedMessage'; import { MessageType } from '../../../src/model/message/MessageType'; import { PlainMessage } from '../../../src/model/message/PlainMessage'; @@ -35,6 +34,7 @@ import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyL import { AliasAction } from '../../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; import { NamespaceRegistrationType } from '../../../src/model/namespace/NamespaceRegistrationType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { AccountRestrictionModificationAction } from '../../../src/model/restriction/AccountRestrictionModificationAction'; import { AccountRestrictionFlags } from '../../../src/model/restriction/AccountRestrictionType'; import { MosaicRestrictionType } from '../../../src/model/restriction/MosaicRestrictionType'; diff --git a/test/core/utils/UnresolvedMapping.spec.ts b/test/core/utils/UnresolvedMapping.spec.ts index d8df75651f..1740d081d7 100644 --- a/test/core/utils/UnresolvedMapping.spec.ts +++ b/test/core/utils/UnresolvedMapping.spec.ts @@ -17,9 +17,9 @@ import { expect } from 'chai'; import { Convert, RawAddress } from '../../../src/core/format'; import { UnresolvedMapping } from '../../../src/core/utils/UnresolvedMapping'; import { Address } from '../../../src/model/account/Address'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; describe('UnresolvedMapping', () => { let mosaicId: MosaicId; diff --git a/test/infrastructure/BlockHttp.spec.ts b/test/infrastructure/BlockHttp.spec.ts new file mode 100644 index 0000000000..a0e8a8deef --- /dev/null +++ b/test/infrastructure/BlockHttp.spec.ts @@ -0,0 +1,170 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { expect } from 'chai'; +import * as http from 'http'; +import { + BlockDTO, + BlockInfoDTO, + BlockMetaDTO, + BlockRoutesApi, + MerklePathItemDTO, + MerkleProofInfoDTO, + NetworkTypeEnum, + PositionEnum, +} from 'symbol-openapi-typescript-node-client'; +import { instance, mock, reset, when } from 'ts-mockito'; +import { DtoMapping } from '../../src/core/utils/DtoMapping'; +import { BlockHttp } from '../../src/infrastructure/BlockHttp'; +import { BlockRepository } from '../../src/infrastructure/BlockRepository'; +import { BlockInfo } from '../../src/model/blockchain/BlockInfo'; +import { MerklePathItem } from '../../src/model/blockchain/MerklePathItem'; +import { Transaction } from '../../src/model/transaction/Transaction'; +import { UInt64 } from '../../src/model/UInt64'; + +describe('BlockHttp', () => { + + const blockDTO = new BlockDTO(); + blockDTO.version = 1; + blockDTO.network = NetworkTypeEnum.NUMBER_152; + blockDTO.beneficiaryPublicKey = 'a'; + blockDTO.difficulty = '2'; + blockDTO.feeMultiplier = 3; + blockDTO.height = '4'; + blockDTO.previousBlockHash = '5'; + blockDTO.type = 6; + blockDTO.signerPublicKey = '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7'; + blockDTO.timestamp = '7'; + blockDTO.beneficiaryPublicKey = '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A8'; + + const blockMetaDTO = new BlockMetaDTO(); + blockMetaDTO.generationHash = 'abc'; + blockMetaDTO.hash = 'aHash'; + blockMetaDTO.numStatements = 10; + blockMetaDTO.numTransactions = 20; + blockMetaDTO.totalFee = '30'; + blockMetaDTO.stateHashSubCacheMerkleRoots = ['a', 'b', 'c']; + + const blockInfoDto = new BlockInfoDTO(); + blockInfoDto.block = blockDTO; + blockInfoDto.meta = blockMetaDTO; + + const url = 'http://someHost'; + const response: http.IncomingMessage = mock(); + const blockRoutesApi: BlockRoutesApi = mock(); + const blockRepository: BlockRepository = DtoMapping.assign(new BlockHttp(url), {blockRoutesApi: instance(blockRoutesApi)}); + + const transactionInfoDTO = { + meta: { + hash: '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96', + height: '18160', + id: '5A0069D83F17CF0001777E55', + index: 0, + merkleComponentHash: '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7', + }, + transaction: { + deadline: '1000', + maxFee: '0', + signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', + minApprovalDelta: 1, + minRemovalDelta: 1, + modifications: [ + { + cosignatoryPublicKey: '589B73FBC22063E9AE6FBAC67CB9C6EA865EF556E5' + + 'FB8B7310D45F77C1250B97', + modificationAction: 0, + }, + ], + type: 16725, + version: 1, + network: 144, + }, + }; + + before(() => { + reset(response); + reset(blockRoutesApi); + }); + + function assertBlockInfo(blockInfo: BlockInfo) { + expect(blockInfo).to.be.not.null; + expect(blockInfo.type).to.be.equals(blockInfoDto.block.type); + expect(blockInfo.previousBlockHash).to.be.equals(blockInfoDto.block.previousBlockHash); + expect(blockInfo.height.toString()).to.be.equals(blockInfoDto.block.height); + expect(blockInfo.feeMultiplier).to.be.equals(blockInfoDto.block.feeMultiplier); + expect(blockInfo.networkType).to.be.equals(blockInfoDto.block.network); + expect(blockInfo.version).to.be.equals(blockInfoDto.block.version); + expect(blockInfo.beneficiaryPublicKey!.publicKey).to.be.equals(blockInfoDto.block.beneficiaryPublicKey); + expect(blockInfo.difficulty.toString()).to.be.equals(blockInfoDto.block.difficulty); + expect(blockInfo.feeMultiplier).to.be.equals(blockInfoDto.block.feeMultiplier); + expect(blockInfo.signer!.publicKey).to.be.equals(blockInfoDto.block.signerPublicKey); + expect(blockInfo.signature).to.be.equals(blockInfoDto.block.signature); + + expect(blockInfo.generationHash).to.be.equals(blockInfoDto.meta.generationHash); + expect(blockInfo.hash).to.be.equals(blockInfoDto.meta.hash); + expect(blockInfo.numStatements).to.be.equals(blockInfoDto.meta.numStatements); + expect(blockInfo.numTransactions).to.be.equals(blockInfoDto.meta.numTransactions); + expect(blockInfo.totalFee.toString()).to.be.equals(blockInfoDto.meta.totalFee); + } + + function assertTransaction(transaction: Transaction) { + expect(transaction).to.be.not.null; + expect(transaction.type).to.be.equals(transactionInfoDTO.transaction.type); + expect(transaction.deadline.toString()).to.be.equals(transactionInfoDTO.transaction.deadline); + } + + it('getBlockInfo', async () => { + when(blockRoutesApi.getBlockByHeight('1')).thenReturn(Promise.resolve({response, body: blockInfoDto})); + const blockInfo = await blockRepository.getBlockByHeight(UInt64.fromUint(1)).toPromise(); + assertBlockInfo(blockInfo); + }); + + it('getBlocksByHeightWithLimit', async () => { + when(blockRoutesApi.getBlocksByHeightWithLimit('2', 10)).thenReturn(Promise.resolve({ + response, + body: [blockInfoDto], + })); + const blockInfos = await blockRepository.getBlocksByHeightWithLimit(UInt64.fromUint(2), 10).toPromise(); + assertBlockInfo(blockInfos[0]); + }); + + it('getBlockTransactions', async () => { + when(blockRoutesApi.getBlockTransactions('2', undefined, undefined, undefined)).thenReturn(Promise.resolve({ + response, + body: [transactionInfoDTO], + })); + const transactions = await blockRepository.getBlockTransactions(UInt64.fromUint(2)).toPromise(); + assertTransaction(transactions[0]); + }); + + it('getMerkleTransaction', async () => { + const merkleProofInfoDTO = new MerkleProofInfoDTO(); + const merklePathItemDTO = new MerklePathItemDTO(); + merklePathItemDTO.hash = 'bbb'; + merklePathItemDTO.position = PositionEnum.Left; + merkleProofInfoDTO.merklePath = [merklePathItemDTO]; + + when(blockRoutesApi.getMerkleTransaction('2', 'abc')).thenReturn(Promise.resolve({ + response, + body: merkleProofInfoDTO, + })); + const merkleProofInfo = await blockRepository.getMerkleTransaction(UInt64.fromUint(2), 'abc').toPromise(); + expect(merkleProofInfo).to.be.not.null; + expect(merkleProofInfo.merklePath).to.deep.equals([new MerklePathItem(PositionEnum.Left, 'bbb')]); + }); + +}); diff --git a/test/infrastructure/ChainHttp.spec.ts b/test/infrastructure/ChainHttp.spec.ts new file mode 100644 index 0000000000..502e39869b --- /dev/null +++ b/test/infrastructure/ChainHttp.spec.ts @@ -0,0 +1,56 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { expect } from 'chai'; +import * as http from 'http'; +import { ChainRoutesApi, ChainScoreDTO, HeightInfoDTO, } from 'symbol-openapi-typescript-node-client'; +import { instance, mock, reset, when } from 'ts-mockito'; +import { DtoMapping } from '../../src/core/utils/DtoMapping'; +import { ChainHttp } from '../../src/infrastructure/ChainHttp'; +import { ChainRepository } from '../../src/infrastructure/ChainRepository'; + +describe('ChainHttp', () => { + + const url = 'http://someHost'; + const response: http.IncomingMessage = mock(); + const chainRoutesApi: ChainRoutesApi = mock(); + const chainRepository: ChainRepository = DtoMapping.assign(new ChainHttp(url), {chainRoutesApi: instance(chainRoutesApi)}); + + before(() => { + reset(response); + reset(chainRoutesApi); + }); + + it('getBlockchainHeight', async () => { + const heightInfoDTO = new HeightInfoDTO(); + heightInfoDTO.height = '3'; + when(chainRoutesApi.getChainHeight()).thenReturn(Promise.resolve({response, body: heightInfoDTO})); + const heightInfo = await chainRepository.getBlockchainHeight().toPromise(); + expect(heightInfo).to.be.not.null; + expect(heightInfo.toString()).to.be.equals('3'); + }); + + it('getChainScore', async () => { + const chainScoreDTO = new ChainScoreDTO(); + chainScoreDTO.scoreLow = '2'; + chainScoreDTO.scoreHigh = '3'; + when(chainRoutesApi.getChainScore()).thenReturn(Promise.resolve({response, body: chainScoreDTO})); + const chainScore = await chainRepository.getChainScore().toPromise(); + expect(chainScore).to.be.not.null; + expect(chainScore.scoreLow.toString()).to.be.equals('2'); + expect(chainScore.scoreHigh.toString()).to.be.equals('3'); + }); + +}); diff --git a/test/infrastructure/MetadataHttp.spec.ts b/test/infrastructure/MetadataHttp.spec.ts new file mode 100644 index 0000000000..7ad4c82437 --- /dev/null +++ b/test/infrastructure/MetadataHttp.spec.ts @@ -0,0 +1,216 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { expect } from 'chai'; +import * as http from 'http'; +import { + MetadataDTO, + MetadataEntriesDTO, + MetadataEntryDTO, + MetadataRoutesApi, + MetadataTypeEnum, +} from 'symbol-openapi-typescript-node-client'; +import { instance, mock, reset, when } from 'ts-mockito'; +import { DtoMapping } from '../../src/core/utils/DtoMapping'; +import { MetadataHttp } from '../../src/infrastructure/MetadataHttp'; +import { MetadataRepository } from '../../src/infrastructure/MetadataRepository'; +import { QueryParams } from '../../src/infrastructure/QueryParams'; +import { Address } from '../../src/model/account/Address'; +import { Metadata } from '../../src/model/metadata/Metadata'; +import { MetadataType } from '../../src/model/metadata/MetadataType'; +import { MosaicId } from '../../src/model/mosaic/MosaicId'; +import { NamespaceId } from '../../src/model/namespace/NamespaceId'; + +describe('MetadataHttp', () => { + + const address = Address.createFromRawAddress('MCTVW23D2MN5VE4AQ4TZIDZENGNOZXPRPR72DYSX'); + const mosaicId = new MosaicId('941299B2B7E1291C'); + const namespaceId = new NamespaceId('some.address'); + + const metadataDTOMosaic = new MetadataDTO(); + metadataDTOMosaic.id = 'aaa'; + + const metadataEntryDtoMosaic = new MetadataEntryDTO(); + metadataEntryDtoMosaic.compositeHash = '1'; + metadataEntryDtoMosaic.metadataType = MetadataTypeEnum.NUMBER_1; + metadataEntryDtoMosaic.scopedMetadataKey = '123451234512345A'; + metadataEntryDtoMosaic.senderPublicKey = 'aSenderPublicKey1'; + metadataEntryDtoMosaic.targetPublicKey = 'aTargetPublicKey1'; + metadataEntryDtoMosaic.value = 'value1'; + metadataEntryDtoMosaic.targetId = '941299B2B7E1291C' as any; + metadataDTOMosaic.metadataEntry = metadataEntryDtoMosaic; + + const metadataDTOAddress = new MetadataDTO(); + metadataDTOAddress.id = 'bbb'; + + const metadataEntryDtoAddress = new MetadataEntryDTO(); + metadataEntryDtoAddress.compositeHash = '2'; + metadataEntryDtoAddress.metadataType = MetadataTypeEnum.NUMBER_0; + metadataEntryDtoAddress.scopedMetadataKey = '123451234512345B'; + metadataEntryDtoAddress.senderPublicKey = 'aSenderPublicKey2'; + metadataEntryDtoAddress.targetPublicKey = 'aTargetPublicKey2'; + metadataEntryDtoAddress.value = 'value1'; + metadataEntryDtoAddress.targetId = '941299B2B7E1291D' as any; + metadataDTOAddress.metadataEntry = metadataEntryDtoAddress; + + const metadataDTONamespace = new MetadataDTO(); + metadataDTONamespace.id = 'ccc'; + + const metadataEntryDtoNamespace = new MetadataEntryDTO(); + metadataEntryDtoNamespace.compositeHash = '3'; + metadataEntryDtoNamespace.metadataType = MetadataTypeEnum.NUMBER_2; + metadataEntryDtoNamespace.scopedMetadataKey = '123451234512345C'; + metadataEntryDtoNamespace.senderPublicKey = 'aSenderPublicKey3'; + metadataEntryDtoNamespace.targetPublicKey = 'aTargetPublicKey3'; + metadataEntryDtoNamespace.value = 'value1'; + metadataEntryDtoNamespace.targetId = '941299B2B7E1291E' as any; + metadataDTONamespace.metadataEntry = metadataEntryDtoNamespace; + + const metadataEntriesDTO = new MetadataEntriesDTO(); + metadataEntriesDTO.metadataEntries = [metadataDTOMosaic, metadataDTOAddress, metadataDTONamespace]; + + const url = 'http://someHost'; + const response: http.IncomingMessage = mock(); + const metadataRoutesApi: MetadataRoutesApi = mock(); + const metadataRepository: MetadataRepository = DtoMapping.assign( + new MetadataHttp(url), {metadataRoutesApi: instance(metadataRoutesApi)}); + before(() => { + reset(response); + reset(metadataRoutesApi); + }); + + function assertMetadataInfo(metadataInfo: Metadata, dto: MetadataDTO) { + expect(metadataInfo).to.be.not.null; + expect(metadataInfo.id).to.be.equals(dto.id); + if (metadataInfo.metadataEntry.metadataType === MetadataType.Mosaic) { + expect(metadataInfo.metadataEntry.targetId!.toHex()).to.be.equals(dto.metadataEntry.targetId); + } + if (metadataInfo.metadataEntry.metadataType === MetadataType.Account) { + expect(metadataInfo.metadataEntry.targetId).to.be.undefined; + } + if (metadataInfo.metadataEntry.metadataType === MetadataType.Namespace) { + expect(metadataInfo.metadataEntry.targetId!.toHex()).to.be.equals(dto.metadataEntry.targetId); + } + expect(metadataInfo.metadataEntry.targetPublicKey).to.be.equals(dto.metadataEntry.targetPublicKey); + expect(metadataInfo.metadataEntry.scopedMetadataKey.toHex()).to.be.equals(dto.metadataEntry.scopedMetadataKey); + expect(metadataInfo.metadataEntry.compositeHash).to.be.equals(dto.metadataEntry.compositeHash); + } + + it('getAccountMetadata', async () => { + when(metadataRoutesApi.getAccountMetadata(address.plain(), 1, 'a', '-id')).thenReturn(Promise.resolve({ + response, + body: metadataEntriesDTO, + })); + const metadatas = await metadataRepository.getAccountMetadata(address, new QueryParams({ + pageSize: 1, + id: 'a', + })).toPromise(); + expect(metadatas.length).to.be.equals(3); + assertMetadataInfo(metadatas[0], metadataDTOMosaic); + assertMetadataInfo(metadatas[1], metadataDTOAddress); + assertMetadataInfo(metadatas[2], metadataDTONamespace); + }); + + it('getAccountMetadataByKey', async () => { + when(metadataRoutesApi.getAccountMetadataByKey(address.plain(), 'aaa')).thenReturn(Promise.resolve({ + response, + body: metadataEntriesDTO, + })); + const metadatas = await metadataRepository.getAccountMetadataByKey(address, 'aaa').toPromise(); + assertMetadataInfo(metadatas[0], metadataDTOMosaic); + assertMetadataInfo(metadatas[1], metadataDTOAddress); + assertMetadataInfo(metadatas[2], metadataDTONamespace); + }); + + it('getAccountMetadataByKeyAndSender', async () => { + when(metadataRoutesApi.getAccountMetadataByKeyAndSender(address.plain(), 'aaa', 'sender')).thenReturn(Promise.resolve({ + response, + body: metadataDTOMosaic, + })); + const metadata = await metadataRepository.getAccountMetadataByKeyAndSender(address, 'aaa', 'sender').toPromise(); + assertMetadataInfo(metadata, metadataDTOMosaic); + }); + + it('getMosaicMetadata', async () => { + when(metadataRoutesApi.getMosaicMetadata(mosaicId.toHex(), 1, 'a', '-id')).thenReturn(Promise.resolve({ + response, + body: metadataEntriesDTO, + })); + const metadatas = await metadataRepository.getMosaicMetadata(mosaicId, new QueryParams({ + pageSize: 1, + id: 'a', + })).toPromise(); + expect(metadatas.length).to.be.equals(3); + assertMetadataInfo(metadatas[0], metadataDTOMosaic); + assertMetadataInfo(metadatas[1], metadataDTOAddress); + assertMetadataInfo(metadatas[2], metadataDTONamespace); + }); + + it('getMosaicMetadataByKey', async () => { + when(metadataRoutesApi.getMosaicMetadataByKey(mosaicId.toHex(), 'aaa')).thenReturn(Promise.resolve({ + response, + body: metadataEntriesDTO, + })); + const metadatas = await metadataRepository.getMosaicMetadataByKey(mosaicId, 'aaa').toPromise(); + assertMetadataInfo(metadatas[0], metadataDTOMosaic); + assertMetadataInfo(metadatas[1], metadataDTOAddress); + assertMetadataInfo(metadatas[2], metadataDTONamespace); + }); + + it('getMosaicMetadataByKeyAndSender', async () => { + when(metadataRoutesApi.getMosaicMetadataByKeyAndSender(mosaicId.toHex(), 'aaa', 'sender')).thenReturn(Promise.resolve({ + response, + body: metadataDTOMosaic, + })); + const metadata = await metadataRepository.getMosaicMetadataByKeyAndSender(mosaicId, 'aaa', 'sender').toPromise(); + assertMetadataInfo(metadata, metadataDTOMosaic); + }); + + it('getNamespaceMetadata', async () => { + when(metadataRoutesApi.getNamespaceMetadata(namespaceId.toHex(), 2, 'a', '-id')).thenReturn(Promise.resolve({ + response, + body: metadataEntriesDTO, + })); + const metadatas = await metadataRepository.getNamespaceMetadata(namespaceId, new QueryParams({ + pageSize: 2, + id: 'a', + })).toPromise(); + expect(metadatas.length).to.be.equals(3); + assertMetadataInfo(metadatas[0], metadataDTOMosaic); + assertMetadataInfo(metadatas[1], metadataDTOAddress); + assertMetadataInfo(metadatas[2], metadataDTONamespace); + }); + + it('getNamespaceMetadataByKey', async () => { + when(metadataRoutesApi.getNamespaceMetadataByKey(namespaceId.toHex(), 'bbb')).thenReturn(Promise.resolve({ + response, + body: metadataEntriesDTO, + })); + const metadatas = await metadataRepository.getNamespaceMetadataByKey(namespaceId, 'bbb').toPromise(); + assertMetadataInfo(metadatas[0], metadataDTOMosaic); + assertMetadataInfo(metadatas[1], metadataDTOAddress); + assertMetadataInfo(metadatas[2], metadataDTONamespace); + }); + + it('getNamespaceMetadataByKeyAndSender', async () => { + when(metadataRoutesApi.getNamespaceMetadataByKeyAndSender(namespaceId.toHex(), 'cccc', 'sender1')).thenReturn(Promise.resolve({ + response, + body: metadataDTOMosaic, + })); + const metadata = await metadataRepository.getNamespaceMetadataByKeyAndSender(namespaceId, 'cccc', 'sender1').toPromise(); + assertMetadataInfo(metadata, metadataDTOMosaic); + }); + +}); diff --git a/test/infrastructure/MosaicHttp.spec.ts b/test/infrastructure/MosaicHttp.spec.ts new file mode 100644 index 0000000000..715095e28d --- /dev/null +++ b/test/infrastructure/MosaicHttp.spec.ts @@ -0,0 +1,143 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { expect } from 'chai'; +import * as http from 'http'; +import { + Mosaic, + MosaicRoutesApi, + MosaicInfoDTO, + MosaicDTO, + MosaicsInfoDTO, + MosaicIds, +} from 'symbol-openapi-typescript-node-client'; +import { instance, mock, reset, when, deepEqual } from 'ts-mockito'; +import { DtoMapping } from '../../src/core/utils/DtoMapping'; +import { MosaicRepository } from '../../src/infrastructure/MosaicRepository'; +import { MosaicHttp } from '../../src/infrastructure/MosaicHttp'; +import { NetworkType } from '../../src/model/network/NetworkType'; +import { MosaicId } from '../../src/model/mosaic/MosaicId'; +import { MosaicInfo } from '../../src/model/mosaic/MosaicInfo'; +import { PublicAccount } from '../../src/model/account/PublicAccount'; +import { AccountIds } from 'symbol-openapi-typescript-node-client'; +import { assert } from 'chai'; + +describe('MosaicHttp', () => { + + const publicAccount = + PublicAccount.createFromPublicKey('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B6', NetworkType.MIJIN_TEST); + const address = publicAccount.address; + const mosaicId = new MosaicId('941299B2B7E1291C'); + const mosaic = new Mosaic(); + mosaic.amount = '777'; + mosaic.id = mosaicId.toHex(); + + const mosaicDto = new MosaicDTO(); + mosaicDto.divisibility = 6; + mosaicDto.duration = '10'; + mosaicDto.flags = 1; + mosaicDto.id = mosaicId.toHex(); + mosaicDto.ownerAddress = address.encoded(); + mosaicDto.ownerPublicKey = publicAccount.publicKey; + mosaicDto.revision = 0; + mosaicDto.startHeight = '1'; + mosaicDto.supply = '100'; + + const mosaicInfoDto = new MosaicInfoDTO(); + const mosaicsInfoDto = new MosaicsInfoDTO(); + mosaicInfoDto.mosaic = mosaicDto; + mosaicsInfoDto.mosaics = [mosaicDto]; + + const url = 'http://someHost'; + const response: http.IncomingMessage = mock(); + const mosaicRoutesApi: MosaicRoutesApi = mock(); + const mosaicRepository: MosaicRepository = DtoMapping.assign(new MosaicHttp(url, NetworkType.MIJIN_TEST), + {mosaicRoutesApi: instance(mosaicRoutesApi)}); + + before(() => { + reset(response); + reset(mosaicRoutesApi); + }); + + function assertMosaicInfo(mosaicInfo: MosaicInfo) { + expect(mosaicInfo).to.be.not.null; + expect(mosaicInfo.divisibility).to.be.equals(6); + expect(mosaicInfo.duration.toString()).to.be.equals(mosaicDto.duration); + expect(mosaicInfo.flags.getValue()).to.be.equals(mosaicDto.flags); + expect(mosaicInfo.height.toString()).to.be.equals(mosaicDto.startHeight); + expect(mosaicInfo.supply.toString()).to.be.equals(mosaicDto.supply); + expect(mosaicInfo.owner.publicKey).to.be.equals(mosaicDto.ownerPublicKey); + expect(mosaicInfo.owner.address.encoded()).to.be.equals(mosaicDto.ownerAddress); + expect(mosaicInfo.revision).to.be.equals(mosaicDto.revision); + expect(mosaicInfo.id.toHex()).to.be.equals(mosaicId.toHex()); + } + + it('getMosaic', async () => { + when(mosaicRoutesApi.getMosaic(mosaicId.toHex())).thenReturn(Promise.resolve({response, body: mosaicInfoDto})); + const mosaicInfo = await mosaicRepository.getMosaic(mosaicId).toPromise(); + assertMosaicInfo(mosaicInfo); + }); + + it('getMosaics', async () => { + const mosaicIds = new MosaicIds(); + mosaicIds.mosaicIds = [mosaicId.toHex()]; + when(mosaicRoutesApi.getMosaics(deepEqual(mosaicIds))).thenReturn(Promise.resolve({response, body: [mosaicInfoDto]})); + const mosaicInfos = await mosaicRepository.getMosaics([mosaicId]).toPromise(); + assertMosaicInfo(mosaicInfos[0]); + }); + + it('getMosaicsFromAccount', async () => { + when(mosaicRoutesApi.getMosaicsFromAccount(address.plain())).thenReturn(Promise.resolve({response, body: mosaicsInfoDto})); + const mosaicsInfo = await mosaicRepository.getMosaicsFromAccount(address).toPromise(); + assertMosaicInfo(mosaicsInfo[0]); + }); + + it('getMosaicsFromAccounts', async () => { + const accountIds = new AccountIds(); + accountIds.addresses = [address.plain()]; + when(mosaicRoutesApi.getMosaicsFromAccounts(deepEqual(accountIds))) + .thenReturn(Promise.resolve({response, body: mosaicsInfoDto})); + const mosaicsInfo = await mosaicRepository.getMosaicsFromAccounts([address]).toPromise(); + assertMosaicInfo(mosaicsInfo[0]); + }); + + it('getMosaic - Error', async () => { + when(mosaicRoutesApi.getMosaic(mosaicId.toHex())).thenThrow(new Error('Mocked Error')); + await mosaicRepository.getMosaic(mosaicId).toPromise().catch((error) => + expect(error).not.to.be.undefined); + }); + + it('getMosaics - Error', async () => { + const mosaicIds = new MosaicIds(); + mosaicIds.mosaicIds = [mosaicId.toHex()]; + when(mosaicRoutesApi.getMosaics(deepEqual(mosaicIds))).thenThrow(new Error('Mocked Error')); + await mosaicRepository.getMosaics([mosaicId]).toPromise().catch((error) => + expect(error).not.to.be.undefined); + }); + + it('getMosaicsFromAccount - Error', async () => { + when(mosaicRoutesApi.getMosaicsFromAccount(address.plain())).thenThrow(new Error('Mocked Error')); + await mosaicRepository.getMosaicsFromAccount(address).toPromise().catch((error) => + expect(error).not.to.be.undefined); + }); + + it('getMosaicsFromAccounts - Error', async () => { + const accountIds = new AccountIds(); + accountIds.addresses = [address.plain()]; + when(mosaicRoutesApi.getMosaicsFromAccounts(deepEqual(accountIds))).thenThrow(new Error('Mocked Error')); + await mosaicRepository.getMosaicsFromAccounts([address]).toPromise().catch((error) => + expect(error).not.to.be.undefined); + }); +}); diff --git a/test/infrastructure/NetworkHttp.spec.ts b/test/infrastructure/NetworkHttp.spec.ts index 545fd77d6e..9e61d08b54 100644 --- a/test/infrastructure/NetworkHttp.spec.ts +++ b/test/infrastructure/NetworkHttp.spec.ts @@ -15,12 +15,35 @@ */ import { expect } from 'chai'; import * as http from 'http'; -import { NetworkFeesDTO, NetworkRoutesApi, NetworkTypeDTO, NodeInfoDTO, NodeRoutesApi } from 'symbol-openapi-typescript-node-client'; +import { NetworkRoutesApi, + NetworkTypeDTO, + NodeInfoDTO, + NodeRoutesApi, + TransactionFeesDTO, + RentalFeesDTO, + NetworkConfigurationDTO, + NetworkPropertiesDTO, + NodeIdentityEqualityStrategy, + ChainPropertiesDTO, + PluginsPropertiesDTO, + AccountLinkNetworkPropertiesDTO, + AggregateNetworkPropertiesDTO, + HashLockNetworkPropertiesDTO, + SecretLockNetworkPropertiesDTO, + MetadataNetworkPropertiesDTO, + MosaicNetworkPropertiesDTO, + MultisigNetworkPropertiesDTO, + NamespaceNetworkPropertiesDTO, + AccountRestrictionNetworkPropertiesDTO, + MosaicRestrictionNetworkPropertiesDTO, + TransferNetworkPropertiesDTO } from 'symbol-openapi-typescript-node-client'; import { instance, mock, reset, when } from 'ts-mockito'; import { DtoMapping } from '../../src/core/utils/DtoMapping'; import { NetworkHttp } from '../../src/infrastructure/NetworkHttp'; import { NodeHttp } from '../../src/infrastructure/NodeHttp'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../src/model/network/NetworkType'; +import { deepEqual } from 'assert'; +import * as testResources from '../resource/TestResources'; describe('NetworkHttp', () => { const url = 'http://someHost'; @@ -40,17 +63,17 @@ describe('NetworkHttp', () => { reset(networkRoutesApi); }); - it('getNetworkFees', async () => { + it('getTransactionFees', async () => { - const body = new NetworkFeesDTO(); + const body = new TransactionFeesDTO(); body.averageFeeMultiplier = 1; body.highestFeeMultiplier = 2; body.lowestFeeMultiplier = 3; body.medianFeeMultiplier = 4; - when(networkRoutesApi.getNetworkFees()).thenReturn(Promise.resolve({response, body})); + when(networkRoutesApi.getTransactionFees()).thenReturn(Promise.resolve({response, body})); - const networkFees = await networkRepository.getNetworkFees().toPromise(); + const networkFees = await networkRepository.getTransactionFees().toPromise(); expect(networkFees).to.be.not.null; expect(networkFees.averageFeeMultiplier).to.be.equals(1); expect(networkFees.highestFeeMultiplier).to.be.equals(2); @@ -58,6 +81,22 @@ describe('NetworkHttp', () => { expect(networkFees.medianFeeMultiplier).to.be.equals(4); }); + it('getRentalFees', async () => { + + const body = new RentalFeesDTO(); + body.effectiveChildNamespaceRentalFee = '1'; + body.effectiveMosaicRentalFee = '2'; + body.effectiveRootNamespaceRentalFeePerBlock = '3'; + + when(networkRoutesApi.getRentalFees()).thenReturn(Promise.resolve({response, body})); + + const rentalFees = await networkRepository.getRentalFees().toPromise(); + expect(rentalFees).to.be.not.null; + expect(rentalFees.effectiveChildNamespaceRentalFee.toString()).to.be.equals('1'); + expect(rentalFees.effectiveMosaicRentalFee.toString()).to.be.equals('2'); + expect(rentalFees.effectiveRootNamespaceRentalFeePerBlock.toString()).to.be.equals('3'); + }); + it('getNetworkType', async () => { const body = new NodeInfoDTO(); @@ -82,4 +121,114 @@ describe('NetworkHttp', () => { expect(networkName.name).to.be.equals(body.name); }); + it('getNetworkProperties', async () => { + + const body = new NetworkConfigurationDTO(); + + const network = new NetworkPropertiesDTO(); + network.identifier = 'id'; + network.nodeEqualityStrategy = NodeIdentityEqualityStrategy.Host; + network.publicKey = 'pubKey'; + network.generationHash = 'genHash'; + network.epochAdjustment = '123456'; + + const chain = new ChainPropertiesDTO(); + chain.blockGenerationTargetTime = '1'; + chain.blockPruneInterval = '1'; + chain.blockTimeSmoothingFactor = '1'; + chain.currencyMosaicId = '1111111111111111'; + chain.defaultDynamicFeeMultiplier = '1'; + chain.enableVerifiableReceipts = true; + chain.enableVerifiableState = true; + chain.harvestBeneficiaryPercentage = '1'; + chain.harvestingMosaicId = '2222222222222222'; + chain.importanceActivityPercentage = '1'; + chain.importanceGrouping = '1'; + chain.initialCurrencyAtomicUnits = '1'; + chain.maxBlockFutureTime = '1'; + chain.maxDifficultyBlocks = '1'; + chain.maxHarvesterBalance = '1'; + chain.maxMosaicAtomicUnits = '1'; + chain.maxRollbackBlocks = '1'; + chain.maxTransactionLifetime = '1'; + chain.maxTransactionsPerBlock = '1'; + chain.minHarvesterBalance = '1'; + chain.totalChainImportance = '1'; + + const plugin = new PluginsPropertiesDTO(); + plugin.accountlink = new AccountLinkNetworkPropertiesDTO(); + plugin.accountlink.dummy = 'dummy'; + + plugin.aggregate = new AggregateNetworkPropertiesDTO(); + plugin.aggregate.enableBondedAggregateSupport = true; + plugin.aggregate.enableStrictCosignatureCheck = true; + plugin.aggregate.maxBondedTransactionLifetime = '1'; + plugin.aggregate.maxCosignaturesPerAggregate = '1'; + plugin.aggregate.maxTransactionsPerAggregate = '1'; + + plugin.lockhash = new HashLockNetworkPropertiesDTO(); + plugin.lockhash.lockedFundsPerAggregate = '1'; + plugin.lockhash.maxHashLockDuration = '1'; + + plugin.locksecret = new SecretLockNetworkPropertiesDTO(); + plugin.locksecret.maxProofSize = '1'; + plugin.locksecret.maxSecretLockDuration = '1'; + plugin.locksecret.minProofSize = '1'; + + plugin.metadata = new MetadataNetworkPropertiesDTO(); + plugin.metadata.maxValueSize = '1'; + + plugin.mosaic = new MosaicNetworkPropertiesDTO(); + plugin.mosaic.maxMosaicDivisibility = '1'; + plugin.mosaic.maxMosaicDuration = '1'; + plugin.mosaic.maxMosaicsPerAccount = '1'; + plugin.mosaic.mosaicRentalFee = '1'; + plugin.mosaic.mosaicRentalFeeSinkPublicKey = '1'; + + plugin.multisig = new MultisigNetworkPropertiesDTO(); + plugin.multisig.maxCosignatoriesPerAccount = '1'; + plugin.multisig.maxCosignedAccountsPerAccount = '1'; + plugin.multisig.maxMultisigDepth = '1'; + + plugin.namespace = new NamespaceNetworkPropertiesDTO(); + plugin.namespace.childNamespaceRentalFee = '1'; + plugin.namespace.maxChildNamespaces = '1'; + plugin.namespace.maxNameSize = '1'; + plugin.namespace.maxNamespaceDepth = '1'; + plugin.namespace.maxNamespaceDuration = '1'; + plugin.namespace.minNamespaceDuration = '1'; + plugin.namespace.namespaceGracePeriodDuration = '1'; + plugin.namespace.namespaceRentalFeeSinkPublicKey = '1'; + plugin.namespace.reservedRootNamespaceNames = '1'; + plugin.namespace.rootNamespaceRentalFeePerBlock = '1'; + + plugin.restrictionaccount = new AccountRestrictionNetworkPropertiesDTO(); + plugin.restrictionaccount.maxAccountRestrictionValues = '1'; + + plugin.restrictionmosaic = new MosaicRestrictionNetworkPropertiesDTO(); + plugin.restrictionmosaic.maxMosaicRestrictionValues = '1'; + + plugin.transfer = new TransferNetworkPropertiesDTO(); + plugin.transfer.maxMessageSize = '1'; + + body.chain = chain; + body.network = network; + body.plugins = plugin; + + when(networkRoutesApi.getNetworkProperties()).thenReturn(Promise.resolve({response, body})); + + const networkProperties = await networkRepository.getNetworkProperties().toPromise(); + deepEqual(networkProperties.network, body.network); + deepEqual(networkProperties.chain, body.chain); + deepEqual(networkProperties.plugins, body.plugins); + }); + + it('getNetworkProperties - using rest json payload', async () => { + const body = testResources.getDummyNetworkProperties(); + when(networkRoutesApi.getNetworkProperties()).thenReturn(Promise.resolve({response, body})); + const networkProperties = await networkRepository.getNetworkProperties().toPromise(); + deepEqual(networkProperties.network, body.network); + deepEqual(networkProperties.chain, body.chain); + deepEqual(networkProperties.plugins, body.plugins); + }); }); diff --git a/test/infrastructure/NodeHttp.spec.ts b/test/infrastructure/NodeHttp.spec.ts index db62b06607..52ce4dbc82 100644 --- a/test/infrastructure/NodeHttp.spec.ts +++ b/test/infrastructure/NodeHttp.spec.ts @@ -31,7 +31,7 @@ import { import { instance, mock, reset, when } from 'ts-mockito'; import { DtoMapping } from '../../src/core/utils/DtoMapping'; import { NodeHttp } from '../../src/infrastructure/NodeHttp'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../src/model/network/NetworkType'; describe('NodeHttp', () => { @@ -162,7 +162,7 @@ describe('NodeHttp', () => { it('getStorageInfo on Exception', async () => { when(nodeRoutesApi.getNodeStorage()).thenReturn(Promise.reject({ - response: {statusCode: 500, statusMessage: 'Some Error', body: 'The Body',}, + response: {statusCode: 500, statusMessage: 'Some Error', body: 'The Body'}, })); try { await nodeRepository.getStorageInfo().toPromise(); diff --git a/test/infrastructure/RepositoryFactory.spec.ts b/test/infrastructure/RepositoryFactory.spec.ts index 9400c71815..269960b59a 100644 --- a/test/infrastructure/RepositoryFactory.spec.ts +++ b/test/infrastructure/RepositoryFactory.spec.ts @@ -21,7 +21,7 @@ import { BlockRepository } from '../../src/infrastructure/BlockRepository'; import { NetworkRepository } from '../../src/infrastructure/NetworkRepository'; import { RepositoryFactoryHttp } from '../../src/infrastructure/RepositoryFactoryHttp'; import { BlockInfo } from '../../src/model/blockchain/BlockInfo'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { UInt64 } from '../../src/model/UInt64'; describe('RepositoryFactory', () => { diff --git a/test/infrastructure/SerializeTransactionToJSON.spec.ts b/test/infrastructure/SerializeTransactionToJSON.spec.ts index 49c0275d1a..e94620a4e8 100644 --- a/test/infrastructure/SerializeTransactionToJSON.spec.ts +++ b/test/infrastructure/SerializeTransactionToJSON.spec.ts @@ -20,7 +20,6 @@ import { Convert as convert } from '../../src/core/format'; import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; import { PublicAccount } from '../../src/model/account/PublicAccount'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; @@ -29,6 +28,7 @@ import { MosaicSupplyChangeAction } from '../../src/model/mosaic/MosaicSupplyCha import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AccountRestrictionFlags } from '../../src/model/restriction/AccountRestrictionType'; import { AccountLinkTransaction } from '../../src/model/transaction/AccountLinkTransaction'; import { AccountRestrictionTransaction } from '../../src/model/transaction/AccountRestrictionTransaction'; diff --git a/test/infrastructure/TransactionHttp.spec.ts b/test/infrastructure/TransactionHttp.spec.ts index 1a82929076..dcee18bdfa 100644 --- a/test/infrastructure/TransactionHttp.spec.ts +++ b/test/infrastructure/TransactionHttp.spec.ts @@ -27,8 +27,8 @@ import { deepEqual, instance, mock, when } from 'ts-mockito'; import { TransactionHttp } from '../../src/infrastructure/TransactionHttp'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { TransferTransaction } from '../../src/model/transaction/TransferTransaction'; diff --git a/test/infrastructure/receipt/CreateReceiptFromDTO.spec.ts b/test/infrastructure/receipt/CreateReceiptFromDTO.spec.ts index 9d84277290..20f4047ed1 100644 --- a/test/infrastructure/receipt/CreateReceiptFromDTO.spec.ts +++ b/test/infrastructure/receipt/CreateReceiptFromDTO.spec.ts @@ -19,9 +19,9 @@ import { expect } from 'chai'; import { CreateStatementFromDTO } from '../../../src/infrastructure/receipt/CreateReceiptFromDTO'; import {Account} from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptType } from '../../../src/model/receipt/ReceiptType'; import { UInt64 } from '../../../src/model/UInt64'; diff --git a/test/model/account/Account.spec.ts b/test/model/account/Account.spec.ts index 3b0cdc12c0..183a366393 100644 --- a/test/model/account/Account.spec.ts +++ b/test/model/account/Account.spec.ts @@ -17,7 +17,7 @@ import {expect} from 'chai'; import { Convert } from '../../../src/core/format/Convert'; import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../../src/model/network/NetworkType'; describe('Account', () => { const accountInformation = { diff --git a/test/model/account/AccountInfo.spec.ts b/test/model/account/AccountInfo.spec.ts index aea56c7d3f..775fa89194 100644 --- a/test/model/account/AccountInfo.spec.ts +++ b/test/model/account/AccountInfo.spec.ts @@ -20,9 +20,9 @@ import {AccountInfo} from '../../../src/model/account/AccountInfo'; import { ActivityBucket } from '../../../src/model/account/ActivityBucket'; import {Address} from '../../../src/model/account/Address'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {Mosaic} from '../../../src/model/mosaic/Mosaic'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {UInt64} from '../../../src/model/UInt64'; describe('AccountInfo', () => { diff --git a/test/model/account/Address.spec.ts b/test/model/account/Address.spec.ts index 0578e7d522..ca7db5c9bd 100644 --- a/test/model/account/Address.spec.ts +++ b/test/model/account/Address.spec.ts @@ -17,7 +17,7 @@ import { expect } from 'chai'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; const Address_Decoded_Size = 25; diff --git a/test/model/account/MultisigAccountGraphInfo.spec.ts b/test/model/account/MultisigAccountGraphInfo.spec.ts index 0965eaf87a..45df95e7cd 100644 --- a/test/model/account/MultisigAccountGraphInfo.spec.ts +++ b/test/model/account/MultisigAccountGraphInfo.spec.ts @@ -19,7 +19,7 @@ import {expect} from 'chai'; import {MultisigAccountGraphInfo} from '../../../src/model/account/MultisigAccountGraphInfo'; import {MultisigAccountInfo} from '../../../src/model/account/MultisigAccountInfo'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../../src/model/network/NetworkType'; describe('MultisigAccountGraphInfo', () => { diff --git a/test/model/account/MultisigAccountInfo.spec.ts b/test/model/account/MultisigAccountInfo.spec.ts index 3b92e3415f..54f27d5ede 100644 --- a/test/model/account/MultisigAccountInfo.spec.ts +++ b/test/model/account/MultisigAccountInfo.spec.ts @@ -17,7 +17,7 @@ import {expect} from 'chai'; import {MultisigAccountInfo} from '../../../src/model/account/MultisigAccountInfo'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../../src/model/network/NetworkType'; describe('MultisigAccountInfo', () => { const multisigAccountInfoDTO = { diff --git a/test/model/account/PublicAccount.spec.ts b/test/model/account/PublicAccount.spec.ts index f6f742a61e..4dd719f29e 100644 --- a/test/model/account/PublicAccount.spec.ts +++ b/test/model/account/PublicAccount.spec.ts @@ -17,7 +17,7 @@ import { expect } from 'chai'; import { Account } from '../../../src/model/account/Account'; import { PublicAccount } from '../../../src/model/account/PublicAccount'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; describe('PublicAccount', () => { const publicKey = 'b4f12e7c9f6946091e2cb8b6d3a12b50d17ccbbf646386ea27ce2946a7423dcf'; diff --git a/test/model/message/PersistentHarvestingDelegationMessage.spec.ts b/test/model/message/PersistentHarvestingDelegationMessage.spec.ts index cabccca84b..c76c879e2a 100644 --- a/test/model/message/PersistentHarvestingDelegationMessage.spec.ts +++ b/test/model/message/PersistentHarvestingDelegationMessage.spec.ts @@ -16,9 +16,9 @@ import {expect} from 'chai'; import {Account} from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { MessageType } from '../../../src/model/message/MessageType'; import {PersistentHarvestingDelegationMessage} from '../../../src/model/message/PersistentHarvestingDelegationMessage'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { PersistentDelegationRequestTransaction } from '../../../src/model/transaction/PersistentDelegationRequestTransaction'; diff --git a/test/model/mosaic/MosaicAmountView.spec.ts b/test/model/mosaic/MosaicAmountView.spec.ts index 04544aed14..72bbab4cdd 100644 --- a/test/model/mosaic/MosaicAmountView.spec.ts +++ b/test/model/mosaic/MosaicAmountView.spec.ts @@ -16,10 +16,10 @@ import {expect} from 'chai'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicFlags} from '../../../src/model/mosaic/MosaicFlags'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import {MosaicInfo} from '../../../src/model/mosaic/MosaicInfo'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {UInt64} from '../../../src/model/UInt64'; import {MosaicAmountView} from '../../../src/service/MosaicAmountView'; diff --git a/test/model/mosaic/MosaicId.spec.ts b/test/model/mosaic/MosaicId.spec.ts index 1ba7c5670b..cc4fdfa9dc 100644 --- a/test/model/mosaic/MosaicId.spec.ts +++ b/test/model/mosaic/MosaicId.spec.ts @@ -15,10 +15,11 @@ */ import { deepEqual } from 'assert'; import { PublicAccount } from '../../../src/model/account/PublicAccount'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { Id } from '../../../src/model/Id'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { MosaicNonce } from '../../../src/model/mosaic/MosaicNonce'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { expect } from 'chai'; describe('MosaicId', () => { const publicKey = 'b4f12e7c9f6946091e2cb8b6d3a12b50d17ccbbf646386ea27ce2946a7423dcf'; @@ -46,4 +47,10 @@ describe('MosaicId', () => { deepEqual(id1.id, id2.id); }); + + it('should throw invalid size', () => { + expect(() => { + new MosaicId('85BBEA6CC462B24499'); + }).to.throw(Error, 'Invalid size for MosaicId hexadecimal notation'); + }); }); diff --git a/test/model/mosaic/MosaicInfo.spec.ts b/test/model/mosaic/MosaicInfo.spec.ts index 10f2069328..6439174a05 100644 --- a/test/model/mosaic/MosaicInfo.spec.ts +++ b/test/model/mosaic/MosaicInfo.spec.ts @@ -17,10 +17,10 @@ import {deepEqual} from 'assert'; import {expect} from 'chai'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicFlags} from '../../../src/model/mosaic/MosaicFlags'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import {MosaicInfo} from '../../../src/model/mosaic/MosaicInfo'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {UInt64} from '../../../src/model/UInt64'; describe('MosaicInfo', () => { diff --git a/test/model/mosaic/MosaicView.spec.ts b/test/model/mosaic/MosaicView.spec.ts index 5d19187a0b..996db20578 100644 --- a/test/model/mosaic/MosaicView.spec.ts +++ b/test/model/mosaic/MosaicView.spec.ts @@ -16,10 +16,10 @@ import {expect} from 'chai'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import { MosaicFlags } from '../../../src/model/mosaic/MosaicFlags'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import {MosaicInfo} from '../../../src/model/mosaic/MosaicInfo'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {UInt64} from '../../../src/model/UInt64'; import {MosaicView} from '../../../src/service/MosaicView'; diff --git a/test/model/namespace/Alias.spec.ts b/test/model/namespace/Alias.spec.ts index 996e64ef1c..669ade46d7 100644 --- a/test/model/namespace/Alias.spec.ts +++ b/test/model/namespace/Alias.spec.ts @@ -17,13 +17,13 @@ import {deepEqual} from 'assert'; import {expect} from 'chai'; import {Address} from '../../../src/model/account/Address'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import {AddressAlias} from '../../../src/model/namespace/AddressAlias'; import {Alias} from '../../../src/model/namespace/Alias'; import {AliasType} from '../../../src/model/namespace/AliasType'; import {EmptyAlias} from '../../../src/model/namespace/EmptyAlias'; import {MosaicAlias} from '../../../src/model/namespace/MosaicAlias'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {UInt64} from '../../../src/model/UInt64'; describe('Alias', () => { diff --git a/test/model/namespace/NamespaceInfo.spec.ts b/test/model/namespace/NamespaceInfo.spec.ts index e0a4457905..e63a5f0149 100644 --- a/test/model/namespace/NamespaceInfo.spec.ts +++ b/test/model/namespace/NamespaceInfo.spec.ts @@ -17,10 +17,10 @@ import {deepEqual} from 'assert'; import {expect} from 'chai'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; import {NamespaceInfo} from '../../../src/model/namespace/NamespaceInfo'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {UInt64} from '../../../src/model/UInt64'; describe('NamespaceInfo', () => { diff --git a/test/model/blockchain/NetworkType.spec.ts b/test/model/network/NetworkType.spec.ts similarity index 94% rename from test/model/blockchain/NetworkType.spec.ts rename to test/model/network/NetworkType.spec.ts index 13e9fff664..d018a5445d 100644 --- a/test/model/blockchain/NetworkType.spec.ts +++ b/test/model/network/NetworkType.spec.ts @@ -15,7 +15,7 @@ */ import {expect} from 'chai'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../../src/model/network/NetworkType'; describe('NetworkType', () => { it('MAIN_NET is 0x68', () => { diff --git a/test/model/receipt/Receipt.spec.ts b/test/model/receipt/Receipt.spec.ts index 0c80ea03d4..3ad33b82ca 100644 --- a/test/model/receipt/Receipt.spec.ts +++ b/test/model/receipt/Receipt.spec.ts @@ -23,9 +23,9 @@ import { import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; import { PublicAccount } from '../../../src/model/account/PublicAccount'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ArtifactExpiryReceipt } from '../../../src/model/receipt/ArtifactExpiryReceipt'; import { BalanceChangeReceipt } from '../../../src/model/receipt/BalanceChangeReceipt'; import { BalanceTransferReceipt } from '../../../src/model/receipt/BalanceTransferReceipt'; diff --git a/test/model/receipt/ResolutionStatement.spec.ts b/test/model/receipt/ResolutionStatement.spec.ts index 9649864236..5a6b092680 100644 --- a/test/model/receipt/ResolutionStatement.spec.ts +++ b/test/model/receipt/ResolutionStatement.spec.ts @@ -17,8 +17,8 @@ import { expect } from 'chai'; import { CreateStatementFromDTO } from '../../../src/infrastructure/receipt/CreateReceiptFromDTO'; import { Account } from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { Address, MosaicId, NamespaceId, ResolutionType } from '../../../src/model/model'; +import { NetworkType } from '../../../src/model/network/NetworkType'; describe('ResolutionStatement', () => { let account: Account; diff --git a/test/model/receipt/Statement.spec.ts b/test/model/receipt/Statement.spec.ts index c0d99f5f3c..d26b413f74 100644 --- a/test/model/receipt/Statement.spec.ts +++ b/test/model/receipt/Statement.spec.ts @@ -18,8 +18,8 @@ import { expect } from 'chai'; import { UnresolvedMapping } from '../../../src/core/utils/UnresolvedMapping'; import { CreateStatementFromDTO } from '../../../src/infrastructure/receipt/CreateReceiptFromDTO'; import { Account } from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { Address, MosaicId, NamespaceId, ResolutionType } from '../../../src/model/model'; +import { NetworkType } from '../../../src/model/network/NetworkType'; describe('Statement', () => { let account: Account; diff --git a/test/model/transaction/AccountLinkTransaction.spec.ts b/test/model/transaction/AccountLinkTransaction.spec.ts index 72c2826b22..889d7a6e86 100644 --- a/test/model/transaction/AccountLinkTransaction.spec.ts +++ b/test/model/transaction/AccountLinkTransaction.spec.ts @@ -17,7 +17,7 @@ import { expect } from 'chai'; import {Convert} from '../../../src/core/format'; import { Account } from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { AccountLinkTransaction } from '../../../src/model/transaction/AccountLinkTransaction'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { LinkAction } from '../../../src/model/transaction/LinkAction'; diff --git a/test/model/transaction/AccountMetadataTransaction.spec.ts b/test/model/transaction/AccountMetadataTransaction.spec.ts index 4defc457f3..d9dda03acc 100644 --- a/test/model/transaction/AccountMetadataTransaction.spec.ts +++ b/test/model/transaction/AccountMetadataTransaction.spec.ts @@ -17,7 +17,7 @@ import { expect } from 'chai'; import { Convert } from '../../../src/core/format/Convert'; import { Account } from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { AccountMetadataTransaction } from '../../../src/model/transaction/AccountMetadataTransaction'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { UInt64 } from '../../../src/model/UInt64'; diff --git a/test/model/transaction/AccountRestrictionTransaction.spec.ts b/test/model/transaction/AccountRestrictionTransaction.spec.ts index 7ce075a035..461c078df6 100644 --- a/test/model/transaction/AccountRestrictionTransaction.spec.ts +++ b/test/model/transaction/AccountRestrictionTransaction.spec.ts @@ -18,8 +18,8 @@ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; import {Address} from '../../../src/model/account/Address'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import { AccountRestrictionModificationAction } from '../../../src/model/restriction/AccountRestrictionModificationAction'; import { AccountRestrictionFlags } from '../../../src/model/restriction/AccountRestrictionType'; import { AccountRestrictionModification } from '../../../src/model/transaction/AccountRestrictionModification'; diff --git a/test/model/transaction/AddressAliasTransaction.spec.ts b/test/model/transaction/AddressAliasTransaction.spec.ts index b68154c471..db8d7b954b 100644 --- a/test/model/transaction/AddressAliasTransaction.spec.ts +++ b/test/model/transaction/AddressAliasTransaction.spec.ts @@ -18,10 +18,10 @@ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; import {Address} from '../../../src/model/account/Address'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import {AliasAction} from '../../../src/model/namespace/AliasAction'; import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {AddressAliasTransaction} from '../../../src/model/transaction/AddressAliasTransaction'; import {Deadline} from '../../../src/model/transaction/Deadline'; import {UInt64} from '../../../src/model/UInt64'; diff --git a/test/model/transaction/AggregateTransaction.spec.ts b/test/model/transaction/AggregateTransaction.spec.ts index d5a3f2b86e..4c1c4f1fa4 100644 --- a/test/model/transaction/AggregateTransaction.spec.ts +++ b/test/model/transaction/AggregateTransaction.spec.ts @@ -22,7 +22,6 @@ import { CreateTransactionFromDTO } from '../../../src/infrastructure/transactio import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; import { PublicAccount } from '../../../src/model/account/PublicAccount'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../../src/model/message/PlainMessage'; import { Mosaic } from '../../../src/model/mosaic/Mosaic'; import { MosaicFlags } from '../../../src/model/mosaic/MosaicFlags'; @@ -31,6 +30,7 @@ import { MosaicNonce } from '../../../src/model/mosaic/MosaicNonce'; import { MosaicSupplyChangeAction } from '../../../src/model/mosaic/MosaicSupplyChangeAction'; import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; diff --git a/test/model/transaction/CosignatureTransaction.spec.ts b/test/model/transaction/CosignatureTransaction.spec.ts index bf13629857..1c5555559e 100644 --- a/test/model/transaction/CosignatureTransaction.spec.ts +++ b/test/model/transaction/CosignatureTransaction.spec.ts @@ -17,8 +17,8 @@ import {expect} from 'chai'; import {CreateTransactionFromDTO} from '../../../src/infrastructure/transaction/CreateTransactionFromDTO'; import {Account} from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../../src/model/message/PlainMessage'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import {AggregateTransaction} from '../../../src/model/transaction/AggregateTransaction'; import {CosignatureTransaction} from '../../../src/model/transaction/CosignatureTransaction'; import { Deadline } from '../../../src/model/transaction/Deadline'; diff --git a/test/model/transaction/HashLockTransaction.spec.ts b/test/model/transaction/HashLockTransaction.spec.ts index 65a2fca403..9b5682dfa3 100644 --- a/test/model/transaction/HashLockTransaction.spec.ts +++ b/test/model/transaction/HashLockTransaction.spec.ts @@ -15,8 +15,8 @@ */ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyLocal'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {AggregateTransaction} from '../../../src/model/transaction/AggregateTransaction'; import {Deadline} from '../../../src/model/transaction/Deadline'; import {HashLockTransaction} from '../../../src/model/transaction/HashLockTransaction'; diff --git a/test/model/transaction/LockFundsTransaction.spec.ts b/test/model/transaction/LockFundsTransaction.spec.ts index f43a11b4c7..cf2a8a9cba 100644 --- a/test/model/transaction/LockFundsTransaction.spec.ts +++ b/test/model/transaction/LockFundsTransaction.spec.ts @@ -17,11 +17,11 @@ import {deepEqual} from 'assert'; import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import { Mosaic } from '../../../src/model/mosaic/Mosaic'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import {NetworkCurrencyLocal} from '../../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; diff --git a/test/model/transaction/MosaicAddressRestrictionTransaction.spec.ts b/test/model/transaction/MosaicAddressRestrictionTransaction.spec.ts index 63f6e2b595..5aceec8548 100644 --- a/test/model/transaction/MosaicAddressRestrictionTransaction.spec.ts +++ b/test/model/transaction/MosaicAddressRestrictionTransaction.spec.ts @@ -18,9 +18,9 @@ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; diff --git a/test/model/transaction/MosaicAliasTransaction.spec.ts b/test/model/transaction/MosaicAliasTransaction.spec.ts index 3e9f775b44..e8cf306a03 100644 --- a/test/model/transaction/MosaicAliasTransaction.spec.ts +++ b/test/model/transaction/MosaicAliasTransaction.spec.ts @@ -17,10 +17,10 @@ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import {AliasAction} from '../../../src/model/namespace/AliasAction'; import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {Deadline} from '../../../src/model/transaction/Deadline'; import {MosaicAliasTransaction} from '../../../src/model/transaction/MosaicAliasTransaction'; import {UInt64} from '../../../src/model/UInt64'; diff --git a/test/model/transaction/MosaicDefinitionTransaction.spec.ts b/test/model/transaction/MosaicDefinitionTransaction.spec.ts index c1a4d9bc42..1529e2c211 100644 --- a/test/model/transaction/MosaicDefinitionTransaction.spec.ts +++ b/test/model/transaction/MosaicDefinitionTransaction.spec.ts @@ -17,10 +17,10 @@ import { expect } from 'chai'; import { Convert } from '../../../src/core/format'; import { Account } from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { MosaicFlags } from '../../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { MosaicNonce } from '../../../src/model/mosaic/MosaicNonce'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { MosaicDefinitionTransaction } from '../../../src/model/transaction/MosaicDefinitionTransaction'; import { UInt64 } from '../../../src/model/UInt64'; diff --git a/test/model/transaction/MosaicGlobalRestrictionTransaction.spec.ts b/test/model/transaction/MosaicGlobalRestrictionTransaction.spec.ts index 846f631733..fe733553fe 100644 --- a/test/model/transaction/MosaicGlobalRestrictionTransaction.spec.ts +++ b/test/model/transaction/MosaicGlobalRestrictionTransaction.spec.ts @@ -17,9 +17,9 @@ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; diff --git a/test/model/transaction/MosaicMetadataTransaction.spec.ts b/test/model/transaction/MosaicMetadataTransaction.spec.ts index 5394522694..d084164cef 100644 --- a/test/model/transaction/MosaicMetadataTransaction.spec.ts +++ b/test/model/transaction/MosaicMetadataTransaction.spec.ts @@ -17,9 +17,9 @@ import { expect } from 'chai'; import { Convert } from '../../../src/core/format/Convert'; import { Account } from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; diff --git a/test/model/transaction/MosaicSupplyChangeTransaction.spec.ts b/test/model/transaction/MosaicSupplyChangeTransaction.spec.ts index 77f2fdaa90..6a42f809b4 100644 --- a/test/model/transaction/MosaicSupplyChangeTransaction.spec.ts +++ b/test/model/transaction/MosaicSupplyChangeTransaction.spec.ts @@ -17,10 +17,10 @@ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import {MosaicId} from '../../../src/model/mosaic/MosaicId'; import {MosaicSupplyChangeAction} from '../../../src/model/mosaic/MosaicSupplyChangeAction'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; diff --git a/test/model/transaction/MultisigAccountModificationTransaction.spec.ts b/test/model/transaction/MultisigAccountModificationTransaction.spec.ts index ff5a2ae193..18bdcfe5b8 100644 --- a/test/model/transaction/MultisigAccountModificationTransaction.spec.ts +++ b/test/model/transaction/MultisigAccountModificationTransaction.spec.ts @@ -18,7 +18,7 @@ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {Deadline} from '../../../src/model/transaction/Deadline'; import {MultisigAccountModificationTransaction} from '../../../src/model/transaction/MultisigAccountModificationTransaction'; import {UInt64} from '../../../src/model/UInt64'; diff --git a/test/model/transaction/MultisigCosignatoryModification.spec.ts b/test/model/transaction/MultisigCosignatoryModification.spec.ts index 125d732869..c313c565c3 100644 --- a/test/model/transaction/MultisigCosignatoryModification.spec.ts +++ b/test/model/transaction/MultisigCosignatoryModification.spec.ts @@ -16,7 +16,7 @@ import {expect} from 'chai'; import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {CosignatoryModificationAction} from '../../../src/model/transaction/CosignatoryModificationAction'; import {MultisigCosignatoryModification} from '../../../src/model/transaction/MultisigCosignatoryModification'; diff --git a/test/model/transaction/NamespaceMetadataTransaction.spec.ts b/test/model/transaction/NamespaceMetadataTransaction.spec.ts index efbb5a45db..801735c777 100644 --- a/test/model/transaction/NamespaceMetadataTransaction.spec.ts +++ b/test/model/transaction/NamespaceMetadataTransaction.spec.ts @@ -17,8 +17,8 @@ import { expect } from 'chai'; import { Convert } from '../../../src/core/format/Convert'; import { Account } from '../../../src/model/account/Account'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { NamespaceMetadataTransaction } from '../../../src/model/transaction/NamespaceMetadataTransaction'; import { UInt64 } from '../../../src/model/UInt64'; diff --git a/test/model/transaction/NamespaceRegistrationTransaction.spec.ts b/test/model/transaction/NamespaceRegistrationTransaction.spec.ts index 921a3bd457..38fd8bd2d7 100644 --- a/test/model/transaction/NamespaceRegistrationTransaction.spec.ts +++ b/test/model/transaction/NamespaceRegistrationTransaction.spec.ts @@ -17,8 +17,8 @@ import {expect} from 'chai'; import {Convert} from '../../../src/core/format'; import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {Deadline} from '../../../src/model/transaction/Deadline'; import {NamespaceRegistrationTransaction} from '../../../src/model/transaction/NamespaceRegistrationTransaction'; import {UInt64} from '../../../src/model/UInt64'; diff --git a/test/model/transaction/PersistentDelegationRequestTransaction.spec.ts b/test/model/transaction/PersistentDelegationRequestTransaction.spec.ts index db339164d2..fb5e2a71e4 100644 --- a/test/model/transaction/PersistentDelegationRequestTransaction.spec.ts +++ b/test/model/transaction/PersistentDelegationRequestTransaction.spec.ts @@ -17,8 +17,8 @@ import { expect } from 'chai'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { MessageMarker } from '../../../src/model/message/MessageMarker'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { PersistentDelegationRequestTransaction, diff --git a/test/model/transaction/SecretLockTransaction.spec.ts b/test/model/transaction/SecretLockTransaction.spec.ts index ebb2d0cb04..9d394e512c 100644 --- a/test/model/transaction/SecretLockTransaction.spec.ts +++ b/test/model/transaction/SecretLockTransaction.spec.ts @@ -20,11 +20,11 @@ import {keccak_256, sha3_256} from 'js-sha3'; import {Convert, Convert as convert} from '../../../src/core/format'; import { Account } from '../../../src/model/account/Account'; import {Address} from '../../../src/model/account/Address'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import { Mosaic } from '../../../src/model/mosaic/Mosaic'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import {NetworkCurrencyLocal} from '../../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; diff --git a/test/model/transaction/SecretProofTransaction.spec.ts b/test/model/transaction/SecretProofTransaction.spec.ts index 6ea61c6300..e118cefe26 100644 --- a/test/model/transaction/SecretProofTransaction.spec.ts +++ b/test/model/transaction/SecretProofTransaction.spec.ts @@ -19,8 +19,8 @@ import {keccak_256, sha3_256} from 'js-sha3'; import {Convert, Convert as convert} from '../../../src/core/format'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; diff --git a/test/model/transaction/SignedTransaction.spec.ts b/test/model/transaction/SignedTransaction.spec.ts index 02e132ee6c..a6c2875ea6 100644 --- a/test/model/transaction/SignedTransaction.spec.ts +++ b/test/model/transaction/SignedTransaction.spec.ts @@ -15,7 +15,7 @@ */ import {expect} from 'chai'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {SignedTransaction} from '../../../src/model/transaction/SignedTransaction'; import {TransactionType} from '../../../src/model/transaction/TransactionType'; diff --git a/test/model/transaction/Transaction.spec.ts b/test/model/transaction/Transaction.spec.ts index eaeeee963b..0f9de203b2 100644 --- a/test/model/transaction/Transaction.spec.ts +++ b/test/model/transaction/Transaction.spec.ts @@ -19,8 +19,8 @@ import { expect } from 'chai'; import { Convert } from '../../../src/core/format/Convert'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../../src/model/message/PlainMessage'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { SignedTransaction } from '../../../src/model/transaction/SignedTransaction'; diff --git a/test/model/transaction/TransferTransaction.spec.ts b/test/model/transaction/TransferTransaction.spec.ts index d810cc281e..19fd40c058 100644 --- a/test/model/transaction/TransferTransaction.spec.ts +++ b/test/model/transaction/TransferTransaction.spec.ts @@ -19,7 +19,6 @@ import {Convert} from '../../../src/core/format'; import { CreateTransactionFromPayload } from '../../../src/infrastructure/transaction/CreateTransactionFromPayload'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; -import { NetworkType } from '../../../src/model/blockchain/NetworkType'; import { MessageMarker } from '../../../src/model/message/MessageMarker'; import { MessageType } from '../../../src/model/message/MessageType'; import { PersistentHarvestingDelegationMessage } from '../../../src/model/message/PersistentHarvestingDelegationMessage'; @@ -29,6 +28,7 @@ import { Mosaic } from '../../../src/model/mosaic/Mosaic'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; import { Statement } from '../../../src/model/receipt/Statement'; import { Deadline } from '../../../src/model/transaction/Deadline'; diff --git a/test/model/wallet/SimpleWallet.spec.ts b/test/model/wallet/SimpleWallet.spec.ts index 0dce309b56..4e5362c57d 100644 --- a/test/model/wallet/SimpleWallet.spec.ts +++ b/test/model/wallet/SimpleWallet.spec.ts @@ -16,7 +16,7 @@ import {expect} from 'chai'; import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/blockchain/NetworkType'; +import {NetworkType} from '../../../src/model/network/NetworkType'; import {Password} from '../../../src/model/wallet/Password'; import {SimpleWallet} from '../../../src/model/wallet/SimpleWallet'; @@ -60,4 +60,12 @@ describe('SimpleWallet', () => { const account2 = simpleWallet2.open(password); expect(account).to.deep.equal(account2); }); + + it('should create a simple wallet DTO', () => { + const privateKey = '5149a02ca2b2610138376717daaff8477f1639796aa108b7eee83e99e585b250'; + const password = new Password('password'); + const simpleWallet = SimpleWallet.createFromPrivateKey('wallet-name', password, privateKey, NetworkType.MIJIN_TEST); + const simpleWalletDTO = simpleWallet.toDTO() + expect(simpleWalletDTO).to.deep.equal(JSON.parse(JSON.stringify(simpleWallet))) + }) }); diff --git a/test/resource/TestResources.ts b/test/resource/TestResources.ts new file mode 100644 index 0000000000..fc844192c7 --- /dev/null +++ b/test/resource/TestResources.ts @@ -0,0 +1,91 @@ +export const getDummyNetworkProperties = () => { + return JSON.parse(`{ + "network": { + "identifier": "public-test", + "nodeEqualityStrategy": "public-key", + "publicKey": "86E8FDE6F3FE540ADC1B3A78DFA9B9E735736FC520E0D9C9CD4ADD3255CD9605", + "generationHash": "E759C7C56FD20021C8F0CC7FF5F108A2FEBA3312F6EC6D6A702DF87657FEC55C", + "epochAdjustment": "1573430400s" + }, + "chain": { + "enableVerifiableState": true, + "enableVerifiableReceipts": true, + "currencyMosaicId": "0x605E'BB80'8E3A'21C6", + "harvestingMosaicId": "0x501C'4C79'2FEB'D419", + "blockGenerationTargetTime": "15s", + "blockTimeSmoothingFactor": "3000", + "importanceGrouping": "1433", + "importanceActivityPercentage": "5", + "maxRollbackBlocks": "398", + "maxDifficultyBlocks": "60", + "defaultDynamicFeeMultiplier": "1'000", + "maxTransactionLifetime": "24h", + "maxBlockFutureTime": "500ms", + "initialCurrencyAtomicUnits": "8'998'999'998'000'000", + "maxMosaicAtomicUnits": "9'000'000'000'000'000", + "totalChainImportance": "15'000'000", + "minHarvesterBalance": "500", + "maxHarvesterBalance": "50'000'000'000'000", + "harvestBeneficiaryPercentage": "10", + "blockPruneInterval": "360", + "maxTransactionsPerBlock": "6'000" + }, + "plugins": { + "accountlink": { + "dummy": "to trigger plugin load" + }, + "aggregate": { + "maxTransactionsPerAggregate": "1'000", + "maxCosignaturesPerAggregate": "25", + "enableStrictCosignatureCheck": false, + "enableBondedAggregateSupport": true, + "maxBondedTransactionLifetime": "48h" + }, + "lockhash": { + "lockedFundsPerAggregate": "10'000'000", + "maxHashLockDuration": "2d" + }, + "locksecret": { + "maxSecretLockDuration": "30d", + "minProofSize": "1", + "maxProofSize": "1000" + }, + "metadata": { + "maxValueSize": "1024" + }, + "mosaic": { + "maxMosaicsPerAccount": "1'000", + "maxMosaicDuration": "3650d", + "maxMosaicDivisibility": "6", + "mosaicRentalFeeSinkPublicKey": "53E140B5947F104CABC2D6FE8BAEDBC30EF9A0609C717D9613DE593EC2A266D3", + "mosaicRentalFee": "500" + }, + "multisig": { + "maxMultisigDepth": "3", + "maxCosignatoriesPerAccount": "25", + "maxCosignedAccountsPerAccount": "25" + }, + "namespace": { + "maxNameSize": "64", + "maxChildNamespaces": "256", + "maxNamespaceDepth": "3", + "minNamespaceDuration": "1m", + "maxNamespaceDuration": "365d", + "namespaceGracePeriodDuration": "30d", + "reservedRootNamespaceNames": "xem, nem, user, account, org, com, biz, net, edu, mil, gov, info", + "namespaceRentalFeeSinkPublicKey": "3E82E1C1E4A75ADAA3CBA8C101C3CD31D9817A2EB966EB3B511FB2ED45B8E262", + "rootNamespaceRentalFeePerBlock": "1", + "childNamespaceRentalFee": "100" + }, + "restrictionaccount": { + "maxAccountRestrictionValues": "512" + }, + "restrictionmosaic": { + "maxMosaicRestrictionValues": "20" + }, + "transfer": { + "maxMessageSize": "1024" + } + } + }`); + }; diff --git a/test/service/AggregateTransactionService.spec.ts b/test/service/AggregateTransactionService.spec.ts index e15a57f276..5808745618 100644 --- a/test/service/AggregateTransactionService.spec.ts +++ b/test/service/AggregateTransactionService.spec.ts @@ -24,8 +24,8 @@ import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; import { MultisigAccountGraphInfo } from '../../src/model/account/MultisigAccountGraphInfo'; import { MultisigAccountInfo } from '../../src/model/account/MultisigAccountInfo'; -import {NetworkType} from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; +import {NetworkType} from '../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { MultisigAccountModificationTransaction } from '../../src/model/transaction/MultisigAccountModificationTransaction'; diff --git a/test/service/BlockService.spec.ts b/test/service/BlockService.spec.ts index 23f8e65be4..8713cb7bda 100644 --- a/test/service/BlockService.spec.ts +++ b/test/service/BlockService.spec.ts @@ -25,7 +25,7 @@ import { Account } from '../../src/model/account/Account'; import { BlockInfo } from '../../src/model/blockchain/BlockInfo'; import { MerklePathItem } from '../../src/model/blockchain/MerklePathItem'; import { MerkleProofInfo } from '../../src/model/blockchain/MerkleProofInfo'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { UInt64 } from '../../src/model/UInt64'; import { BlockService } from '../../src/service/BlockService'; import { TestingAccount } from '../conf/conf.spec'; diff --git a/test/service/MetadataTransactionservice.spec.ts b/test/service/MetadataTransactionservice.spec.ts index 6a88a391f3..cc988efff8 100644 --- a/test/service/MetadataTransactionservice.spec.ts +++ b/test/service/MetadataTransactionservice.spec.ts @@ -20,12 +20,12 @@ import { deepEqual, instance, mock, when } from 'ts-mockito'; import { Convert } from '../../src/core/format/Convert'; import { MetadataRepository } from '../../src/infrastructure/MetadataRepository'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { Metadata } from '../../src/model/metadata/Metadata'; import { MetadataEntry } from '../../src/model/metadata/MetadataEntry'; import { MetadataType } from '../../src/model/metadata/MetadataType'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AccountMetadataTransaction } from '../../src/model/transaction/AccountMetadataTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { MosaicMetadataTransaction } from '../../src/model/transaction/MosaicMetadataTransaction'; diff --git a/test/service/MosaicRestrictionTransactionservice.spec.ts b/test/service/MosaicRestrictionTransactionservice.spec.ts index cfa0f9ab74..4b629431e8 100644 --- a/test/service/MosaicRestrictionTransactionservice.spec.ts +++ b/test/service/MosaicRestrictionTransactionservice.spec.ts @@ -21,9 +21,9 @@ import { KeyGenerator } from '../../src/core/format/KeyGenerator'; import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; import { RestrictionMosaicRepository } from '../../src/infrastructure/RestrictionMosaicRepository'; import { Account } from '../../src/model/account/Account'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { MosaicAddressRestriction } from '../../src/model/restriction/MosaicAddressRestriction'; import { MosaicGlobalRestriction } from '../../src/model/restriction/MosaicGlobalRestriction'; import { MosaicGlobalRestrictionItem } from '../../src/model/restriction/MosaicGlobalRestrictionItem'; diff --git a/test/service/MosaicService.spec.ts b/test/service/MosaicService.spec.ts index d1fa62292d..eeeab2b4e3 100644 --- a/test/service/MosaicService.spec.ts +++ b/test/service/MosaicService.spec.ts @@ -15,10 +15,7 @@ */ import {expect} from 'chai'; -import {AccountHttp} from '../../src/infrastructure/AccountHttp'; -import {MosaicHttp} from '../../src/infrastructure/MosaicHttp'; -import {Address} from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/model'; +import { MosaicFlags, AccountInfo, AccountType } from '../../src/model/model'; import {Mosaic} from '../../src/model/mosaic/Mosaic'; import {MosaicId} from '../../src/model/mosaic/MosaicId'; import {MosaicInfo} from '../../src/model/mosaic/MosaicInfo'; @@ -26,13 +23,23 @@ import {UInt64} from '../../src/model/UInt64'; import {MosaicAmountView} from '../../src/service/MosaicAmountView'; import {MosaicService} from '../../src/service/MosaicService'; import {MosaicView} from '../../src/service/MosaicView'; -import * as conf from '../conf/conf.spec'; +import { AccountRepository } from '../../src/infrastructure/AccountRepository'; +import { mock, when, instance, deepEqual } from 'ts-mockito'; +import { MosaicRepository } from '../../src/infrastructure/MosaicRepository'; +import { of as observableOf } from 'rxjs'; +import { PublicAccount } from '../../src/model/account/PublicAccount'; +import { TestingAccount } from '../conf/conf.spec'; describe('MosaicService', () => { + const accountRepositoryMock = mock(); + const mosaicRepositoryMock = mock(); + it('mosaicsView', () => { const mosaicId = new MosaicId([3294802500, 2243684972]); - const mosaicService = new MosaicService( - new AccountHttp(conf.NIS2_URL), new MosaicHttp(conf.NIS2_URL, NetworkType.MIJIN_TEST)); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( + [buildMosaicInfo(mosaicId, TestingAccount.publicAccount)] + )); + const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); return mosaicService.mosaicsView([mosaicId]).subscribe((mosaicsView: MosaicView[]) => { const mosaicView = mosaicsView[0]; expect(mosaicView.mosaicInfo).to.be.an.instanceof(MosaicInfo); @@ -41,17 +48,26 @@ describe('MosaicService', () => { it('mosaicsView of no existing mosaicId', () => { const mosaicId = new MosaicId([1234, 1234]); - const mosaicService = new MosaicService( - new AccountHttp(conf.NIS2_URL), new MosaicHttp(conf.NIS2_URL, NetworkType.MIJIN_TEST)); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( + [] + )); + const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); return mosaicService.mosaicsView([mosaicId]).subscribe((mosaicsView: MosaicView[]) => { expect(mosaicsView.length).to.be.equal(0); }); }); it('mosaicsAmountView', () => { - const mosaicService = new MosaicService( - new AccountHttp(conf.NIS2_URL), new MosaicHttp(conf.NIS2_URL, NetworkType.MIJIN_TEST)); - return mosaicService.mosaicsAmountViewFromAddress(Address.createFromRawAddress('SARNASAS2BIAB6LMFA3FPMGBPGIJGK6IJETM3ZSP')) + const mosaicId = new MosaicId([3294802500, 2243684972]); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( + [buildMosaicInfo(mosaicId, TestingAccount.publicAccount)] + )); + when(accountRepositoryMock.getAccountInfo(deepEqual(TestingAccount.address))).thenReturn(observableOf( + buildAccountInfo(mosaicId), + )); + + const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); + return mosaicService.mosaicsAmountViewFromAddress(TestingAccount.address) .subscribe((mosaicsAmountView: MosaicAmountView[]) => { const mosaicAmountView = mosaicsAmountView[0]; expect(mosaicAmountView.mosaicInfo).to.be.an.instanceof(MosaicInfo); @@ -59,18 +75,29 @@ describe('MosaicService', () => { }); it('mosaicsAmountView of no existing account', () => { - const mosaicService = new MosaicService( - new AccountHttp(conf.NIS2_URL), new MosaicHttp(conf.NIS2_URL, NetworkType.MIJIN_TEST)); - return mosaicService.mosaicsAmountViewFromAddress(Address.createFromRawAddress('SCKBZAMIQ6F46QMZUANE6E33KA63KA7KEQ5X6WJW')) + const mosaicId = new MosaicId([3294802500, 2243684972]); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( + [] + )); + when(accountRepositoryMock.getAccountInfo(deepEqual(TestingAccount.address))).thenReturn(observableOf( + buildAccountInfo(mosaicId), + )); + + const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); + return mosaicService.mosaicsAmountViewFromAddress(TestingAccount.address) .subscribe((mosaicsAmountView: MosaicAmountView[]) => { expect(mosaicsAmountView.length).to.be.equal(0); }); }); it('mosaicsAmountView', () => { - const mosaic = new Mosaic(new MosaicId([3646934825, 3576016193]), UInt64.fromUint(1000)); - const mosaicService = new MosaicService( - new AccountHttp(conf.NIS2_URL), new MosaicHttp(conf.NIS2_URL, NetworkType.MIJIN_TEST)); + const mosaicId = new MosaicId([3294802500, 2243684972]); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( + [buildMosaicInfo(mosaicId, TestingAccount.publicAccount)] + )); + + const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); + const mosaic = new Mosaic(mosaicId, UInt64.fromUint(1000)); return mosaicService.mosaicsAmountView([mosaic]).subscribe((mosaicsAmountView: MosaicAmountView[]) => { const mosaicAmountView = mosaicsAmountView[0]; expect(mosaicAmountView.mosaicInfo).to.be.an.instanceof(MosaicInfo); @@ -78,4 +105,19 @@ describe('MosaicService', () => { }); }); + function buildMosaicInfo(mosaicId: MosaicId, publicAccount: PublicAccount): MosaicInfo { + return new MosaicInfo( + mosaicId, UInt64.fromUint(10), UInt64.fromUint(1), publicAccount, 0, + new MosaicFlags(1), 6, UInt64.fromUint(1) + ); + } + + function buildAccountInfo(mosaicId: MosaicId, isEmptyMosaic: boolean = false): AccountInfo { + return new AccountInfo( + TestingAccount.address, UInt64.fromUint(1), TestingAccount.publicKey, UInt64.fromUint(1), + AccountType.Main, '', [], isEmptyMosaic ? [] : [new Mosaic(mosaicId, UInt64.fromUint(100))], UInt64.fromUint(1), + UInt64.fromUint(1), + ); + } + }); diff --git a/test/service/NamespaceService.spec.ts b/test/service/NamespaceService.spec.ts index dda67196b7..30eda39e28 100644 --- a/test/service/NamespaceService.spec.ts +++ b/test/service/NamespaceService.spec.ts @@ -19,11 +19,11 @@ import { of as observableOf } from 'rxjs'; import { deepEqual, instance, mock, when } from 'ts-mockito'; import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; import { PublicAccount } from '../../src/model/account/PublicAccount'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { EmptyAlias } from '../../src/model/namespace/EmptyAlias'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; import { NamespaceInfo } from '../../src/model/namespace/NamespaceInfo'; import { NamespaceName } from '../../src/model/namespace/NamespaceName'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { UInt64 } from '../../src/model/UInt64'; import { NamespaceService } from '../../src/service/NamespaceService'; diff --git a/test/service/TransactionService.spec.ts b/test/service/TransactionService.spec.ts index 79e2ff1763..3825f76c56 100644 --- a/test/service/TransactionService.spec.ts +++ b/test/service/TransactionService.spec.ts @@ -24,11 +24,11 @@ import { TransactionRepository } from '../../src/infrastructure/TransactionRepos import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/blockchain/NetworkType'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { Mosaic } from '../../src/model/mosaic/Mosaic'; import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { HashLockTransaction } from '../../src/model/transaction/HashLockTransaction'; diff --git a/.npmrc.template b/travis/.npmrc similarity index 100% rename from .npmrc.template rename to travis/.npmrc diff --git a/travis/github-pages.sh b/travis/github-pages.sh new file mode 100644 index 0000000000..a3e78de3d5 --- /dev/null +++ b/travis/github-pages.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -e + +PUBLICATION_BRANCH=gh-pages +# Checkout the branch +REPO_PATH=$PWD +CURRENT_VERSION=$(npm run version --silent) +rm -rf $HOME/publish +cd $HOME +git clone --branch=$PUBLICATION_BRANCH https://${GITHUB_TOKEN}@github.com/$TRAVIS_REPO_SLUG publish 2>&1 > /dev/null +cd publish +# Update pages + +cp -r $REPO_PATH/ts-docs/. ./ +# Commit and push latest version +git add . +git config user.name "Travis" +git config user.email "travis@travis-ci.org" +git commit -m "Uploading $CURRENT_VERSION docs." +git push -fq origin $PUBLICATION_BRANCH 2>&1 > /dev/null +cd $REPO_PATH diff --git a/travis/release.sh b/travis/release.sh new file mode 100644 index 0000000000..20f16d94ea --- /dev/null +++ b/travis/release.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +set -e + +if [ "$TRAVIS_BRANCH" = "$RELEASE_BRANCH" ]; then + + REMOTE_NAME="origin" + POST_RELEASE_BRANCH="post-$RELEASE_BRANCH" + + git remote rm $REMOTE_NAME + + echo "Setting remote url https://github.com/${TRAVIS_REPO_SLUG}.git" + git remote add $REMOTE_NAME "https://${GITHUB_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git" > /dev/null 2>&1 + + echo "Checking out $RELEASE_BRANCH as travis leaves the head detached." + git checkout $RELEASE_BRANCH + + CURRENT_VERSION=$(npm run version --silent) + + echo "Current Version" + cat "$CURRENT_VERSION" + echo "" + + echo "Testing git remote" + git branch -vv + echo "" + + echo "Creating tag v$CURRENT_VERSION" + git tag -fa "v$CURRENT_VERSION" -m "Releasing version $CURRENT_VERSION" + + cp travis/.npmrc $HOME/.npmrc + + # The $SKIP_RELEASE_PUBLISH env variable can avoid republishing the same version to npm if something in the release process fails. + if [ "$SKIP_RELEASE_PUBLISH" = "true" ]; then + echo "Skipping publishing of sdk artifacts" + echo "" + else + echo "Publishing SDK artifacts" + npm publish + echo "" + fi + + echo "Increasing sdk version" + npm version patch -m "Increasing version to %s" --git-tag-version false + + CURRENT_VERSION=$(npm run version --silent) + + echo "New Version" + cat "$CURRENT_VERSION" + echo "" + + git add . + git commit -m "Creating new version $CURRENT_VERSION" + + echo "Pushing code to $REMOTE_NAME $POST_RELEASE_BRANCH" + git push --set-upstream $REMOTE_NAME $RELEASE_BRANCH:$POST_RELEASE_BRANCH + echo "Pushing tags to $REMOTE_NAME" + git push --tags $REMOTE_NAME +else + echo "Release is disabled" +fi diff --git a/travis/uploadArchives.sh b/travis/uploadArchives.sh index f4aec74a78..33159e61d9 100644 --- a/travis/uploadArchives.sh +++ b/travis/uploadArchives.sh @@ -5,7 +5,7 @@ CURRENT_VERSION=$(npm run version --silent) NEW_VERSION="$CURRENT_VERSION-alpha-$(date +%Y%m%d%H%M)" echo "Uploading npm package version $NEW_VERSION" -cp .npmrc.template $HOME/.npmrc +cp travis/.npmrc $HOME/.npmrc npm version "$NEW_VERSION" --commit-hooks false --git-tag-version false From fcf67e64ef2bf9212726ab17efca47f82a512eb0 Mon Sep 17 00:00:00 2001 From: Steven Liu Date: Wed, 8 Apr 2020 13:49:47 +0100 Subject: [PATCH 2/5] Trigger release build From 2c991cf713d8e20d1bfffc10c944f9a17da624f9 Mon Sep 17 00:00:00 2001 From: Steven Liu Date: Mon, 20 Apr 2020 20:14:46 +0100 Subject: [PATCH 3/5] v0.18.0 release --- CHANGELOG.md | 24 ++++++++++++++++++++++++ README.md | 14 +++++--------- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4e2eef843..e55dc08c60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,29 @@ All notable changes to this project will be documented in this file. The changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). +## [0.18.0] - 20-Apr-2020 + +**Milestone**: Fushicho.4(RC3 0.9.3.2) + Package | Version | Link +---|---|--- +SDK Core| v0.18.0 | https://www.npmjs.com/package/symbol-sdk +Catbuffer | v0.0.11 | https://www.npmjs.com/package/catbuffer-typescript +Client Library | v0.8.9 | https://www.npmjs.com/package/symbol-openapi-typescript-node-client + +- **[BREAKING CHANGE]** Stopped NodeJS v8 and v9 support. From this version (`v0.18.0`) onwards, Symbol-SDK will target on Node v10+. +- **[BREAKING CHANGE]** Removed `Keccac_256` from `LockHashAlgorithm` (enum index changed). +- **[BREAKING CHANGE]** Updated enum name `HashType` to `LockHashAlgorithm`. +- **[BREAKING CHANGE]** Updated property name `hashType` to `hashAlgorithm` in `SecretLockTransaction` and `SecretProofTransaction`. +- **[BREAKING CHANGE]** Removed redundant argument `NetworkType` from `Transaction.createTransactionHash()` and `Address.isValidRawAddress()`. +- **[BREAKING CHANGE]** Added `setMaxFeeForAggregate()` for `AggregateTransaction`. `Transaction.setMaxFee()` can only be used by standalone transaction objects. +- **[BREAKING CHANGE]** Refactored `SimpleWallet` model and wallet private key `Encryption / Decryption` methods to patch potential security risk. +- Added `AccountService` to resolve mosaic alias and return namespace name. +- Migrated from `TSLint` to `ESLint`. Added `Prettier` support. +- Removed metadata value size validation (1024 bytes). +- Fixed `PublicAccount.verifySignature` bug when verify string in hexadecimal format. +- Added check on `UInt64.compact()` which throw exception on over flow. +- Added `Network currency resolver` for e2e tests. + ## [0.17.4] - 07-Apr-2020 **Milestone**: Fushicho.4(RC3 0.9.3.2) @@ -437,6 +460,7 @@ Client Library | v0.7.20-alpha.6 | https://www.npmjs.com/package/nem2-sdk-opena - Initial code release. +[0.18.0]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.4...v0.18.0 [0.17.4]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.3...v0.17.4 [0.17.3]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.2...v0.17.3 [0.17.2]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.1...v0.17.2 diff --git a/README.md b/README.md index a892167259..4ad5425a09 100644 --- a/README.md +++ b/README.md @@ -11,11 +11,9 @@ The Symbol SDK for TypeScript / JavaScript allows you to develop web, mobile, an ### _Fushicho_ Network Compatibility (catapult-server@0.9.3.2) -**!!! Please be noted that the NEM2-SDK is rebranded to SYMBOL-SDK now**. +Due to a network upgrade with [catapult-server@Fushicho](https://github.com/nemtech/catapult-server/releases/tag/v0.9.3.2) version, **it is recommended to use this package's 0.18.0 version and upwards to use this package with Fushicho versioned networks**. -Due to a network upgrade with [catapult-server@Fushicho](https://github.com/nemtech/catapult-server/releases/tag/v0.9.3.2) version, **it is recommended to use this package's 0.17.4 version and upwards to use this package with Fushicho versioned networks**. - -The upgrade to this package's [version v0.17.4](https://github.com/nemtech/symbol-sdk-typescript-javascript/releases/tag/v0.17.4) is mandatory for **fushicho compatibility**. +The upgrade to this package's [version v0.18.0](https://github.com/nemtech/symbol-sdk-typescript-javascript/releases/tag/v0.18.0) is mandatory for **fushicho compatibility**. Find the complete release notes [here](CHANGELOG.md). @@ -23,9 +21,7 @@ Find the complete release notes [here](CHANGELOG.md). ### NodeJS -- NodeJS 8.9.X -- NodeJS 9.X.X -- NodeJS 10.X.X +- NodeJS 10.X.X and above (from v0.18.0) ## Installation @@ -46,14 +42,14 @@ Use the following available resources to get help: - [Symbol Documentation][docs] - [Symbol SDK Typescript/Javascript Reference][sdk-ref] -- Join the community [slack group (#sig-api)][slack] +- Join the community [slack group (#sig-api)][slack] - If you found a bug, [open a new issue][issues] ## Contributing This project is developed and maintained by NEM Foundation. -Contributions are welcome and appreciated. +Contributions are welcome and appreciated. Check [CONTRIBUTING](CONTRIBUTING.md) for information on how to contribute. You can also find useful notes for developers under our documentation [guidelines][guidelines] section. From bfde2d46670da55ad6f6a5307e20a32b220abc4b Mon Sep 17 00:00:00 2001 From: Steven Liu Date: Mon, 20 Apr 2020 21:17:46 +0100 Subject: [PATCH 4/5] v0.18.0 Release (#543) * Post Release (#519) * v0.17.4 (#514) * Created `network` folder for network models * Fixed lint after files moved * Applied openAPI 0.8.7 changes * Added tests * Use UInt64 in retalFees * Fixed #455 Make namespace max depth configurable in idGenerator * - Fixed parser bug - Use rest json payload for unit testing * restored removed tests to cover models * Working on travis release process and ts-doc github deployments * Simplfied BlockHttp Added BlockHttp unit tests Changed travis to just report coveralls from one job * fixed travis * Uploading multiple versions of ts-docs into git hub pages * Improved ChainHttp, added unit tests * Removed maxDepth. Let server run the validation * Added unit tests * FIxed #493 * Added tests * useQuerystring on all https * Fixed github token env variable name Added escape skip flag to avoid republishing the same version Added missing git commit . after version increase * Update README links * Update README.md * Update release.sh * Update README.md * Installing typescript globally * Improved MetadataHttp, added unit tests * fixed #495 * Fixed #501 * fixed #503 * Refactored MosaicService unit test (#510) * Fixed #509 * Added mosaicHttp unit tests * Refactored mosaicHttp to use abstract caller * Add error trapping unit test * removed unused error catcher * add SimpleWallet.toDTO, fixes #504 (#508) * add SimpleWallet.toDTO, fixes #504 * add word2ua test * Update README.md (#512) * v0.17.4 release (#513) * v0.17.4 release * Updated md table header Co-authored-by: Fernando Boucquez Co-authored-by: David Garcia Co-authored-by: Decentraliser * Trigger release build Co-authored-by: Fernando Boucquez Co-authored-by: David Garcia Co-authored-by: Decentraliser * Post release (#520) * v0.17.4 (#514) * Created `network` folder for network models * Fixed lint after files moved * Applied openAPI 0.8.7 changes * Added tests * Use UInt64 in retalFees * Fixed #455 Make namespace max depth configurable in idGenerator * - Fixed parser bug - Use rest json payload for unit testing * restored removed tests to cover models * Working on travis release process and ts-doc github deployments * Simplfied BlockHttp Added BlockHttp unit tests Changed travis to just report coveralls from one job * fixed travis * Uploading multiple versions of ts-docs into git hub pages * Improved ChainHttp, added unit tests * Removed maxDepth. Let server run the validation * Added unit tests * FIxed #493 * Added tests * useQuerystring on all https * Fixed github token env variable name Added escape skip flag to avoid republishing the same version Added missing git commit . after version increase * Update README links * Update README.md * Update release.sh * Update README.md * Installing typescript globally * Improved MetadataHttp, added unit tests * fixed #495 * Fixed #501 * fixed #503 * Refactored MosaicService unit test (#510) * Fixed #509 * Added mosaicHttp unit tests * Refactored mosaicHttp to use abstract caller * Add error trapping unit test * removed unused error catcher * add SimpleWallet.toDTO, fixes #504 (#508) * add SimpleWallet.toDTO, fixes #504 * add word2ua test * Update README.md (#512) * v0.17.4 release (#513) * v0.17.4 release * Updated md table header Co-authored-by: Fernando Boucquez Co-authored-by: David Garcia Co-authored-by: Decentraliser * Trigger release build * Creating new version 0.17.5 Co-authored-by: Fernando Boucquez Co-authored-by: David Garcia Co-authored-by: Decentraliser Co-authored-by: Travis CI User * LockHashAlgorithm (#522) * Fixed #518 - Added LockHashUtils - Removed Op_Keccak_256 algorithm - Renamed HashType to LockHashAlgorithm - Renamed model field name to be aligned with Catbuffer * Fixed #521 * - Added Hash method with algorithm input - Added unit tests - Added export * Added networkCurrency resolver for e2e tests (#529) * Fixed #523 - Added networkCurrency resolver for e2e tests * trigger travis * Removed metadata size validation (#527) * Fixed #526 - Removed metadata size validation * Added unit tests for coverage * added unit tests * improved coverage * Added check on Account.signData and PublicAccount.verifySignature for hexadecimal (#528) * Fixed #252 - Added check on Account.signData and PublicAccount.verifySignature for hexadecimal * trigger travis * Added isHexadecimal argument to account.signData and publicAccount.verifySignature * Fixed #525 * Removed unused condition * refactored signData and verifySignature * Prettier - ESLint (#531) * eslint and prettier * working on eslint * working on eslint * fixed travis * rolled back md changes * Added unit tests * improved NamespaceHttp * Fixed eslint warnings (#538) * Fixed #535 * Fixed #536 * maxFee in Aggregate transactions (#539) * Fixed #533 - Added setMaxFeeForAggregate - Changed setMaxFee for stand alone tx only - Addes getMaxCosignatures - Added getNetworkMaxCosignaturesPerAggregate * Fixed typo * Fixe typo * Fixed PR review comments * Added tests * Fixed #507 (#541) * upgrade crypto-js to v4.0.0, add AESEncryptionService and apply it to SimpleWallet, fixes #524 (#530) * upgrade crypto-js to v4.0.0, add AESEncryptionService and apply it to SimpleWallet, fixes #524 * remove passwordToPrivateKey, rename toMobileKey by encryptPBKDF2 * accept string as password in AESEncryptionService * remove unused functions in Crypto, merge AES Encryption service into Crypto Co-authored-by: Steven Liu * Alias resolution for accountHttp (#540) * Fixed #499 - Added AccountService * Fixed e2e tests * Fixed lints * Fixed years * another year fix * Chaned to use address array and reduce rest calls * handle empty array * Fixed typos * more typo fix * Fixed function name * v0.18.0 release Co-authored-by: Fernando Boucquez Co-authored-by: David Garcia Co-authored-by: Decentraliser Co-authored-by: Travis CI User --- .eslintrc.js | 19 + .github/issue_template.md | 2 +- .../WalletAlgorithm.ts => .prettierrc.js | 15 +- .travis.yml | 13 +- CHANGELOG.md | 24 + README.md | 14 +- e2e/infrastructure/AccountHttp.spec.ts | 97 +- e2e/infrastructure/BlockHttp.spec.ts | 48 +- e2e/infrastructure/IntegrationTestHelper.ts | 85 +- e2e/infrastructure/Listener.spec.ts | 145 ++- e2e/infrastructure/MetadataHttp.spec.ts | 28 +- e2e/infrastructure/MosaicHttp.spec.ts | 13 +- e2e/infrastructure/NamespaceHttp.spec.ts | 7 +- e2e/infrastructure/RestrictionHttp.spec.ts | 70 +- e2e/infrastructure/TransactionHttp.spec.ts | 681 +++++------ e2e/infrastructure/UnresolvedMapping.spec.ts | 73 +- e2e/service/AccountService.spec.ts | 94 ++ e2e/service/BlockService.spec.ts | 2 - .../MetadataTransactionService.spec.ts | 199 +-- ...osaicRestrictionTransactionService.spec.ts | 218 ++-- e2e/service/MosaicService.spec.ts | 16 +- e2e/service/TransactionService.spec.ts | 256 ++-- ...TransactionService_AggregateBonded.spec.ts | 137 ++- package-lock.json | 1083 +++++++++++++++-- package.json | 195 +-- src/core/crypto/Crypto.ts | 267 +--- src/core/crypto/KeyPair.ts | 16 +- src/core/crypto/MerkleHashBuilder.ts | 17 +- src/core/crypto/SHA3Hasher.ts | 24 +- src/core/crypto/Utilities.ts | 25 +- src/core/crypto/index.ts | 3 +- src/core/crypto/nacl_catapult.ts | 168 ++- src/core/format/Base32.ts | 8 +- src/core/format/Convert.ts | 41 +- src/core/format/IdGenerator.ts | 17 +- src/core/format/RawAddress.ts | 24 +- src/core/format/RawArray.ts | 14 +- src/core/format/RawUInt64.ts | 32 +- src/core/format/Utilities.ts | 50 +- src/core/utils/DtoMapping.ts | 53 +- src/core/utils/LockHashUtils.ts | 73 ++ src/core/utils/TransactionMapping.ts | 4 +- src/core/utils/UnresolvedMapping.ts | 1 - src/core/utils/utility.ts | 1 + src/infrastructure/AccountHttp.ts | 134 +- src/infrastructure/AccountRepository.ts | 31 +- src/infrastructure/BlockHttp.ts | 30 +- src/infrastructure/BlockRepository.ts | 12 +- src/infrastructure/ChainHttp.ts | 7 +- src/infrastructure/ChainRepository.ts | 4 +- src/infrastructure/Http.ts | 18 +- src/infrastructure/IListener.ts | 4 +- src/infrastructure/Listener.ts | 90 +- src/infrastructure/MetadataHttp.ts | 51 +- src/infrastructure/MetadataRepository.ts | 9 +- src/infrastructure/MosaicHttp.ts | 54 +- src/infrastructure/MosaicRepository.ts | 17 +- src/infrastructure/MultisigHttp.ts | 81 +- src/infrastructure/MultisigRepository.ts | 10 +- src/infrastructure/NamespaceHttp.ts | 209 ++-- src/infrastructure/NamespaceRepository.ts | 25 +- src/infrastructure/NetworkHttp.ts | 121 +- src/infrastructure/NetworkRepository.ts | 5 +- src/infrastructure/NodeHttp.ts | 33 +- src/infrastructure/NodeRepository.ts | 4 +- src/infrastructure/QueryParams.ts | 26 +- src/infrastructure/ReceiptHttp.ts | 18 +- src/infrastructure/ReceiptRepository.ts | 3 +- src/infrastructure/RepositoryFactory.ts | 2 - src/infrastructure/RepositoryFactoryHttp.ts | 11 +- src/infrastructure/RestrictionAccountHttp.ts | 19 +- src/infrastructure/RestrictionMosaicHttp.ts | 42 +- src/infrastructure/TransactionFilter.ts | 8 +- src/infrastructure/TransactionHttp.ts | 47 +- src/infrastructure/TransactionRepository.ts | 13 +- .../receipt/CreateReceiptFromDTO.ts | 33 +- .../transaction/CreateTransactionFromDTO.ts | 352 +++--- .../CreateTransactionFromPayload.ts | 26 +- .../transaction/NamespaceMosaicIdGenerator.ts | 25 +- .../transaction/SerializeTransactionToJSON.ts | 27 +- src/model/Id.ts | 5 +- src/model/UInt64.ts | 9 +- src/model/account/Account.ts | 83 +- src/model/account/AccountInfo.ts | 14 +- .../account/AccountInfoResolvedMosaic.ts | 23 + src/model/account/AccountNames.ts | 8 +- src/model/account/AccountType.ts | 2 +- src/model/account/ActivityBucket.ts | 36 +- src/model/account/Address.ts | 49 +- src/model/account/MultisigAccountGraphInfo.ts | 14 +- src/model/account/MultisigAccountInfo.ts | 47 +- src/model/account/PublicAccount.ts | 28 +- src/model/blockchain/BlockInfo.ts | 169 ++- src/model/blockchain/BlockchainScore.ts | 23 +- src/model/blockchain/MerklePathItem.ts | 21 +- src/model/blockchain/MerkleProofInfo.ts | 13 +- src/model/blockchain/StorageInfo.ts | 28 +- src/model/message/EncryptedMessage.ts | 35 +- src/model/message/Message.ts | 23 +- src/model/message/MessageType.ts | 2 +- .../PersistentHarvestingDelegationMessage.ts | 17 +- src/model/message/PlainMessage.ts | 5 +- src/model/metadata/Metadata.ts | 20 +- src/model/metadata/MetadataEntry.ts | 64 +- src/model/model.ts | 9 +- src/model/mosaic/Mosaic.ts | 31 +- src/model/mosaic/MosaicFlags.ts | 8 +- src/model/mosaic/MosaicId.ts | 5 +- src/model/mosaic/MosaicInfo.ts | 68 +- src/model/mosaic/MosaicNames.ts | 6 +- src/model/mosaic/MosaicNonce.ts | 1 - src/model/mosaic/NetworkCurrencyLocal.ts | 12 +- src/model/mosaic/NetworkCurrencyPublic.ts | 12 +- src/model/mosaic/NetworkHarvestLocal.ts | 12 +- src/model/mosaic/ResolvedMosaic.ts | 23 + src/model/namespace/AddressAlias.ts | 15 +- src/model/namespace/Alias.ts | 8 +- src/model/namespace/EmptyAlias.ts | 2 +- src/model/namespace/MosaicAlias.ts | 15 +- src/model/namespace/NamespaceId.ts | 11 +- src/model/namespace/NamespaceInfo.ts | 101 +- src/model/namespace/NamespaceInfoWithName.ts | 22 + src/model/namespace/NamespaceName.ts | 30 +- .../network/AccountLinkNetworkProperties.ts | 4 +- .../AccountRestrictionNetworkProperties.ts | 4 +- .../network/AggregateNetworkProperties.ts | 14 +- src/model/network/ChainProperties.ts | 46 +- .../network/HashLockNetworkProperties.ts | 5 +- .../network/MetadataNetworkProperties.ts | 4 +- src/model/network/MosaicNetworkProperties.ts | 15 +- .../MosaicRestrictionNetworkProperties.ts | 4 +- .../network/MultisigNetworkProperties.ts | 10 +- .../network/NamespaceNetworkProperties.ts | 24 +- src/model/network/NetworkConfiguration.ts | 10 +- src/model/network/NetworkName.ts | 4 +- src/model/network/NetworkProperties.ts | 14 +- src/model/network/PluginProperties.ts | 26 +- src/model/network/RentalFees.ts | 12 +- .../network/SecretLockNetworkProperties.ts | 10 +- src/model/network/TransactionFees.ts | 12 +- .../network/TransferNetworkProperties.ts | 4 +- src/model/node/NodeHealth.ts | 19 +- src/model/node/NodeInfo.ts | 67 +- src/model/node/NodeTime.ts | 19 +- src/model/node/ServerInfo.ts | 21 +- src/model/receipt/ArtifactExpiryReceipt.ts | 20 +- src/model/receipt/BalanceChangeReceipt.ts | 36 +- src/model/receipt/BalanceTransferReceipt.ts | 44 +- src/model/receipt/InflationReceipt.ts | 29 +- src/model/receipt/Receipt.ts | 27 +- src/model/receipt/ReceiptSource.ts | 23 +- src/model/receipt/ReceiptType.ts | 19 +- src/model/receipt/ReceiptVersion.ts | 1 - src/model/receipt/ResolutionEntry.ts | 35 +- src/model/receipt/ResolutionStatement.ts | 138 ++- src/model/receipt/Statement.ts | 114 +- src/model/receipt/TransactionStatement.ts | 27 +- src/model/restriction/AccountRestriction.ts | 21 +- .../restriction/AccountRestrictionType.ts | 24 +- src/model/restriction/AccountRestrictions.ts | 20 +- .../restriction/AccountRestrictionsInfo.ts | 20 +- .../restriction/MosaicAddressRestriction.ts | 44 +- .../restriction/MosaicGlobalRestriction.ts | 36 +- .../MosaicGlobalRestrictionItem.ts | 29 +- .../AccountAddressRestrictionTransaction.ts | 88 +- .../transaction/AccountLinkTransaction.ts | 62 +- .../transaction/AccountMetadataTransaction.ts | 89 +- .../AccountMosaicRestrictionTransaction.ts | 88 +- .../AccountOperationRestrictionTransaction.ts | 71 +- .../AccountRestrictionModification.ts | 44 +- .../AccountRestrictionTransaction.ts | 31 +- .../transaction/AddressAliasTransaction.ts | 72 +- src/model/transaction/AggregateTransaction.ts | 239 ++-- .../AggregateTransactionCosignature.ts | 26 +- .../transaction/AggregateTransactionInfo.ts | 30 +- src/model/transaction/AliasTransaction.ts | 48 +- .../CosignatureSignedTransaction.ts | 25 +- .../transaction/CosignatureTransaction.ts | 39 +- src/model/transaction/Deadline.ts | 18 +- src/model/transaction/HashLockTransaction.ts | 3 +- src/model/transaction/InnerTransaction.ts | 6 +- src/model/transaction/LockFundsTransaction.ts | 92 +- .../{HashType.ts => LockHashAlgorithm.ts} | 26 +- .../MosaicAddressRestrictionTransaction.ts | 117 +- .../transaction/MosaicAliasTransaction.ts | 69 +- .../MosaicDefinitionTransaction.ts | 99 +- .../MosaicGlobalRestrictionTransaction.ts | 146 ++- .../transaction/MosaicMetadataTransaction.ts | 110 +- .../MosaicSupplyChangeTransaction.ts | 85 +- .../MultisigAccountModificationTransaction.ts | 103 +- .../MultisigCosignatoryModification.ts | 26 +- .../NamespaceMetadataTransaction.ts | 112 +- .../NamespaceRegistrationTransaction.ts | 142 ++- .../PersistentDelegationRequestTransaction.ts | 14 +- .../transaction/SecretLockTransaction.ts | 130 +- .../transaction/SecretProofTransaction.ts | 80 +- src/model/transaction/SignedTransaction.ts | 46 +- src/model/transaction/SyncAnnounce.ts | 4 +- src/model/transaction/Transaction.ts | 189 +-- .../TransactionAnnounceResponse.ts | 12 +- src/model/transaction/TransactionInfo.ts | 44 +- src/model/transaction/TransactionStatus.ts | 46 +- .../transaction/TransactionStatusError.ts | 42 +- src/model/transaction/TransactionType.ts | 13 +- src/model/transaction/TransactionVersion.ts | 1 - src/model/transaction/TransferTransaction.ts | 134 +- src/model/wallet/EncryptedPrivateKey.ts | 57 - src/model/wallet/ISimpleWalletDTO.ts | 11 +- src/model/wallet/Password.ts | 5 +- src/model/wallet/SimpleWallet.ts | 82 +- src/model/wallet/Wallet.ts | 54 +- src/service/AccountService.ts | 137 +++ src/service/AggregateTransactionService.ts | 118 +- src/service/BlockService.ts | 35 +- src/service/MetadataTransactionService.ts | 195 +-- src/service/MosaicAmountView.ts | 25 +- .../MosaicRestrictionTransactionService.ts | 147 +-- src/service/MosaicService.ts | 28 +- src/service/MosaicView.ts | 15 +- src/service/Namespace.ts | 2 +- src/service/NamespaceService.ts | 41 +- src/service/TransactionService.ts | 93 +- src/service/interfaces/IAccountService.ts | 38 + src/service/interfaces/IBlockService.ts | 1 - src/service/interfaces/ITransactionService.ts | 9 +- src/service/service.ts | 2 + test/conf/conf.spec.ts | 19 +- test/core/crypto/MerkleHashBuilder.spec.ts | 5 - test/core/crypto/crypto.spec.ts | 409 +------ test/core/crypto/hkdf.spec.ts | 4 +- test/core/crypto/keyPair.spec.ts | 66 +- test/core/crypto/sha3Hasher.spec.ts | 31 +- test/core/crypto/utilities.spec.ts | 12 +- test/core/format/Base32.spec.ts | 11 +- test/core/format/Convert.spec.ts | 71 +- test/core/format/IdGenerator.spec.ts | 86 +- test/core/format/RawAddress.spec.ts | 58 +- test/core/format/RawArray.spec.ts | 10 +- test/core/format/RawUInt64.spec.ts | 56 +- test/core/format/Utilities.spec.ts | 6 +- test/core/utils/Hashes.spec.ts | 131 ++ test/core/utils/TransactionMapping.spec.ts | 362 +++--- test/core/utils/UnresolvedMapping.spec.ts | 3 +- test/health.spec.ts | 5 +- test/infrastructure/AccountHttp.spec.ts | 199 +-- test/infrastructure/BlockHttp.spec.ts | 48 +- test/infrastructure/ChainHttp.spec.ts | 12 +- test/infrastructure/Listener.spec.ts | 30 +- test/infrastructure/MetadataHttp.spec.ts | 138 ++- test/infrastructure/MosaicHttp.spec.ts | 59 +- test/infrastructure/MultisigHttp.spec.ts | 98 ++ test/infrastructure/NetworkHttp.spec.ts | 65 +- test/infrastructure/NodeHttp.spec.ts | 38 +- test/infrastructure/QueryParams.spec.ts | 38 + test/infrastructure/RepositoryFactory.spec.ts | 40 +- .../SerializeTransactionToJSON.spec.ts | 48 +- test/infrastructure/TransactionHttp.spec.ts | 19 +- .../receipt/CreateReceiptFromDTO.spec.ts | 156 +-- .../CreateTransactionFromDTO.spec.ts | 151 +-- .../transaction/ValidateTransaction.ts | 154 +-- test/model/Id.spec.ts | 4 +- test/model/UInt64.spec.ts | 57 +- test/model/account/Account.spec.ts | 131 +- test/model/account/AccountInfo.spec.ts | 53 +- test/model/account/Address.spec.ts | 51 +- .../account/MultisigAccountGraphInfo.spec.ts | 91 +- .../model/account/MultisigAccountInfo.spec.ts | 82 +- test/model/account/PublicAccount.spec.ts | 72 +- test/model/blockchain/BlockInfo.spec.ts | 27 +- test/model/blockchain/BlockchainScore.spec.ts | 12 +- .../blockchain/BlockchainStorageInfo.spec.ts | 3 +- test/model/message/EncryptedMessage.spec.ts | 47 +- test/model/message/Message.spec.ts | 5 +- ...sistentHarvestingDelegationMessage.spec.ts | 88 +- test/model/message/PlainMessage.spec.ts | 7 +- test/model/metadata/Metadata.spec.ts | 4 +- test/model/metadata/MetadataEntry.spec.ts | 4 +- test/model/mosaic/Mosaic.spec.ts | 16 +- test/model/mosaic/MosaicAmountView.spec.ts | 17 +- test/model/mosaic/MosaicFlags.spec.ts | 9 +- test/model/mosaic/MosaicInfo.spec.ts | 43 +- test/model/mosaic/MosaicNames.spec.ts | 39 + test/model/mosaic/MosaicNonce.spec.ts | 1 - test/model/mosaic/MosaicView.spec.ts | 18 +- test/model/mosaic/NetworkCurrency.spec.ts | 47 +- test/model/mosaic/NetworkHarvestLocal.spec.ts | 29 +- test/model/namespace/Alias.spec.ts | 24 +- test/model/namespace/NamespaceId.spec.ts | 23 +- test/model/namespace/NamespaceInfo.spec.ts | 111 +- test/model/namespace/NamespaceName.spec.ts | 15 +- test/model/network/NetworkType.spec.ts | 4 +- test/model/receipt/Receipt.spec.ts | 102 +- .../model/receipt/ResolutionStatement.spec.ts | 103 +- test/model/receipt/Statement.spec.ts | 79 +- .../restriction/AccountRestriction.spec.ts | 5 +- .../restriction/AccountRestrictions.spec.ts | 35 +- .../AccountRestrictionsInfo.spec.ts | 52 +- .../restriction/MosaicRestriction.spec.ts | 47 +- .../AccountLinkTransaction.spec.ts | 17 +- .../AccountMetadataTransaction.spec.ts | 58 +- .../AccountRestrictionTransaction.spec.ts | 139 +-- .../AddressAliasTransaction.spec.ts | 32 +- .../transaction/AggregateTransaction.spec.ts | 288 +++-- .../CosignatureTransaction.spec.ts | 41 +- test/model/transaction/Deadline.spec.ts | 8 +- .../transaction/HashLockTransaction.spec.ts | 42 +- .../HashTypeLengthValidator.spec.ts | 89 +- .../transaction/LockFundsTransaction.spec.ts | 127 +- ...osaicAddressRestrictionTransaction.spec.ts | 69 +- .../MosaicAliasTransaction.spec.ts | 68 +- .../MosaicDefinitionTransaction.spec.ts | 40 +- ...MosaicGlobalRestrictionTransaction.spec.ts | 62 +- .../MosaicMetadataTransaction.spec.ts | 70 +- .../MosaicSupplyChangeTransaction.spec.ts | 43 +- ...isigAccountModificationTransaction.spec.ts | 106 +- .../MultisigCosignatoryModification.spec.ts | 31 +- .../NamespaceMetadataTransaction.spec.ts | 63 +- .../NamespaceRegistrationTransaction.spec.ts | 40 +- ...istentDelegationRequestTransaction.spec.ts | 61 +- .../transaction/SecretLockTransaction.spec.ts | 138 +-- .../SecretProofTransaction.spec.ts | 173 +-- .../transaction/SignedTransaction.spec.ts | 29 +- test/model/transaction/Transaction.spec.ts | 207 ++-- .../TransactionStatusError.spec.ts | 14 +- .../model/transaction/TransactionType.spec.ts | 10 +- .../transaction/TransferTransaction.spec.ts | 144 +-- test/model/wallet/EncryptedPrivateKey.spec.ts | 39 - test/model/wallet/Password.spec.ts | 5 +- test/model/wallet/SimpleWallet.spec.ts | 28 +- test/resource/TestResources.ts | 4 +- test/service/AccountService.spec.ts | 190 +++ .../AggregateTransactionService.spec.ts | 420 ++++--- test/service/BlockService.spec.ts | 102 +- .../MetadataTransactionservice.spec.ts | 192 +-- ...osaicRestrictionTransactionservice.spec.ts | 220 ++-- test/service/MosaicService.spec.ts | 110 +- test/service/NamespaceService.spec.ts | 103 +- test/service/TransactionService.spec.ts | 74 +- tslint.json | 144 --- 339 files changed, 11097 insertions(+), 9051 deletions(-) create mode 100644 .eslintrc.js rename src/model/wallet/WalletAlgorithm.ts => .prettierrc.js (79%) create mode 100644 e2e/service/AccountService.spec.ts create mode 100644 src/core/utils/LockHashUtils.ts create mode 100644 src/model/account/AccountInfoResolvedMosaic.ts create mode 100644 src/model/mosaic/ResolvedMosaic.ts create mode 100644 src/model/namespace/NamespaceInfoWithName.ts rename src/model/transaction/{HashType.ts => LockHashAlgorithm.ts} (66%) delete mode 100644 src/model/wallet/EncryptedPrivateKey.ts create mode 100644 src/service/AccountService.ts create mode 100644 src/service/interfaces/IAccountService.ts create mode 100644 test/core/utils/Hashes.spec.ts create mode 100644 test/infrastructure/MultisigHttp.spec.ts create mode 100644 test/infrastructure/QueryParams.spec.ts create mode 100644 test/model/mosaic/MosaicNames.spec.ts delete mode 100644 test/model/wallet/EncryptedPrivateKey.spec.ts create mode 100644 test/service/AccountService.spec.ts delete mode 100644 tslint.json diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000000..2763e81261 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,19 @@ +module.exports = { + parser: '@typescript-eslint/parser', // Specifies the ESLint parser + extends: [ + 'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin + 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier + 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. + ], + parserOptions: { + ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features + sourceType: 'module', // Allows for the use of imports + }, + rules: { + '@typescript-eslint/no-non-null-assertion': 'off', + '@typescript-eslint/interface-name-prefix': 'off', + '@typescript-eslint/camelcase': 'off', + // TODO fix all the warnings + '@typescript-eslint/no-explicit-any': 'off', + }, +}; diff --git a/.github/issue_template.md b/.github/issue_template.md index eda3062d65..f841b3f980 100644 --- a/.github/issue_template.md +++ b/.github/issue_template.md @@ -2,4 +2,4 @@ 2. Steps to reproduce the problem. -3. Specifications like the version of the project, operating system, or hardware. \ No newline at end of file +3. Specifications like the version of the project, operating system, or hardware. diff --git a/src/model/wallet/WalletAlgorithm.ts b/.prettierrc.js similarity index 79% rename from src/model/wallet/WalletAlgorithm.ts rename to .prettierrc.js index fd7bec5a2e..212e486ae0 100644 --- a/src/model/wallet/WalletAlgorithm.ts +++ b/.prettierrc.js @@ -1,5 +1,5 @@ /* - * Copyright 2019 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,9 +14,10 @@ * limitations under the License. */ -export enum WalletAlgorithm { - Pass_6k = 1, - Pass_bip32 = 2, - Pass_enc = 4, - Trezor = 3, -} +module.exports = { + semi: true, + trailingComma: "all", + singleQuote: true, + printWidth: 140, + tabWidth: 4 +}; diff --git a/.travis.yml b/.travis.yml index 208c848e41..5cbbdce92b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,36 +1,37 @@ language: node_js node_js: - - "8" - - "9" - "10" + - "12" cache: directories: - "node_modules" + - .eslintcache before_script: - npm run build + - if [ "$TRAVIS_NODE_VERSION" = "10" ] || [ "$TRAVIS_NODE_VERSION" = "12" ]; then npm run lint; fi script: - npm run test:cov - npm install --global typedoc typescript - CURRENT_VERSION=$(npm run version --silent) - typedoc --out "ts-docs/$CURRENT_VERSION" src - touch ./ts-docs/.nojekyll - - if [ "$TRAVIS_NODE_VERSION" = "8" ]; then npm run coveralls-report; fi + - if [ "$TRAVIS_NODE_VERSION" = "10" ]; then npm run coveralls-report; fi deploy: - provider: script skip_cleanup: true script: /bin/sh travis/github-pages.sh on: branch: master - node_js: "9" + node_js: "12" - provider: script skip_cleanup: true script: /bin/sh travis/uploadArchives.sh on: branch: master - node_js: "8" + node_js: "10" - provider: script skip_cleanup: true script: /bin/sh travis/release.sh on: branch: $RELEASE_BRANCH - node_js: "8" + node_js: "10" diff --git a/CHANGELOG.md b/CHANGELOG.md index f4e2eef843..e55dc08c60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,29 @@ All notable changes to this project will be documented in this file. The changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). +## [0.18.0] - 20-Apr-2020 + +**Milestone**: Fushicho.4(RC3 0.9.3.2) + Package | Version | Link +---|---|--- +SDK Core| v0.18.0 | https://www.npmjs.com/package/symbol-sdk +Catbuffer | v0.0.11 | https://www.npmjs.com/package/catbuffer-typescript +Client Library | v0.8.9 | https://www.npmjs.com/package/symbol-openapi-typescript-node-client + +- **[BREAKING CHANGE]** Stopped NodeJS v8 and v9 support. From this version (`v0.18.0`) onwards, Symbol-SDK will target on Node v10+. +- **[BREAKING CHANGE]** Removed `Keccac_256` from `LockHashAlgorithm` (enum index changed). +- **[BREAKING CHANGE]** Updated enum name `HashType` to `LockHashAlgorithm`. +- **[BREAKING CHANGE]** Updated property name `hashType` to `hashAlgorithm` in `SecretLockTransaction` and `SecretProofTransaction`. +- **[BREAKING CHANGE]** Removed redundant argument `NetworkType` from `Transaction.createTransactionHash()` and `Address.isValidRawAddress()`. +- **[BREAKING CHANGE]** Added `setMaxFeeForAggregate()` for `AggregateTransaction`. `Transaction.setMaxFee()` can only be used by standalone transaction objects. +- **[BREAKING CHANGE]** Refactored `SimpleWallet` model and wallet private key `Encryption / Decryption` methods to patch potential security risk. +- Added `AccountService` to resolve mosaic alias and return namespace name. +- Migrated from `TSLint` to `ESLint`. Added `Prettier` support. +- Removed metadata value size validation (1024 bytes). +- Fixed `PublicAccount.verifySignature` bug when verify string in hexadecimal format. +- Added check on `UInt64.compact()` which throw exception on over flow. +- Added `Network currency resolver` for e2e tests. + ## [0.17.4] - 07-Apr-2020 **Milestone**: Fushicho.4(RC3 0.9.3.2) @@ -437,6 +460,7 @@ Client Library | v0.7.20-alpha.6 | https://www.npmjs.com/package/nem2-sdk-opena - Initial code release. +[0.18.0]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.4...v0.18.0 [0.17.4]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.3...v0.17.4 [0.17.3]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.2...v0.17.3 [0.17.2]: https://github.com/nemtech/symbol-sdk-typescript-javascript/compare/v0.17.1...v0.17.2 diff --git a/README.md b/README.md index a892167259..4ad5425a09 100644 --- a/README.md +++ b/README.md @@ -11,11 +11,9 @@ The Symbol SDK for TypeScript / JavaScript allows you to develop web, mobile, an ### _Fushicho_ Network Compatibility (catapult-server@0.9.3.2) -**!!! Please be noted that the NEM2-SDK is rebranded to SYMBOL-SDK now**. +Due to a network upgrade with [catapult-server@Fushicho](https://github.com/nemtech/catapult-server/releases/tag/v0.9.3.2) version, **it is recommended to use this package's 0.18.0 version and upwards to use this package with Fushicho versioned networks**. -Due to a network upgrade with [catapult-server@Fushicho](https://github.com/nemtech/catapult-server/releases/tag/v0.9.3.2) version, **it is recommended to use this package's 0.17.4 version and upwards to use this package with Fushicho versioned networks**. - -The upgrade to this package's [version v0.17.4](https://github.com/nemtech/symbol-sdk-typescript-javascript/releases/tag/v0.17.4) is mandatory for **fushicho compatibility**. +The upgrade to this package's [version v0.18.0](https://github.com/nemtech/symbol-sdk-typescript-javascript/releases/tag/v0.18.0) is mandatory for **fushicho compatibility**. Find the complete release notes [here](CHANGELOG.md). @@ -23,9 +21,7 @@ Find the complete release notes [here](CHANGELOG.md). ### NodeJS -- NodeJS 8.9.X -- NodeJS 9.X.X -- NodeJS 10.X.X +- NodeJS 10.X.X and above (from v0.18.0) ## Installation @@ -46,14 +42,14 @@ Use the following available resources to get help: - [Symbol Documentation][docs] - [Symbol SDK Typescript/Javascript Reference][sdk-ref] -- Join the community [slack group (#sig-api)][slack] +- Join the community [slack group (#sig-api)][slack] - If you found a bug, [open a new issue][issues] ## Contributing This project is developed and maintained by NEM Foundation. -Contributions are welcome and appreciated. +Contributions are welcome and appreciated. Check [CONTRIBUTING](CONTRIBUTING.md) for information on how to contribute. You can also find useful notes for developers under our documentation [guidelines][guidelines] section. diff --git a/e2e/infrastructure/AccountHttp.spec.ts b/e2e/infrastructure/AccountHttp.spec.ts index 8ec542f0f2..fa13a56bf0 100644 --- a/e2e/infrastructure/AccountHttp.spec.ts +++ b/e2e/infrastructure/AccountHttp.spec.ts @@ -24,7 +24,6 @@ import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; import { PublicAccount } from '../../src/model/account/PublicAccount'; import { PlainMessage } from '../../src/model/message/PlainMessage'; -import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; import { NetworkType } from '../../src/model/network/NetworkType'; @@ -93,7 +92,7 @@ describe('AccountHttp', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, - [NetworkCurrencyLocal.createAbsolute(1)], + [helper.createNetworkCurrency(1, false)], PlainMessage.create('test-message'), networkType, helper.maxFee, @@ -121,7 +120,6 @@ describe('AccountHttp', () => { }); describe('Setup test AddressAlias', () => { - it('Announce addressAliasTransaction', () => { const addressAliasTransaction = AddressAliasTransaction.create( Deadline.create(), @@ -137,29 +135,29 @@ describe('AccountHttp', () => { }); describe('Setup test multisig account', () => { - it('Announce MultisigAccountModificationTransaction', () => { const modifyMultisigAccountTransaction = MultisigAccountModificationTransaction.create( Deadline.create(), 2, 1, - [ - cosignAccount1.publicAccount, - cosignAccount2.publicAccount, - cosignAccount3.publicAccount, - ], + [cosignAccount1.publicAccount, cosignAccount2.publicAccount, cosignAccount3.publicAccount], [], networkType, helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [modifyMultisigAccountTransaction.toAggregate(multisigAccount.publicAccount)], networkType, [], - helper.maxFee); - const signedTransaction = aggregateTransaction - .signTransactionWithCosignatories(multisigAccount, [cosignAccount1, cosignAccount2, cosignAccount3], generationHash); + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signTransactionWithCosignatories( + multisigAccount, + [cosignAccount1, cosignAccount2, cosignAccount3], + generationHash, + ); return helper.announce(signedTransaction); }); @@ -187,8 +185,9 @@ describe('AccountHttp', () => { describe('getMultisigAccountGraphInfo', () => { it('should call getMultisigAccountGraphInfo successfully', async () => { - const multisigAccountGraphInfo = - await multisigRepository.getMultisigAccountGraphInfo(multisigAccount.publicAccount.address).toPromise(); + const multisigAccountGraphInfo = await multisigRepository + .getMultisigAccountGraphInfo(multisigAccount.publicAccount.address) + .toPromise(); expect(multisigAccountGraphInfo.multisigAccounts.get(0)![0].account.publicKey).to.be.equal(multisigAccount.publicKey); }); }); @@ -214,26 +213,37 @@ describe('AccountHttp', () => { describe('transactions', () => { it('should not return accounts when account does not exist', () => { - return accountRepository.getAccountInfo(Account.generateNewAccount(networkType).address).toPromise().then(() => { - return Promise.reject('should fail!'); - }, (err) => { - const error = JSON.parse(err.message); - expect(error.statusCode).to.be.eq(404); - expect(error.errorDetails.statusMessage).to.be.eq('Not Found'); - return Promise.resolve(); - }); + return accountRepository + .getAccountInfo(Account.generateNewAccount(networkType).address) + .toPromise() + .then( + () => { + return Promise.reject('should fail!'); + }, + (err) => { + const error = JSON.parse(err.message); + expect(error.statusCode).to.be.eq(404); + expect(error.errorDetails.statusMessage).to.be.eq('Not Found'); + return Promise.resolve(); + }, + ); }); }); describe('transactions', () => { it('should call transactions successfully by type', async () => { - const transactions = await accountRepository.getAccountTransactions( - publicAccount.address, new QueryParams(), new TransactionFilter({ - types: [TransactionType.TRANSFER, TransactionType.AGGREGATE_COMPLETE], - })).toPromise(); + const transactions = await accountRepository + .getAccountTransactions( + publicAccount.address, + new QueryParams(), + new TransactionFilter({ + types: [TransactionType.TRANSFER, TransactionType.AGGREGATE_COMPLETE], + }), + ) + .toPromise(); expect(transactions.length).to.be.greaterThan(0); transactions.forEach((t) => { - expect((t.type === TransactionType.TRANSFER || t.type === TransactionType.AGGREGATE_COMPLETE)).to.be.eq(true); + expect(t.type === TransactionType.TRANSFER || t.type === TransactionType.AGGREGATE_COMPLETE).to.be.eq(true); }); }); }); @@ -286,8 +296,7 @@ describe('AccountHttp', () => { -1, 0, [], - [cosignAccount1.publicAccount, - ], + [cosignAccount1.publicAccount], networkType, helper.maxFee, ); @@ -296,9 +305,7 @@ describe('AccountHttp', () => { 0, 0, [], - [ - cosignAccount2.publicAccount, - ], + [cosignAccount2.publicAccount], networkType, helper.maxFee, ); @@ -308,21 +315,27 @@ describe('AccountHttp', () => { -1, -1, [], - [ - cosignAccount3.publicAccount, - ], + [cosignAccount3.publicAccount], networkType, helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), - [removeCosigner1.toAggregate(multisigAccount.publicAccount), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), + [ + removeCosigner1.toAggregate(multisigAccount.publicAccount), removeCosigner2.toAggregate(multisigAccount.publicAccount), - removeCosigner3.toAggregate(multisigAccount.publicAccount)], + removeCosigner3.toAggregate(multisigAccount.publicAccount), + ], networkType, - [], helper.maxFee); - const signedTransaction = aggregateTransaction - .signTransactionWithCosignatories(cosignAccount1, [cosignAccount2, cosignAccount3], generationHash); + [], + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signTransactionWithCosignatories( + cosignAccount1, + [cosignAccount2, cosignAccount3], + generationHash, + ); return helper.announce(signedTransaction); }); }); diff --git a/e2e/infrastructure/BlockHttp.spec.ts b/e2e/infrastructure/BlockHttp.spec.ts index 43afb52e4f..b389ae2787 100644 --- a/e2e/infrastructure/BlockHttp.spec.ts +++ b/e2e/infrastructure/BlockHttp.spec.ts @@ -16,13 +16,11 @@ import { expect } from 'chai'; import { mergeMap } from 'rxjs/operators'; -import { BlockHttp } from '../../src/infrastructure/BlockHttp'; import { BlockRepository } from '../../src/infrastructure/BlockRepository'; import { QueryParams } from '../../src/infrastructure/QueryParams'; import { ReceiptRepository } from '../../src/infrastructure/ReceiptRepository'; import { Account } from '../../src/model/account/Account'; import { PlainMessage } from '../../src/model/message/PlainMessage'; -import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { NetworkType } from '../../src/model/network/NetworkType'; import { Deadline } from '../../src/model/transaction/Deadline'; import { TransactionInfo } from '../../src/model/transaction/TransactionInfo'; @@ -36,8 +34,6 @@ describe('BlockHttp', () => { let account2: Account; let blockRepository: BlockRepository; let receiptRepository: ReceiptRepository; - let blockReceiptHash = ''; - let blockTransactionHash = ''; let chainHeight; let generationHash: string; let networkType: NetworkType; @@ -68,12 +64,11 @@ describe('BlockHttp', () => { */ describe('Setup Test Data', () => { - it('Announce TransferTransaction', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, - [NetworkCurrencyLocal.createAbsolute(1)], + [helper.createNetworkCurrency(1, false)], PlainMessage.create('test-message'), networkType, helper.maxFee, @@ -89,8 +84,6 @@ describe('BlockHttp', () => { describe('getBlockByHeight', () => { it('should return block info given height', async () => { const blockInfo = await blockRepository.getBlockByHeight(UInt64.fromUint(1)).toPromise(); - blockReceiptHash = blockInfo.blockReceiptsHash; - blockTransactionHash = blockInfo.blockTransactionsHash; expect(blockInfo.height.lower).to.be.equal(1); expect(blockInfo.height.higher).to.be.equal(0); expect(blockInfo.timestamp.lower).to.be.equal(0); @@ -112,8 +105,9 @@ describe('BlockHttp', () => { }); it('should return block transactions data given height with paginated transactionId', async () => { - const transactions = await blockRepository.getBlockTransactions(UInt64.fromUint(1), - new QueryParams({ pageSize: 10, id: nextId})).toPromise(); + const transactions = await blockRepository + .getBlockTransactions(UInt64.fromUint(1), new QueryParams({ pageSize: 10, id: nextId })) + .toPromise(); expect(transactions[0].transactionInfo!.id).to.be.equal(firstId); expect(transactions.length).to.be.greaterThan(0); }); @@ -127,24 +121,32 @@ describe('BlockHttp', () => { }); describe('getMerkleReceipts', () => { it('should return Merkle Receipts', async () => { - const merkleReceipts = await receiptRepository.getBlockReceipts(chainHeight).pipe( - mergeMap((_) => { - return receiptRepository.getMerkleReceipts(chainHeight, _.transactionStatements[0].generateHash()); - })).toPromise(); + const merkleReceipts = await receiptRepository + .getBlockReceipts(chainHeight) + .pipe( + mergeMap((_) => { + return receiptRepository.getMerkleReceipts(chainHeight, _.transactionStatements[0].generateHash()); + }), + ) + .toPromise(); expect(merkleReceipts.merklePath).not.to.be.null; }); }); describe('getMerkleTransaction', () => { it('should return Merkle Transaction', async () => { - const merkleTransactionss = await blockRepository.getBlockTransactions(chainHeight).pipe( - mergeMap((_) => { - const hash = (_[0].transactionInfo as TransactionInfo).hash; - if (hash) { - return blockRepository.getMerkleTransaction(chainHeight, hash); - } - // If reaching this line, something is not right - throw new Error('Tansacation hash is undefined'); - })).toPromise(); + const merkleTransactionss = await blockRepository + .getBlockTransactions(chainHeight) + .pipe( + mergeMap((_) => { + const hash = (_[0].transactionInfo as TransactionInfo).hash; + if (hash) { + return blockRepository.getMerkleTransaction(chainHeight, hash); + } + // If reaching this line, something is not right + throw new Error('Tansacation hash is undefined'); + }), + ) + .toPromise(); expect(merkleTransactionss.merklePath).not.to.be.null; }); }); diff --git a/e2e/infrastructure/IntegrationTestHelper.ts b/e2e/infrastructure/IntegrationTestHelper.ts index 31939327c2..50cd9ac7c3 100644 --- a/e2e/infrastructure/IntegrationTestHelper.ts +++ b/e2e/infrastructure/IntegrationTestHelper.ts @@ -24,6 +24,9 @@ import { SignedTransaction } from '../../src/model/transaction/SignedTransaction import { Transaction } from '../../src/model/transaction/Transaction'; import { UInt64 } from '../../src/model/UInt64'; import { TransactionService } from '../../src/service/TransactionService'; +import { NetworkCurrencyPublic } from '../../src/model/mosaic/NetworkCurrencyPublic'; +import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; +import { NamespaceId } from '../../src/model/namespace/NamespaceId'; export class IntegrationTestHelper { public readonly yaml = require('js-yaml'); @@ -43,24 +46,27 @@ export class IntegrationTestHelper { public maxFee: UInt64; public harvestingAccount: Account; public transactionService: TransactionService; + public networkCurrencyNamespaceId: NamespaceId; + public networkCurrencyDivisibility: number; start(): Promise { - return new Promise( - (resolve, reject) => { - - const path = require('path'); - require('fs').readFile(path.resolve(__dirname, '../conf/network.conf'), (err, jsonData) => { - if (err) { - return reject(err); - } - const json = JSON.parse(jsonData); - console.log(`Running tests against: ${json.apiUrl}`); - this.apiUrl = json.apiUrl; - this.repositoryFactory = new RepositoryFactoryHttp(json.apiUrl); - this.transactionService = new TransactionService( - this.repositoryFactory.createTransactionRepository(), this.repositoryFactory.createReceiptRepository()); - combineLatest(this.repositoryFactory.getGenerationHash(), - this.repositoryFactory.getNetworkType()).subscribe(([generationHash, networkType]) => { + return new Promise((resolve, reject) => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const path = require('path'); + require('fs').readFile(path.resolve(__dirname, '../conf/network.conf'), (err, jsonData) => { + if (err) { + return reject(err); + } + const json = JSON.parse(jsonData); + console.log(`Running tests against: ${json.apiUrl}`); + this.apiUrl = json.apiUrl; + this.repositoryFactory = new RepositoryFactoryHttp(json.apiUrl); + this.transactionService = new TransactionService( + this.repositoryFactory.createTransactionRepository(), + this.repositoryFactory.createReceiptRepository(), + ); + combineLatest(this.repositoryFactory.getGenerationHash(), this.repositoryFactory.getNetworkType()).subscribe( + ([generationHash, networkType]) => { this.networkType = networkType; this.generationHash = generationHash; this.account = this.createAccount(json.testAccount); @@ -77,11 +83,22 @@ export class IntegrationTestHelper { // What would be the best maxFee? In the future we will load the fee multiplier from rest. this.maxFee = UInt64.fromUint(1000000); - const bootstrapRoot = process.env.CATAPULT_SERVICE_BOOTSTRAP || path.resolve(__dirname, '../../../../catapult-service-bootstrap'); + // network Currency + this.networkCurrencyNamespaceId = this.apiUrl.toLowerCase().includes('localhost') + ? NetworkCurrencyLocal.NAMESPACE_ID + : NetworkCurrencyPublic.NAMESPACE_ID; + this.networkCurrencyDivisibility = this.apiUrl.toLowerCase().includes('localhost') + ? NetworkCurrencyLocal.DIVISIBILITY + : NetworkCurrencyPublic.DIVISIBILITY; + + const bootstrapRoot = + process.env.CATAPULT_SERVICE_BOOTSTRAP || path.resolve(__dirname, '../../../../catapult-service-bootstrap'); const bootstrapPath = `${bootstrapRoot}/build/generated-addresses/addresses.yaml`; require('fs').readFile(bootstrapPath, (error: any, yamlData: any) => { if (error) { - console.log(`catapult-service-bootstrap generated address could not be loaded from path ${bootstrapPath}. Ignoring and using accounts from network.conf.`); + console.log( + `catapult-service-bootstrap generated address could not be loaded from path ${bootstrapPath}. Ignoring and using accounts from network.conf.`, + ); return resolve(this); } else { console.log(`catapult-service-bootstrap generated address loaded from path ${bootstrapPath}.`); @@ -96,25 +113,37 @@ export class IntegrationTestHelper { return resolve(this); } }); - }, (error) => { + }, + (error) => { console.log('There has been an error loading the configuration. ', error); return reject(error); - }); - }); - - }, - ); + }, + ); + }); + }); } createAccount(data): Account { return Account.createFromPrivateKey(data.privateKey ? data.privateKey : data.private, this.networkType); } + createNetworkCurrency(amount: number, isRelative = true): NetworkCurrencyPublic | NetworkCurrencyLocal { + if (this.apiUrl.toLowerCase().includes('localhost')) { + return isRelative ? NetworkCurrencyLocal.createRelative(amount) : NetworkCurrencyLocal.createAbsolute(amount); + } + return isRelative ? NetworkCurrencyPublic.createRelative(amount) : NetworkCurrencyPublic.createAbsolute(amount); + } + announce(signedTransaction: SignedTransaction): Promise { console.log(`Announcing transaction: ${signedTransaction.type}`); - return this.transactionService.announce(signedTransaction, this.listener).pipe(map((t) => { - console.log(`Transaction ${signedTransaction.type} confirmed`); - return t; - })).toPromise(); + return this.transactionService + .announce(signedTransaction, this.listener) + .pipe( + map((t) => { + console.log(`Transaction ${signedTransaction.type} confirmed`); + return t; + }), + ) + .toPromise(); } } diff --git a/e2e/infrastructure/Listener.spec.ts b/e2e/infrastructure/Listener.spec.ts index e9314050ca..b772d07032 100644 --- a/e2e/infrastructure/Listener.spec.ts +++ b/e2e/infrastructure/Listener.spec.ts @@ -17,13 +17,11 @@ import { assert, expect } from 'chai'; import { ChronoUnit } from 'js-joda'; import { filter } from 'rxjs/operators'; import { AccountRepository } from '../../src/infrastructure/AccountRepository'; -import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; import { TransactionRepository } from '../../src/infrastructure/TransactionRepository'; import { Account } from '../../src/model/account/Account'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { Address, CosignatureTransaction, LockFundsTransaction, Mosaic, SignedTransaction, UInt64 } from '../../src/model/model'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; -import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; import { NetworkType } from '../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; @@ -33,7 +31,6 @@ import { TransferTransaction } from '../../src/model/transaction/TransferTransac import { IntegrationTestHelper } from './IntegrationTestHelper'; describe('Listener', () => { - const helper = new IntegrationTestHelper(); let account: Account; let account2: Account; @@ -42,10 +39,9 @@ describe('Listener', () => { let cosignAccount2: Account; let cosignAccount3: Account; let accountRepository: AccountRepository; - let namespaceRepository: NamespaceRepository; let generationHash: string; let networkType: NetworkType; - const NetworkCurrencyLocalId: NamespaceId = NetworkCurrencyLocal.NAMESPACE_ID; + const NetworkCurrencyLocalId: NamespaceId = helper.networkCurrencyNamespaceId; let transactionRepository: TransactionRepository; before(() => { @@ -59,7 +55,6 @@ describe('Listener', () => { generationHash = helper.generationHash; networkType = helper.networkType; accountRepository = helper.repositoryFactory.createAccountRepository(); - namespaceRepository = helper.repositoryFactory.createNamespaceRepository(); transactionRepository = helper.repositoryFactory.createTransactionRepository(); }); }); @@ -75,49 +70,52 @@ describe('Listener', () => { setTimeout(done, 200); }); - const createSignedAggregatedBondTransaction = (aggregatedTo: Account, - signer: Account, - recipient: Address): SignedTransaction => { + const createSignedAggregatedBondTransaction = (aggregatedTo: Account, signer: Account, recipient: Address): SignedTransaction => { const transferTransaction = TransferTransaction.create( Deadline.create(), recipient, [], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const aggregateTransaction = AggregateTransaction.createBonded( Deadline.create(2, ChronoUnit.MINUTES), [transferTransaction.toAggregate(aggregatedTo.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); return signer.sign(aggregateTransaction, generationHash); }; - const createHashLockTransactionAndAnnounce = (signedAggregatedTransaction: SignedTransaction, - signer: Account, - mosaicId: MosaicId | NamespaceId) => { + const createHashLockTransactionAndAnnounce = ( + signedAggregatedTransaction: SignedTransaction, + signer: Account, + mosaicId: MosaicId | NamespaceId, + ): void => { const lockFundsTransaction = LockFundsTransaction.create( Deadline.create(), - new Mosaic(mosaicId, UInt64.fromUint(10 * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY))), + new Mosaic(mosaicId, UInt64.fromUint(10 * Math.pow(10, helper.networkCurrencyDivisibility))), UInt64.fromUint(1000), signedAggregatedTransaction, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedLockFundsTransaction = signer.sign(lockFundsTransaction, generationHash); transactionRepository.announce(signedLockFundsTransaction); }; describe('Confirmed', () => { - it('confirmedTransactionsGiven address signer', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account.address, [], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = account.sign(transferTransaction, generationHash); return helper.announce(signedTransaction); @@ -125,7 +123,6 @@ describe('Listener', () => { }); describe('Confirmed', () => { - it('confirmedTransactionsGiven address recipient', () => { const recipientAddress = account2.address; const transferTransaction = TransferTransaction.create( @@ -133,7 +130,8 @@ describe('Listener', () => { recipientAddress, [], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = account.sign(transferTransaction, generationHash); return helper.announce(signedTransaction); @@ -141,21 +139,22 @@ describe('Listener', () => { }); describe('UnConfirmed', () => { - it('unconfirmedTransactionsAdded', (done) => { - const transferTransaction = TransferTransaction.create( Deadline.create(), account.address, [], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = account.sign(transferTransaction, generationHash); - helper.listener.unconfirmedAdded(account.address).pipe( - filter((_) => _.transactionInfo!.hash === signedTransaction.hash)).subscribe(() => { - done(); - }); + helper.listener + .unconfirmedAdded(account.address) + .pipe(filter((_) => _.transactionInfo!.hash === signedTransaction.hash)) + .subscribe(() => { + done(); + }); transactionRepository.announce(signedTransaction); }); @@ -165,12 +164,16 @@ describe('Listener', () => { account.address, [], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = account.sign(transferTransaction, generationHash); - helper.listener.unconfirmedRemoved(account.address).pipe(filter((hash) => hash === signedTransaction.hash)).subscribe(() => { - done(); - }); + helper.listener + .unconfirmedRemoved(account.address) + .pipe(filter((hash) => hash === signedTransaction.hash)) + .subscribe(() => { + done(); + }); transactionRepository.announce(signedTransaction); }); }); @@ -180,9 +183,10 @@ describe('Listener', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), cosignAccount1.address, - [new Mosaic(NetworkCurrencyLocalId, UInt64.fromUint(10 * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY)))], + [new Mosaic(NetworkCurrencyLocalId, UInt64.fromUint(10 * Math.pow(10, helper.networkCurrencyDivisibility)))], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = transferTransaction.signWith(account, generationHash); @@ -191,33 +195,35 @@ describe('Listener', () => { }); describe('MultisigAccountModificationTransaction - Create multisig account', () => { - it('MultisigAccountModificationTransaction', () => { const modifyMultisigAccountTransaction = MultisigAccountModificationTransaction.create( Deadline.create(), 2, 1, - [cosignAccount1.publicAccount, - cosignAccount2.publicAccount, - cosignAccount3.publicAccount, - ], + [cosignAccount1.publicAccount, cosignAccount2.publicAccount, cosignAccount3.publicAccount], [], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [modifyMultisigAccountTransaction.toAggregate(multisigAccount.publicAccount)], networkType, - [], helper.maxFee); - const signedTransaction = aggregateTransaction - .signTransactionWithCosignatories(multisigAccount, [cosignAccount1, cosignAccount2, cosignAccount3], generationHash); + [], + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signTransactionWithCosignatories( + multisigAccount, + [cosignAccount1, cosignAccount2, cosignAccount3], + generationHash, + ); return helper.announce(signedTransaction); }); }); describe('Aggregate Bonded Transactions', () => { - it('aggregateBondedTransactionsAdded', (done) => { const signedAggregatedTx = createSignedAggregatedBondTransaction(multisigAccount, account, account2.address); createHashLockTransactionAndAnnounce(signedAggregatedTx, account, NetworkCurrencyLocalId); @@ -236,8 +242,7 @@ describe('Listener', () => { }); describe('Aggregate Bonded Transactions', () => { it('aggregateBondedTransactionsRemoved', (done) => { - const signedAggregatedTx = - createSignedAggregatedBondTransaction(multisigAccount, cosignAccount1, account2.address); + const signedAggregatedTx = createSignedAggregatedBondTransaction(multisigAccount, cosignAccount1, account2.address); createHashLockTransactionAndAnnounce(signedAggregatedTx, cosignAccount1, NetworkCurrencyLocalId); helper.listener.confirmed(cosignAccount1.address).subscribe(() => { @@ -250,7 +255,6 @@ describe('Listener', () => { const cosignatureTransaction = CosignatureTransaction.create(transactionToCosign); const cosignatureSignedTransaction = cosignAccount2.signCosignatureTransaction(cosignatureTransaction); transactionRepository.announceAggregateBondedCosignature(cosignatureSignedTransaction); - }); }); helper.listener.status(cosignAccount1.address).subscribe((error) => { @@ -269,10 +273,8 @@ describe('Listener', () => { }); describe('Aggregate Bonded Transactions', () => { - it('cosignatureAdded', (done) => { - const signedAggregatedTx = - createSignedAggregatedBondTransaction(multisigAccount, cosignAccount1, account2.address); + const signedAggregatedTx = createSignedAggregatedBondTransaction(multisigAccount, cosignAccount1, account2.address); createHashLockTransactionAndAnnounce(signedAggregatedTx, cosignAccount1, NetworkCurrencyLocalId); helper.listener.cosignatureAdded(cosignAccount1.address).subscribe(() => { @@ -298,7 +300,6 @@ describe('Listener', () => { }); describe('MultisigAccountModificationTransaction - Restore multisig Accounts', () => { - it('Restore Multisig Account', () => { const removeCosigner1 = MultisigAccountModificationTransaction.create( Deadline.create(), @@ -326,40 +327,49 @@ describe('Listener', () => { networkType, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), - [removeCosigner1.toAggregate(multisigAccount.publicAccount), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), + [ + removeCosigner1.toAggregate(multisigAccount.publicAccount), removeCosigner2.toAggregate(multisigAccount.publicAccount), - removeCosigner3.toAggregate(multisigAccount.publicAccount)], + removeCosigner3.toAggregate(multisigAccount.publicAccount), + ], networkType, - []); - const signedTransaction = aggregateTransaction - .signTransactionWithCosignatories(cosignAccount1, [cosignAccount2, cosignAccount3], generationHash); + [], + ); + const signedTransaction = aggregateTransaction.signTransactionWithCosignatories( + cosignAccount1, + [cosignAccount2, cosignAccount3], + generationHash, + ); return helper.announce(signedTransaction); }); }); describe('Transactions Status', () => { - it('transactionStatusGiven', () => { - const mosaics = [NetworkCurrencyLocal.createRelative(1000000000000)]; + const mosaics = [helper.createNetworkCurrency(1000000000000)]; const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, mosaics, PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - return helper.announce(transferTransaction.signWith(account, generationHash)).then(() => { - throw new Error('Transaction should have failed!!'); - }, (error) => { - expect(error.code).to.be.equal('Failure_Core_Insufficient_Balance'); - }); + return helper.announce(transferTransaction.signWith(account, generationHash)).then( + () => { + throw new Error('Transaction should have failed!!'); + }, + (error) => { + expect(error.code).to.be.equal('Failure_Core_Insufficient_Balance'); + }, + ); }); }); describe('New Block', () => { - it('newBlock', (done) => { helper.listener.newBlock().subscribe(() => { done(); @@ -369,7 +379,8 @@ describe('Listener', () => { account2.address, [], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); helper.announce(transferTransaction.signWith(account, generationHash)); diff --git a/e2e/infrastructure/MetadataHttp.spec.ts b/e2e/infrastructure/MetadataHttp.spec.ts index ef5b10e433..a0b3d5eec8 100644 --- a/e2e/infrastructure/MetadataHttp.spec.ts +++ b/e2e/infrastructure/MetadataHttp.spec.ts @@ -34,7 +34,6 @@ import { UInt64 } from '../../src/model/UInt64'; import { IntegrationTestHelper } from './IntegrationTestHelper'; describe('MetadataHttp', () => { - const helper = new IntegrationTestHelper(); let account: Account; let accountAddress: Address; @@ -69,7 +68,6 @@ describe('MetadataHttp', () => { */ describe('MosaicDefinitionTransaction', () => { - it('standalone', () => { const nonce = MosaicNonce.createRandom(); mosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); @@ -89,7 +87,6 @@ describe('MetadataHttp', () => { }); describe('Setup test NamespaceId', () => { - it('Announce NamespaceRegistrationTransaction', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( @@ -117,7 +114,8 @@ describe('MetadataHttp', () => { helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [accountMetadataTransaction.toAggregate(account.publicAccount)], networkType, [], @@ -140,7 +138,8 @@ describe('MetadataHttp', () => { helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicMetadataTransaction.toAggregate(account.publicAccount)], networkType, [], @@ -152,7 +151,6 @@ describe('MetadataHttp', () => { }); describe('NamespaceMetadataTransaction', () => { - it('aggregate', () => { const namespaceMetadataTransaction = NamespaceMetadataTransaction.create( Deadline.create(), @@ -165,7 +163,8 @@ describe('MetadataHttp', () => { helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [namespaceMetadataTransaction.toAggregate(account.publicAccount)], networkType, [], @@ -210,8 +209,9 @@ describe('MetadataHttp', () => { describe('getAccountMetadataByKeyAndSender', () => { it('should return metadata given a NEM Address and metadata key and sender public key', async () => { - const metadata = await metadataRepository.getAccountMetadataByKeyAndSender( - accountAddress, UInt64.fromUint(5).toHex(), account.publicKey).toPromise(); + const metadata = await metadataRepository + .getAccountMetadataByKeyAndSender(accountAddress, UInt64.fromUint(5).toHex(), account.publicKey) + .toPromise(); expect(metadata.metadataEntry.scopedMetadataKey.toString()).to.be.equal('5'); expect(metadata.metadataEntry.senderPublicKey).to.be.equal(account.publicKey); expect(metadata.metadataEntry.targetPublicKey).to.be.equal(account.publicKey); @@ -249,8 +249,9 @@ describe('MetadataHttp', () => { describe('getMosaicMetadataByKeyAndSender', () => { it('should return metadata given a mosaicId and metadata key and sender public key', async () => { - const metadata = await metadataRepository.getMosaicMetadataByKeyAndSender( - mosaicId, UInt64.fromUint(5).toHex(), account.publicKey).toPromise(); + const metadata = await metadataRepository + .getMosaicMetadataByKeyAndSender(mosaicId, UInt64.fromUint(5).toHex(), account.publicKey) + .toPromise(); expect(metadata.metadataEntry.scopedMetadataKey.toString()).to.be.equal('5'); expect(metadata.metadataEntry.senderPublicKey).to.be.equal(account.publicKey); expect(metadata.metadataEntry.targetPublicKey).to.be.equal(account.publicKey); @@ -288,8 +289,9 @@ describe('MetadataHttp', () => { describe('getNamespaceMetadataByKeyAndSender', () => { it('should return metadata given a namespaceId and metadata key and sender public key', async () => { - const metadata = await metadataRepository.getNamespaceMetadataByKeyAndSender( - namespaceId, UInt64.fromUint(5).toHex(), account.publicKey).toPromise(); + const metadata = await metadataRepository + .getNamespaceMetadataByKeyAndSender(namespaceId, UInt64.fromUint(5).toHex(), account.publicKey) + .toPromise(); expect(metadata.metadataEntry.scopedMetadataKey.toString()).to.be.equal('5'); expect(metadata.metadataEntry.senderPublicKey).to.be.equal(account.publicKey); expect(metadata.metadataEntry.targetPublicKey).to.be.equal(account.publicKey); diff --git a/e2e/infrastructure/MosaicHttp.spec.ts b/e2e/infrastructure/MosaicHttp.spec.ts index 2cac52791b..73fb65744a 100644 --- a/e2e/infrastructure/MosaicHttp.spec.ts +++ b/e2e/infrastructure/MosaicHttp.spec.ts @@ -31,7 +31,6 @@ import { UInt64 } from '../../src/model/UInt64'; import { IntegrationTestHelper } from './IntegrationTestHelper'; describe('MosaicHttp', () => { - let mosaicId: MosaicId; let mosaicRepository: MosaicRepository; let account: Account; @@ -64,7 +63,6 @@ describe('MosaicHttp', () => { * ========================= */ describe('Setup test MosaicId', () => { - it('Announce MosaicDefinitionTransaction', async () => { const nonce = MosaicNonce.createFromNumber(-1501238750); expect(nonce.toDTO()).to.be.equals(2793728546); @@ -82,13 +80,15 @@ describe('MosaicHttp', () => { ); const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); - const listenedTransaction = await helper.announce(signedTransaction) as MosaicDefinitionTransaction; + const listenedTransaction = (await helper.announce(signedTransaction)) as MosaicDefinitionTransaction; expect(mosaicDefinitionTransaction.nonce.toHex()).to.be.equal(listenedTransaction.nonce.toHex()); expect(mosaicDefinitionTransaction.nonce).to.deep.equal(listenedTransaction.nonce); expect(mosaicDefinitionTransaction.getMosaicNonceIntValue()).to.be.equal(listenedTransaction.getMosaicNonceIntValue()); - const savedTransaction = await helper.repositoryFactory.createTransactionRepository() - .getTransaction(signedTransaction.hash).toPromise() as MosaicDefinitionTransaction; + const savedTransaction = (await helper.repositoryFactory + .createTransactionRepository() + .getTransaction(signedTransaction.hash) + .toPromise()) as MosaicDefinitionTransaction; expect(mosaicDefinitionTransaction.nonce.toHex()).to.be.equal(savedTransaction.nonce.toHex()); expect(mosaicDefinitionTransaction.nonce).to.deep.equal(savedTransaction.nonce); expect(mosaicDefinitionTransaction.getMosaicNonceIntValue()).to.be.equal(savedTransaction.getMosaicNonceIntValue()); @@ -96,7 +96,6 @@ describe('MosaicHttp', () => { }); describe('Setup test NamespaceId', () => { - it('Announce NamespaceRegistrationTransaction', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( @@ -113,7 +112,6 @@ describe('MosaicHttp', () => { }); }); describe('Setup test MosaicAlias', () => { - it('Announce MosaicAliasTransaction', () => { const mosaicAliasTransaction = MosaicAliasTransaction.create( Deadline.create(), @@ -182,7 +180,6 @@ describe('MosaicHttp', () => { * ========================= */ describe('Remove test MosaicAlias', () => { - it('Announce MosaicAliasTransaction', () => { const mosaicAliasTransaction = MosaicAliasTransaction.create( Deadline.create(), diff --git a/e2e/infrastructure/NamespaceHttp.spec.ts b/e2e/infrastructure/NamespaceHttp.spec.ts index 2f99342369..35a6735b39 100644 --- a/e2e/infrastructure/NamespaceHttp.spec.ts +++ b/e2e/infrastructure/NamespaceHttp.spec.ts @@ -18,7 +18,6 @@ import { expect } from 'chai'; import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; import { Account } from '../../src/model/account/Account'; import { Address } from '../../src/model/account/Address'; -import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; import { AddressAliasTransaction } from '../../src/model/transaction/AddressAliasTransaction'; @@ -28,7 +27,7 @@ import { UInt64 } from '../../src/model/UInt64'; import { IntegrationTestHelper } from './IntegrationTestHelper'; describe('NamespaceHttp', () => { - const defaultNamespaceId = NetworkCurrencyLocal.NAMESPACE_ID; + let defaultNamespaceId: NamespaceId; let namespaceId: NamespaceId; let namespaceRepository: NamespaceRepository; let account: Account; @@ -40,6 +39,7 @@ describe('NamespaceHttp', () => { account = helper.account; generationHash = helper.generationHash; namespaceRepository = helper.repositoryFactory.createNamespaceRepository(); + defaultNamespaceId = helper.networkCurrencyNamespaceId; }); }); @@ -52,7 +52,6 @@ describe('NamespaceHttp', () => { }); describe('NamespaceRegistrationTransaction', () => { - it('standalone', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( @@ -68,7 +67,6 @@ describe('NamespaceHttp', () => { }); }); describe('AddressAliasTransaction', () => { - it('standalone', () => { const addressAliasTransaction = AddressAliasTransaction.create( Deadline.create(), @@ -104,7 +102,6 @@ describe('NamespaceHttp', () => { const namespaces = await namespaceRepository.getNamespacesFromAccounts([account.address]).toPromise(); deepEqual(namespaces[0].owner, account.publicAccount); }); - }); describe('getNamespacesName', () => { diff --git a/e2e/infrastructure/RestrictionHttp.spec.ts b/e2e/infrastructure/RestrictionHttp.spec.ts index d1dc9511bc..f3b0aaa95f 100644 --- a/e2e/infrastructure/RestrictionHttp.spec.ts +++ b/e2e/infrastructure/RestrictionHttp.spec.ts @@ -73,7 +73,6 @@ describe('RestrictionHttp', () => { * ========================= */ describe('MosaicDefinitionTransaction', () => { - it('standalone', () => { const nonce = MosaicNonce.createRandom(); mosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); @@ -84,7 +83,8 @@ describe('RestrictionHttp', () => { MosaicFlags.create(true, true, true), 3, UInt64.fromUint(1000), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -92,7 +92,6 @@ describe('RestrictionHttp', () => { }); describe('MosaicDefinitionTransaction', () => { - it('standalone', () => { const nonce = MosaicNonce.createRandom(); referenceMosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); @@ -103,7 +102,8 @@ describe('RestrictionHttp', () => { MosaicFlags.create(true, true, true), 3, UInt64.fromUint(1000), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -111,14 +111,14 @@ describe('RestrictionHttp', () => { }); describe('Setup Test AccountAddressRestriction', () => { - it('Announce AccountRestrictionTransaction', () => { const addressModification = AccountRestrictionTransaction.createAddressRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.AllowIncomingAddress, [account3.address], [], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressModification.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -126,7 +126,6 @@ describe('RestrictionHttp', () => { }); describe('MosaicGlobalRestrictionTransaction - Reference', () => { - it('standalone', () => { const mosaicGlobalRestrictionTransaction = MosaicGlobalRestrictionTransaction.create( Deadline.create(), @@ -136,7 +135,9 @@ describe('RestrictionHttp', () => { MosaicRestrictionType.NONE, UInt64.fromUint(0), MosaicRestrictionType.GE, - networkType, undefined, helper.maxFee, + networkType, + undefined, + helper.maxFee, ); const signedTransaction = mosaicGlobalRestrictionTransaction.signWith(account, generationHash); @@ -154,7 +155,9 @@ describe('RestrictionHttp', () => { MosaicRestrictionType.NONE, UInt64.fromUint(0), MosaicRestrictionType.GE, - networkType, undefined, helper.maxFee, + networkType, + undefined, + helper.maxFee, // TODO: // referenceMosaicId, ); @@ -164,7 +167,6 @@ describe('RestrictionHttp', () => { }); describe('MosaicAddressRestrictionTransaction', () => { - it('aggregate', () => { const mosaicAddressRestrictionTransaction = MosaicAddressRestrictionTransaction.create( Deadline.create(), @@ -172,12 +174,15 @@ describe('RestrictionHttp', () => { UInt64.fromUint(60641), account3.address, UInt64.fromUint(2), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicAddressRestrictionTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -192,7 +197,6 @@ describe('RestrictionHttp', () => { describe('getAccountRestrictions', () => { it('should call getAccountRestrictions successfully', async () => { - const accountRestrictions = await restrictionAccountRepository.getAccountRestrictions(accountAddress).toPromise(); expect(accountRestrictions.length).to.be.greaterThan(0); }); @@ -217,8 +221,9 @@ describe('RestrictionHttp', () => { describe('getMosaicAddressRestrictions', () => { it('should call getMosaicAddressRestrictions successfully', async () => { - const mosaicRestriction = - await restrictionMosaicRepository.getMosaicAddressRestrictions(mosaicId, [account3.address]).toPromise(); + const mosaicRestriction = await restrictionMosaicRepository + .getMosaicAddressRestrictions(mosaicId, [account3.address]) + .toPromise(); deepEqual(mosaicRestriction[0].mosaicId.toHex(), mosaicId.toHex()); deepEqual(mosaicRestriction[0].entryType, MosaicRestrictionEntryType.ADDRESS); deepEqual(mosaicRestriction[0].targetAddress.plain(), account3.address.plain()); @@ -231,12 +236,15 @@ describe('RestrictionHttp', () => { const mosaicRestriction = await restrictionMosaicRepository.getMosaicGlobalRestriction(mosaicId).toPromise(); deepEqual(mosaicRestriction.mosaicId.toHex(), mosaicId.toHex()); deepEqual(mosaicRestriction.entryType, MosaicRestrictionEntryType.GLOBAL); - deepEqual(mosaicRestriction.restrictions.get(UInt64.fromUint(60641).toString())!.referenceMosaicId.toHex(), - new MosaicId(UInt64.fromUint(0).toHex()).toHex()); - deepEqual(mosaicRestriction.restrictions.get(UInt64.fromUint(60641).toString())!.restrictionType, - MosaicRestrictionType.GE); - deepEqual(mosaicRestriction.restrictions.get(UInt64.fromUint(60641).toString())!.restrictionValue.toString(), - UInt64.fromUint(0).toString()); + deepEqual( + mosaicRestriction.restrictions.get(UInt64.fromUint(60641).toString())!.referenceMosaicId.toHex(), + new MosaicId(UInt64.fromUint(0).toHex()).toHex(), + ); + deepEqual(mosaicRestriction.restrictions.get(UInt64.fromUint(60641).toString())!.restrictionType, MosaicRestrictionType.GE); + deepEqual( + mosaicRestriction.restrictions.get(UInt64.fromUint(60641).toString())!.restrictionValue.toString(), + UInt64.fromUint(0).toString(), + ); }); }); @@ -245,12 +253,15 @@ describe('RestrictionHttp', () => { const mosaicRestriction = await restrictionMosaicRepository.getMosaicGlobalRestrictions([mosaicId]).toPromise(); deepEqual(mosaicRestriction[0].mosaicId.toHex(), mosaicId.toHex()); deepEqual(mosaicRestriction[0].entryType, MosaicRestrictionEntryType.GLOBAL); - deepEqual(mosaicRestriction[0].restrictions.get(UInt64.fromUint(60641).toString())!.referenceMosaicId.toHex(), - new MosaicId(UInt64.fromUint(0).toHex()).toHex()); - deepEqual(mosaicRestriction[0].restrictions.get(UInt64.fromUint(60641).toString())!.restrictionType, - MosaicRestrictionType.GE); - deepEqual(mosaicRestriction[0].restrictions.get(UInt64.fromUint(60641).toString())!.restrictionValue.toString(), - UInt64.fromUint(0).toString()); + deepEqual( + mosaicRestriction[0].restrictions.get(UInt64.fromUint(60641).toString())!.referenceMosaicId.toHex(), + new MosaicId(UInt64.fromUint(0).toHex()).toHex(), + ); + deepEqual(mosaicRestriction[0].restrictions.get(UInt64.fromUint(60641).toString())!.restrictionType, MosaicRestrictionType.GE); + deepEqual( + mosaicRestriction[0].restrictions.get(UInt64.fromUint(60641).toString())!.restrictionValue.toString(), + UInt64.fromUint(0).toString(), + ); }); }); @@ -266,7 +277,8 @@ describe('RestrictionHttp', () => { AccountRestrictionFlags.AllowIncomingAddress, [], [account3.address], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressModification.signWith(account, generationHash); return helper.announce(signedTransaction); diff --git a/e2e/infrastructure/TransactionHttp.spec.ts b/e2e/infrastructure/TransactionHttp.spec.ts index 01c29ccbc4..9b34979674 100644 --- a/e2e/infrastructure/TransactionHttp.spec.ts +++ b/e2e/infrastructure/TransactionHttp.spec.ts @@ -1,5 +1,5 @@ /* - * Copyright 2018 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,27 +14,21 @@ * limitations under the License. */ import { expect } from 'chai'; -import * as CryptoJS from 'crypto-js'; import { ChronoUnit } from 'js-joda'; -import { keccak_256, sha3_256 } from 'js-sha3'; +import { sha3_256 } from 'js-sha3'; import { Crypto } from '../../src/core/crypto'; import { Convert, Convert as convert } from '../../src/core/format'; import { TransactionMapping } from '../../src/core/utils/TransactionMapping'; import { AccountRepository } from '../../src/infrastructure/AccountRepository'; -import { MultisigRepository } from '../../src/infrastructure/MultisigRepository'; import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; -import { RepositoryFactory } from '../../src/infrastructure/RepositoryFactory'; import { TransactionRepository } from '../../src/infrastructure/TransactionRepository'; import { Account } from '../../src/model/account/Account'; -import { Address } from '../../src/model/account/Address'; -import { PublicAccount } from '../../src/model/account/PublicAccount'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { Mosaic } from '../../src/model/mosaic/Mosaic'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { MosaicNonce } from '../../src/model/mosaic/MosaicNonce'; import { MosaicSupplyChangeAction } from '../../src/model/mosaic/MosaicSupplyChangeAction'; -import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; import { AliasAction } from '../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; import { NetworkType } from '../../src/model/network/NetworkType'; @@ -54,7 +48,7 @@ import { CosignatureSignedTransaction } from '../../src/model/transaction/Cosign import { CosignatureTransaction } from '../../src/model/transaction/CosignatureTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { HashLockTransaction } from '../../src/model/transaction/HashLockTransaction'; -import { HashType } from '../../src/model/transaction/HashType'; +import { LockHashAlgorithm } from '../../src/model/transaction/LockHashAlgorithm'; import { LinkAction } from '../../src/model/transaction/LinkAction'; import { LockFundsTransaction } from '../../src/model/transaction/LockFundsTransaction'; import { MosaicAddressRestrictionTransaction } from '../../src/model/transaction/MosaicAddressRestrictionTransaction'; @@ -71,6 +65,10 @@ import { TransactionType } from '../../src/model/transaction/TransactionType'; import { TransferTransaction } from '../../src/model/transaction/TransferTransaction'; import { UInt64 } from '../../src/model/UInt64'; import { IntegrationTestHelper } from './IntegrationTestHelper'; +import { LockHashUtils } from '../../src/core/utils/LockHashUtils'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const CryptoJS = require('crypto-js'); describe('TransactionHttp', () => { let transactionHash; @@ -82,14 +80,7 @@ describe('TransactionHttp', () => { let account3: Account; let multisigAccount: Account; let cosignAccount1: Account; - let cosignAccount2: Account; - let cosignAccount3: Account; - let accountAddress: Address; - let accountPublicKey: string; - let publicAccount: PublicAccount; - let repositoryFactory: RepositoryFactory; let accountRepository: AccountRepository; - let multisigRepository: MultisigRepository; let namespaceRepository: NamespaceRepository; let generationHash: string; let networkType: NetworkType; @@ -98,8 +89,11 @@ describe('TransactionHttp', () => { let namespaceId: NamespaceId; let harvestingAccount: Account; let transactionRepository: TransactionRepository; + // eslint-disable-next-line @typescript-eslint/no-var-requires const secureRandom = require('secure-random'); + // eslint-disable-next-line @typescript-eslint/no-var-requires const sha256 = require('js-sha256'); + // eslint-disable-next-line @typescript-eslint/no-var-requires const ripemd160 = require('ripemd160'); before(() => { @@ -109,17 +103,10 @@ describe('TransactionHttp', () => { account3 = helper.account3; multisigAccount = helper.multisigAccount; cosignAccount1 = helper.cosignAccount1; - cosignAccount2 = helper.cosignAccount2; - cosignAccount3 = helper.cosignAccount3; - accountAddress = helper.account.address; harvestingAccount = helper.harvestingAccount; - accountPublicKey = helper.account.publicKey; - publicAccount = helper.account.publicAccount; generationHash = helper.generationHash; networkType = helper.networkType; - repositoryFactory = helper.repositoryFactory; accountRepository = helper.repositoryFactory.createAccountRepository(); - multisigRepository = helper.repositoryFactory.createMultisigRepository(); namespaceRepository = helper.repositoryFactory.createNamespaceRepository(); transactionRepository = helper.repositoryFactory.createTransactionRepository(); }); @@ -134,13 +121,11 @@ describe('TransactionHttp', () => { describe('Get network currency mosaic id', () => { it('get mosaicId', async () => { - NetworkCurrencyLocalId = - (await namespaceRepository.getLinkedMosaicId(new NamespaceId('cat.currency')).toPromise()) as MosaicId; + NetworkCurrencyLocalId = (await namespaceRepository.getLinkedMosaicId(new NamespaceId('cat.currency')).toPromise()) as MosaicId; }); }); describe('MosaicDefinitionTransaction', () => { - it('standalone', () => { const nonce = MosaicNonce.createRandom(); mosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); @@ -169,7 +154,6 @@ describe('TransactionHttp', () => { }); describe('MosaicDefinitionTransaction', () => { - it('aggregate', () => { const nonce = MosaicNonce.createRandom(); const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( @@ -182,17 +166,19 @@ describe('TransactionHttp', () => { networkType, helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicDefinitionTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); }); }); describe('AccountMetadataTransaction', () => { - it('aggregate', () => { const accountMetadataTransaction = AccountMetadataTransaction.create( Deadline.create(), @@ -204,7 +190,8 @@ describe('TransactionHttp', () => { helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [accountMetadataTransaction.toAggregate(account.publicAccount)], networkType, [], @@ -224,7 +211,6 @@ describe('TransactionHttp', () => { }); describe('MosaicMetadataTransaction', () => { - it('aggregate', () => { const mosaicMetadataTransaction = MosaicMetadataTransaction.create( Deadline.create(), @@ -233,13 +219,16 @@ describe('TransactionHttp', () => { mosaicId, 10, Convert.uint8ToUtf8(new Uint8Array(10)), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicMetadataTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction).then((transaction: AggregateTransaction) => { @@ -250,7 +239,6 @@ describe('TransactionHttp', () => { expect((innerTx as MosaicMetadataTransaction).value, 'Value').not.to.be.undefined; expect((innerTx as MosaicMetadataTransaction).targetMosaicId, 'TargetMosaicId').not.to.be.undefined; }); - }); }); }); @@ -262,7 +250,8 @@ describe('TransactionHttp', () => { Deadline.create(), namespaceName, UInt64.fromUint(10), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); namespaceId = new NamespaceId(namespaceName); const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); @@ -275,18 +264,21 @@ describe('TransactionHttp', () => { }); describe('NamespaceRegistrationTransaction', () => { - it('aggregate', () => { const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( Deadline.create(), 'root-test-namespace-' + Math.floor(Math.random() * 10000), UInt64.fromUint(5), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [registerNamespaceTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); }); @@ -301,13 +293,16 @@ describe('TransactionHttp', () => { namespaceId, 10, Convert.uint8ToUtf8(new Uint8Array(10)), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [namespaceMetadataTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction).then((transaction: AggregateTransaction) => { @@ -332,7 +327,9 @@ describe('TransactionHttp', () => { MosaicRestrictionType.NONE, UInt64.fromUint(0), MosaicRestrictionType.GE, - networkType, undefined, helper.maxFee, + networkType, + undefined, + helper.maxFee, ); const signedTransaction = mosaicGlobalRestrictionTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -348,12 +345,16 @@ describe('TransactionHttp', () => { MosaicRestrictionType.GE, UInt64.fromUint(1), MosaicRestrictionType.GE, - networkType, undefined, helper.maxFee, + networkType, + undefined, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicGlobalRestrictionTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -361,7 +362,6 @@ describe('TransactionHttp', () => { }); describe('MosaicAddressRestrictionTransaction', () => { - it('aggregate', () => { const mosaicAddressRestrictionTransaction = MosaicAddressRestrictionTransaction.create( Deadline.create(), @@ -369,12 +369,15 @@ describe('TransactionHttp', () => { UInt64.fromUint(60641), account3.address, UInt64.fromUint(2), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicAddressRestrictionTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -386,9 +389,10 @@ describe('TransactionHttp', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, - [NetworkCurrencyLocal.createAbsolute(1)], + [helper.createNetworkCurrency(1, false)], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = transferTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -399,14 +403,17 @@ describe('TransactionHttp', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, - [NetworkCurrencyLocal.createAbsolute(1)], + [helper.createNetworkCurrency(1, false)], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -419,7 +426,8 @@ describe('TransactionHttp', () => { AccountRestrictionFlags.BlockOutgoingAddress, [account3.address], [], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressModification.signWith(account, generationHash); @@ -430,19 +438,21 @@ describe('TransactionHttp', () => { }); }); describe('AccountRestrictionTransaction - Outgoing Address', () => { - it('aggregate', () => { const addressModification = AccountRestrictionTransaction.createAddressRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.BlockOutgoingAddress, [], [account3.address], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [addressModification.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -450,14 +460,14 @@ describe('TransactionHttp', () => { }); describe('AccountRestrictionTransaction - Incoming Address', () => { - it('standalone', () => { const addressModification = AccountRestrictionTransaction.createAddressRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.BlockIncomingAddress, [account3.address], [], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressModification.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -470,30 +480,30 @@ describe('TransactionHttp', () => { AccountRestrictionFlags.BlockIncomingAddress, [], [account3.address], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [addressModification.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); }); }); describe('AccountRestrictionTransaction - Mosaic', () => { - it('standalone', () => { - AccountRestrictionModification.createForMosaic( - AccountRestrictionModificationAction.Add, - mosaicId, - ); + AccountRestrictionModification.createForMosaic(AccountRestrictionModificationAction.Add, mosaicId); const addressModification = AccountRestrictionTransaction.createMosaicRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.BlockMosaic, [mosaicId], [], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressModification.signWith(account, generationHash); @@ -505,33 +515,35 @@ describe('TransactionHttp', () => { }); }); describe('AccountRestrictionTransaction - Mosaic', () => { - it('aggregate', () => { const addressModification = AccountRestrictionTransaction.createMosaicRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.BlockMosaic, [], [mosaicId], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [addressModification.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); }); }); describe('AccountRestrictionTransaction - Incoming Operation', () => { - it('standalone', () => { const addressModification = AccountRestrictionTransaction.createOperationRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.BlockIncomingTransactionType, [TransactionType.ACCOUNT_LINK], [], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressModification.signWith(account3, generationHash); @@ -543,19 +555,21 @@ describe('TransactionHttp', () => { }); }); describe('AccountRestrictionTransaction - Incoming Operation', () => { - it('aggregate', () => { const addressModification = AccountRestrictionTransaction.createOperationRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.BlockIncomingTransactionType, [], [TransactionType.ACCOUNT_LINK], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [addressModification.toAggregate(account3.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account3, generationHash); return helper.announce(signedTransaction); @@ -563,18 +577,15 @@ describe('TransactionHttp', () => { }); describe('AccountRestrictionTransaction - Outgoing Operation', () => { - it('standalone', () => { - AccountRestrictionModification.createForOperation( - AccountRestrictionModificationAction.Add, - TransactionType.ACCOUNT_LINK, - ); + AccountRestrictionModification.createForOperation(AccountRestrictionModificationAction.Add, TransactionType.ACCOUNT_LINK); const addressModification = AccountRestrictionTransaction.createOperationRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.BlockOutgoingTransactionType, [TransactionType.ACCOUNT_LINK], [], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressModification.signWith(account3, generationHash); @@ -583,38 +594,38 @@ describe('TransactionHttp', () => { expect(transaction.restrictionDeletions, 'RestrictionDeletions').not.to.be.undefined; expect(transaction.restrictionFlags, 'RestrictionFlags').not.to.be.undefined; }); - }); }); describe('AccountRestrictionTransaction - Outgoing Operation', () => { - it('aggregate', () => { const addressModification = AccountRestrictionTransaction.createOperationRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.BlockOutgoingTransactionType, [], [TransactionType.ACCOUNT_LINK], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [addressModification.toAggregate(account3.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account3, generationHash); return helper.announce(signedTransaction); - }); }); describe('AccountLinkTransaction', () => { - it('standalone', () => { const accountLinkTransaction = AccountLinkTransaction.create( Deadline.create(), harvestingAccount.publicKey, LinkAction.Link, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = accountLinkTransaction.signWith(account, generationHash); @@ -623,22 +634,23 @@ describe('TransactionHttp', () => { expect(transaction.linkAction, 'LinkAction').not.to.be.undefined; return signedTransaction; }); - }); }); describe('AccountLinkTransaction', () => { - it('aggregate', () => { const accountLinkTransaction = AccountLinkTransaction.create( Deadline.create(), harvestingAccount.publicKey, LinkAction.Unlink, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [accountLinkTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -646,14 +658,14 @@ describe('TransactionHttp', () => { }); describe('AddressAliasTransaction', () => { - it('standalone', () => { const addressAliasTransaction = AddressAliasTransaction.create( Deadline.create(), AliasAction.Link, namespaceId, account.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressAliasTransaction.signWith(account, generationHash); @@ -661,20 +673,19 @@ describe('TransactionHttp', () => { expect(transaction.namespaceId, 'NamespaceId').not.to.be.undefined; expect(transaction.aliasAction, 'AliasAction').not.to.be.undefined; expect(transaction.address, 'Address').not.to.be.undefined; - }); }); }); describe('Transfer Transaction using address alias', () => { - it('Announce TransferTransaction', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), namespaceId, - [NetworkCurrencyLocal.createAbsolute(1)], + [helper.createNetworkCurrency(1, false)], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = transferTransaction.signWith(account, generationHash); @@ -683,19 +694,21 @@ describe('TransactionHttp', () => { }); describe('AddressAliasTransaction', () => { - it('aggregate', () => { const addressAliasTransaction = AddressAliasTransaction.create( Deadline.create(), AliasAction.Unlink, namespaceId, account.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [addressAliasTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -703,14 +716,14 @@ describe('TransactionHttp', () => { }); describe('MosaicSupplyChangeTransaction', () => { - it('standalone', () => { const mosaicSupplyChangeTransaction = MosaicSupplyChangeTransaction.create( Deadline.create(), mosaicId, MosaicSupplyChangeAction.Increase, UInt64.fromUint(10), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicSupplyChangeTransaction.signWith(account, generationHash); return helper.announce(signedTransaction).then((transaction: MosaicSupplyChangeTransaction) => { @@ -718,38 +731,39 @@ describe('TransactionHttp', () => { expect(transaction.action, 'Action').not.to.be.undefined; expect(transaction.mosaicId, 'MosaicId').not.to.be.undefined; }); - }); }); describe('MosaicSupplyChangeTransaction', () => { - it('aggregate', () => { const mosaicSupplyChangeTransaction = MosaicSupplyChangeTransaction.create( Deadline.create(), mosaicId, MosaicSupplyChangeAction.Increase, UInt64.fromUint(10), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicSupplyChangeTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); }); - }); describe('MosaicAliasTransaction', () => { - it('standalone', () => { const mosaicAliasTransaction = MosaicAliasTransaction.create( Deadline.create(), AliasAction.Link, namespaceId, mosaicId, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicAliasTransaction.signWith(account, generationHash); @@ -762,39 +776,38 @@ describe('TransactionHttp', () => { }); describe('HashLockTransaction - MosaicAlias', () => { - it('standalone', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - networkType, - [], helper.maxFee, - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], networkType, [], helper.maxFee); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const hashLockTransaction = HashLockTransaction.create(Deadline.create(), - new Mosaic(new NamespaceId('cat.currency'), UInt64.fromUint(10 * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY))), + const hashLockTransaction = HashLockTransaction.create( + Deadline.create(), + new Mosaic(new NamespaceId('cat.currency'), UInt64.fromUint(10 * Math.pow(10, helper.networkCurrencyDivisibility))), UInt64.fromUint(10000), signedTransaction, - networkType, helper.maxFee); + networkType, + helper.maxFee, + ); const hashLockSignedTransaction = hashLockTransaction.signWith(account, generationHash); return helper.announce(hashLockSignedTransaction); }); }); describe('MosaicAliasTransaction', () => { - it('aggregate', () => { const mosaicAliasTransaction = MosaicAliasTransaction.create( Deadline.create(), AliasAction.Unlink, namespaceId, mosaicId, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicAliasTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -802,64 +815,60 @@ describe('TransactionHttp', () => { }); describe('LockFundsTransaction', () => { - it('standalone', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - networkType, - [], helper.maxFee, - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], networkType, [], helper.maxFee); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockFundsTransaction = LockFundsTransaction.create(Deadline.create(), - new Mosaic(NetworkCurrencyLocalId, UInt64.fromUint(10 * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY))), + const lockFundsTransaction = LockFundsTransaction.create( + Deadline.create(), + new Mosaic(NetworkCurrencyLocalId, UInt64.fromUint(10 * Math.pow(10, helper.networkCurrencyDivisibility))), UInt64.fromUint(10000), signedTransaction, - networkType, helper.maxFee); + networkType, + helper.maxFee, + ); return helper.announce(lockFundsTransaction.signWith(account, generationHash)); }); }); describe('LockFundsTransaction', () => { - it('aggregate', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - networkType, - [], helper.maxFee, - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], networkType, [], helper.maxFee); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockFundsTransaction = LockFundsTransaction.create(Deadline.create(), - new Mosaic(NetworkCurrencyLocalId, UInt64.fromUint(10 * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY))), + const lockFundsTransaction = LockFundsTransaction.create( + Deadline.create(), + new Mosaic(NetworkCurrencyLocalId, UInt64.fromUint(10 * Math.pow(10, helper.networkCurrencyDivisibility))), UInt64.fromUint(10), signedTransaction, - networkType, helper.maxFee); - const aggregateLockFundsTransaction = AggregateTransaction.createComplete(Deadline.create(), + networkType, + helper.maxFee, + ); + const aggregateLockFundsTransaction = AggregateTransaction.createComplete( + Deadline.create(), [lockFundsTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); return helper.announce(aggregateLockFundsTransaction.signWith(account, generationHash)); }); }); describe('Aggregate Complete Transaction', () => { - it('should announce aggregated complete transaction', () => { const tx = TransferTransaction.create( Deadline.create(), account2.address, [], PlainMessage.create('Hi'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const aggTx = AggregateTransaction.createComplete( Deadline.create(), - [ - tx.toAggregate(account.publicAccount), - ], + [tx.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = account.sign(aggTx, generationHash); return helper.announce(signedTransaction); @@ -867,168 +876,144 @@ describe('TransactionHttp', () => { }); describe('SecretLockTransaction', () => { - it('standalone', () => { const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Crypto.randomBytes(20)).hex(), account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = secretLockTransaction.signWith(account, generationHash); return helper.announce(signedTransaction).then((transaction: SecretLockTransaction) => { expect(transaction.mosaic, 'Mosaic').not.to.be.undefined; expect(transaction.duration, 'Duration').not.to.be.undefined; - expect(transaction.hashType, 'HashType').not.to.be.undefined; + expect(transaction.hashAlgorithm, 'HashAlgorithm').not.to.be.undefined; expect(transaction.secret, 'Secret').not.to.be.undefined; expect(transaction.recipientAddress, 'RecipientAddress').not.to.be.undefined; }); }); }); describe('HashType: Op_Sha3_256', () => { - it('aggregate', () => { const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Crypto.randomBytes(20)).hex(), account2.address, - networkType, helper.maxFee, - ); - const aggregateSecretLockTransaction = AggregateTransaction.createComplete(Deadline.create(), - [secretLockTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee); - return helper.announce(aggregateSecretLockTransaction.signWith(account, generationHash)); - }); - }); - describe('HashType: Keccak_256', () => { - - it('standalone', () => { - const secretLockTransaction = SecretLockTransaction.create( - Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), - UInt64.fromUint(100), - HashType.Op_Keccak_256, - sha3_256.create().update(Crypto.randomBytes(20)).hex(), - account2.address, - networkType, helper.maxFee, + helper.maxFee, ); - return helper.announce(secretLockTransaction.signWith(account, generationHash)); - }); - }); - describe('HashType: Keccak_256', () => { - - it('aggregate', () => { - const secretLockTransaction = SecretLockTransaction.create( + const aggregateSecretLockTransaction = AggregateTransaction.createComplete( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), - UInt64.fromUint(100), - HashType.Op_Keccak_256, - sha3_256.create().update(Crypto.randomBytes(20)).hex(), - account2.address, - networkType, helper.maxFee, - ); - const aggregateSecretLockTransaction = AggregateTransaction.createComplete(Deadline.create(), [secretLockTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); return helper.announce(aggregateSecretLockTransaction.signWith(account, generationHash)); }); }); - describe('HashType: Op_Hash_160', () => { + describe('HashType: Op_Hash_160', () => { it('standalone', () => { const secretSeed = String.fromCharCode.apply(null, Crypto.randomBytes(20)); const secret = CryptoJS.RIPEMD160(CryptoJS.SHA256(secretSeed).toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex); const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, secret, account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); return helper.announce(secretLockTransaction.signWith(account, generationHash)); }); }); describe('HashType: Op_Hash_160', () => { - it('aggregate', () => { const secretSeed = String.fromCharCode.apply(null, Crypto.randomBytes(20)); const secret = CryptoJS.RIPEMD160(CryptoJS.SHA256(secretSeed).toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex); const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, secret, account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateSecretLockTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateSecretLockTransaction = AggregateTransaction.createComplete( + Deadline.create(), [secretLockTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); return helper.announce(aggregateSecretLockTransaction.signWith(account, generationHash)); }); }); describe('HashType: Op_Hash_256', () => { - it('standalone', () => { const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, sha3_256.create().update(Crypto.randomBytes(20)).hex(), account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); return helper.announce(secretLockTransaction.signWith(account, generationHash)); }); }); describe('HashType: Op_Hash_256', () => { - it('aggregate', () => { const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, sha3_256.create().update(Crypto.randomBytes(20)).hex(), account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateSecretLockTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateSecretLockTransaction = AggregateTransaction.createComplete( + Deadline.create(), [secretLockTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); return helper.announce(aggregateSecretLockTransaction.signWith(account, generationHash)); }); }); describe('SecretProofTransaction - HashType: Op_Sha3_256', () => { - it('standalone', () => { const secretSeed = Crypto.randomBytes(20); - const secret = sha3_256.create().update(secretSeed).hex(); + const secret = LockHashUtils.Op_Sha3_256(secretSeed); const proof = convert.uint8ToHex(secretSeed); const secretLockTransaction = SecretLockTransaction.create( Deadline.create(1, ChronoUnit.HOURS), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(11), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, secret, account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedSecretLockTx = secretLockTransaction.signWith(account, generationHash); @@ -1036,143 +1021,86 @@ describe('TransactionHttp', () => { return helper.announce(signedSecretLockTx).then(() => { const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, secret, account2.address, proof, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTx = secretProofTransaction.signWith(account2, generationHash); return helper.announce(signedTx).then((transaction: SecretProofTransaction) => { expect(transaction.secret, 'Secret').not.to.be.undefined; expect(transaction.recipientAddress, 'RecipientAddress').not.to.be.undefined; - expect(transaction.hashType, 'HashType').not.to.be.undefined; + expect(transaction.hashAlgorithm, 'HashAlgorithm').not.to.be.undefined; expect(transaction.proof, 'Proof').not.to.be.undefined; }); }); - }); }); describe('SecretProofTransaction - HashType: Op_Sha3_256', () => { - it('aggregate', () => { const secretSeed = Crypto.randomBytes(20); const secret = sha3_256.create().update(secretSeed).hex(); const proof = convert.uint8ToHex(secretSeed); const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, secret, account2.address, - networkType, helper.maxFee, - ); - - return helper.announce(secretLockTransaction.signWith(account, generationHash)).then(() => { - const secretProofTransaction = SecretProofTransaction.create( - Deadline.create(), - HashType.Op_Sha3_256, - secret, - account2.address, - proof, - networkType, helper.maxFee, - ); - const aggregateSecretProofTransaction = AggregateTransaction.createComplete(Deadline.create(), - [secretProofTransaction.toAggregate(account2.publicAccount)], - networkType, [], helper.maxFee); - return helper.announce(aggregateSecretProofTransaction.signWith(account2, generationHash)); - }); - - }); - }); - describe('SecretProofTransaction - HashType: Op_Keccak_256', () => { - - it('standalone', () => { - const secretSeed = Crypto.randomBytes(20); - const secret = keccak_256.create().update(secretSeed).hex(); - const proof = convert.uint8ToHex(secretSeed); - const secretLockTransaction = SecretLockTransaction.create( - Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), - UInt64.fromUint(100), - HashType.Op_Keccak_256, - secret, - account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); return helper.announce(secretLockTransaction.signWith(account, generationHash)).then(() => { const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Keccak_256, + LockHashAlgorithm.Op_Sha3_256, secret, account2.address, proof, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - return helper.announce(secretProofTransaction.signWith(account2, generationHash)); - }); - }); - }); - describe('SecretProofTransaction - HashType: Op_Keccak_256', () => { - - it('aggregate', () => { - const secretSeed = Crypto.randomBytes(20); - const secret = keccak_256.create().update(secretSeed).hex(); - const proof = convert.uint8ToHex(secretSeed); - const secretLockTransaction = SecretLockTransaction.create( - Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), - UInt64.fromUint(100), - HashType.Op_Keccak_256, - secret, - account2.address, - networkType, helper.maxFee, - ); - return helper.announce(secretLockTransaction.signWith(account, generationHash)).then(() => { - const secretProofTransaction = SecretProofTransaction.create( + const aggregateSecretProofTransaction = AggregateTransaction.createComplete( Deadline.create(), - HashType.Op_Keccak_256, - secret, - account2.address, - proof, - networkType, helper.maxFee, - ); - const aggregateSecretProofTransaction = AggregateTransaction.createComplete(Deadline.create(), [secretProofTransaction.toAggregate(account2.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); return helper.announce(aggregateSecretProofTransaction.signWith(account2, generationHash)); }); }); }); describe('SecretProofTransaction - HashType: Op_Hash_160', () => { - it('standalone', () => { const randomBytes = secureRandom.randomBuffer(32); const secretSeed = randomBytes.toString('hex'); - const hash = sha256(Buffer.from(secretSeed, 'hex')); - const secret = new ripemd160().update(Buffer.from(hash, 'hex')).digest('hex'); + const secret = LockHashUtils.Op_Hash_160(randomBytes); const proof = secretSeed; const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, secret, account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); return helper.announce(secretLockTransaction.signWith(account, generationHash)).then(() => { const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, secret, account2.address, proof, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTx = secretProofTransaction.signWith(account2, generationHash); return helper.announce(signedTx); @@ -1180,7 +1108,6 @@ describe('TransactionHttp', () => { }); }); describe('SecretProofTransaction - HashType: Op_Hash_160', () => { - it('aggregate', () => { const randomBytes = secureRandom.randomBuffer(32); const secretSeed = randomBytes.toString('hex'); @@ -1189,63 +1116,70 @@ describe('TransactionHttp', () => { const proof = secretSeed; const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, secret, account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, secret, account2.address, proof, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateSecretProofTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateSecretProofTransaction = AggregateTransaction.createComplete( + Deadline.create(), [secretProofTransaction.toAggregate(account2.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); - return helper.announce(secretLockTransaction.signWith(account, generationHash)).then( - () => helper.announce(aggregateSecretProofTransaction.signWith(account2, generationHash))); + return helper + .announce(secretLockTransaction.signWith(account, generationHash)) + .then(() => helper.announce(aggregateSecretProofTransaction.signWith(account2, generationHash))); }); }); describe('SecretProofTransaction - HashType: Op_Hash_256', () => { - it('standalone', () => { const randomBytes = secureRandom.randomBuffer(32); const secretSeed = randomBytes.toString('hex'); - const hash = sha256(Buffer.from(secretSeed, 'hex')); - const secret = sha256(Buffer.from(hash, 'hex')); + // const secret = sha256(Buffer.from(hash, 'hex')); + const secret = LockHashUtils.Op_Hash_256(randomBytes); const proof = secretSeed; const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(1, false), UInt64.fromUint(100), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, secret, account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, secret, account2.address, proof, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - return helper.announce(secretLockTransaction.signWith(account, generationHash)).then(() => - helper.announce(secretProofTransaction.signWith(account2, generationHash))); + return helper + .announce(secretLockTransaction.signWith(account, generationHash)) + .then(() => helper.announce(secretProofTransaction.signWith(account2, generationHash))); }); }); describe('SecretProofTransaction - HashType: Op_Hash_256', () => { - it('aggregate', () => { const randomBytes = secureRandom.randomBuffer(32); const secretSeed = randomBytes.toString('hex'); @@ -1254,57 +1188,71 @@ describe('TransactionHttp', () => { const proof = secretSeed; const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), + helper.createNetworkCurrency(10, false), UInt64.fromUint(100), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, secret, account2.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, secret, account2.address, proof, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateSecretProofTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateSecretProofTransaction = AggregateTransaction.createComplete( + Deadline.create(), [secretProofTransaction.toAggregate(account2.publicAccount)], networkType, - [], helper.maxFee); - return helper.announce(secretLockTransaction.signWith(account, generationHash)).then(() => - helper.announce(aggregateSecretProofTransaction.signWith(account2, generationHash))); + [], + helper.maxFee, + ); + return helper + .announce(secretLockTransaction.signWith(account, generationHash)) + .then(() => helper.announce(aggregateSecretProofTransaction.signWith(account2, generationHash))); }); }); describe('SignTransactionGivenSignatures', () => { - it('Announce cosign signatures given', () => { - /** * @see https://github.com/nemtech/symbol-sdk-typescript-javascript/issues/112 */ - // AliceAccount: account - // BobAccount: account + // AliceAccount: account + // BobAccount: account - const sendAmount = NetworkCurrencyLocal.createRelative(1000); - const backAmount = NetworkCurrencyLocal.createRelative(1); + const sendAmount = helper.createNetworkCurrency(1000); + const backAmount = helper.createNetworkCurrency(1); - const aliceTransferTransaction = TransferTransaction.create(Deadline.create(), account2.address, [sendAmount], - PlainMessage.create('payout'), networkType, helper.maxFee); - const bobTransferTransaction = TransferTransaction.create(Deadline.create(), account.address, [backAmount], - PlainMessage.create('payout'), networkType, helper.maxFee); + const aliceTransferTransaction = TransferTransaction.create( + Deadline.create(), + account2.address, + [sendAmount], + PlainMessage.create('payout'), + networkType, + helper.maxFee, + ); + const bobTransferTransaction = TransferTransaction.create( + Deadline.create(), + account.address, + [backAmount], + PlainMessage.create('payout'), + networkType, + helper.maxFee, + ); // 01. Alice creates the aggregated tx and sign it. Then payload send to Bob const aggregateTransaction = AggregateTransaction.createComplete( Deadline.create(), - [ - aliceTransferTransaction.toAggregate(account.publicAccount), - bobTransferTransaction.toAggregate(account2.publicAccount), - ], + [aliceTransferTransaction.toAggregate(account.publicAccount), bobTransferTransaction.toAggregate(account2.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const aliceSignedTransaction = aggregateTransaction.signWith(account, generationHash); @@ -1384,9 +1332,10 @@ describe('TransactionHttp', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, - [NetworkCurrencyLocal.createAbsolute(1)], + [helper.createNetworkCurrency(1, false)], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = transferTransaction.signWith(account, generationHash); const transactionAnnounceResponse = await transactionRepository.announce(signedTransaction).toPromise(); @@ -1399,19 +1348,21 @@ describe('TransactionHttp', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, - [NetworkCurrencyLocal.createRelative(1)], + [helper.createNetworkCurrency(1)], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const aggregateTransaction = AggregateTransaction.createBonded( Deadline.create(2, ChronoUnit.MINUTES), [transferTransaction.toAggregate(multisigAccount.publicAccount)], networkType, - [], helper.maxFee); + [], + helper.maxFee, + ); const signedTransaction = aggregateTransaction.signWith(cosignAccount1, generationHash); const transactionAnnounceResponse = await transactionRepository.announceAggregateBonded(signedTransaction).toPromise(); - expect(transactionAnnounceResponse.message) - .to.be.equal('packet 500 was pushed to the network via /transaction/partial'); + expect(transactionAnnounceResponse.message).to.be.equal('packet 500 was pushed to the network via /transaction/partial'); }); }); diff --git a/e2e/infrastructure/UnresolvedMapping.spec.ts b/e2e/infrastructure/UnresolvedMapping.spec.ts index 88367eb169..59dd881734 100644 --- a/e2e/infrastructure/UnresolvedMapping.spec.ts +++ b/e2e/infrastructure/UnresolvedMapping.spec.ts @@ -15,10 +15,7 @@ */ import { expect } from 'chai'; import { Convert } from '../../src/core/format'; -import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; -import { TransactionHttp } from '../../src/infrastructure/TransactionHttp'; import { Account } from '../../src/model/account/Account'; -import { Address } from '../../src/model/account/Address'; import { PlainMessage } from '../../src/model/message/PlainMessage'; import { MosaicFlags } from '../../src/model/mosaic/MosaicFlags'; import { MosaicId } from '../../src/model/mosaic/MosaicId'; @@ -46,11 +43,9 @@ describe('TransactionHttp', () => { const helper = new IntegrationTestHelper(); let account: Account; let account2: Account; - let namespaceRepository: NamespaceRepository; let generationHash: string; let networkType: NetworkType; let mosaicId: MosaicId; - let NetworkCurrencyLocalId: MosaicId; let namespaceIdAddress: NamespaceId; let namespaceIdMosaic: NamespaceId; @@ -60,7 +55,6 @@ describe('TransactionHttp', () => { account2 = helper.account2; generationHash = helper.generationHash; networkType = helper.networkType; - namespaceRepository = helper.repositoryFactory.createNamespaceRepository(); }); }); @@ -77,15 +71,8 @@ describe('TransactionHttp', () => { * Setup test data * ========================= */ - describe('Get network currency mosaic id', () => { - it('get mosaicId', async () => { - NetworkCurrencyLocalId = - (await namespaceRepository.getLinkedMosaicId(new NamespaceId('cat.currency')).toPromise()) as MosaicId; - }); - }); describe('MosaicDefinitionTransaction', () => { - it('standalone', () => { const nonce = MosaicNonce.createRandom(); mosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); @@ -96,7 +83,8 @@ describe('TransactionHttp', () => { MosaicFlags.create(true, true, true), 3, UInt64.fromUint(1000), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); @@ -105,14 +93,14 @@ describe('TransactionHttp', () => { }); describe('NamespaceRegistrationTransaction', () => { - it('standalone', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( Deadline.create(), namespaceName, UInt64.fromUint(50), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); namespaceIdMosaic = new NamespaceId(namespaceName); const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); @@ -122,14 +110,14 @@ describe('TransactionHttp', () => { }); describe('NamespaceRegistrationTransaction', () => { - it('standalone', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( Deadline.create(), namespaceName, UInt64.fromUint(50), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); namespaceIdAddress = new NamespaceId(namespaceName); const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); @@ -139,14 +127,14 @@ describe('TransactionHttp', () => { }); describe('AddressAliasTransaction', () => { - it('standalone', () => { const addressAliasTransaction = AddressAliasTransaction.create( Deadline.create(), AliasAction.Link, namespaceIdAddress, account.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressAliasTransaction.signWith(account, generationHash); @@ -155,14 +143,14 @@ describe('TransactionHttp', () => { }); describe('MosaicAliasTransaction', () => { - it('standalone', () => { const mosaicAliasTransaction = MosaicAliasTransaction.create( Deadline.create(), AliasAction.Link, namespaceIdMosaic, mosaicId, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicAliasTransaction.signWith(account, generationHash); @@ -177,7 +165,6 @@ describe('TransactionHttp', () => { */ describe('MosaicMetadataTransaction', () => { - it('aggregate', () => { const mosaicMetadataTransaction = MosaicMetadataTransaction.create( Deadline.create(), @@ -186,12 +173,16 @@ describe('TransactionHttp', () => { namespaceIdMosaic, 10, Convert.uint8ToUtf8(new Uint8Array(10)), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicMetadataTransaction.toAggregate(account.publicAccount)], - networkType, [], helper.maxFee, + networkType, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); @@ -199,13 +190,11 @@ describe('TransactionHttp', () => { transaction.innerTransactions.forEach((innerTx) => { expect((innerTx as MosaicMetadataTransaction).targetMosaicId instanceof NamespaceId).to.be.true; }); - }); }); }); describe('MosaicGlobalRestrictionTransaction', () => { - it('standalone', () => { const mosaicGlobalRestrictionTransaction = MosaicGlobalRestrictionTransaction.create( Deadline.create(), @@ -215,19 +204,19 @@ describe('TransactionHttp', () => { MosaicRestrictionType.NONE, UInt64.fromUint(0), MosaicRestrictionType.GE, - networkType, undefined, helper.maxFee, + networkType, + undefined, + helper.maxFee, ); const signedTransaction = mosaicGlobalRestrictionTransaction.signWith(account, generationHash); return helper.announce(signedTransaction).then((transaction: Transaction) => { expect((transaction as MosaicGlobalRestrictionTransaction).mosaicId instanceof NamespaceId).to.be.true; - }); }); }); describe('MosaicAddressRestrictionTransaction', () => { - it('aggregate', () => { const mosaicAddressRestrictionTransaction = MosaicAddressRestrictionTransaction.create( Deadline.create(), @@ -235,12 +224,15 @@ describe('TransactionHttp', () => { UInt64.fromUint(60641), namespaceIdAddress, UInt64.fromUint(2), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicAddressRestrictionTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); @@ -254,14 +246,14 @@ describe('TransactionHttp', () => { }); describe('TransferTransaction', () => { - it('standalone', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, [NetworkCurrencyLocal.createAbsolute(1)], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = transferTransaction.signWith(account, generationHash); @@ -278,14 +270,14 @@ describe('TransactionHttp', () => { */ describe('AddressAliasTransaction', () => { - it('standalone', () => { const addressAliasTransaction = AddressAliasTransaction.create( Deadline.create(), AliasAction.Unlink, namespaceIdAddress, account.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressAliasTransaction.signWith(account, generationHash); @@ -293,20 +285,19 @@ describe('TransactionHttp', () => { expect(transaction.namespaceId, 'NamespaceId').not.to.be.undefined; expect(transaction.aliasAction, 'AliasAction').not.to.be.undefined; expect(transaction.address, 'Address').not.to.be.undefined; - }); }); }); describe('MosaicAliasTransaction', () => { - it('standalone', () => { const mosaicAliasTransaction = MosaicAliasTransaction.create( Deadline.create(), AliasAction.Unlink, namespaceIdMosaic, mosaicId, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicAliasTransaction.signWith(account, generationHash); diff --git a/e2e/service/AccountService.spec.ts b/e2e/service/AccountService.spec.ts new file mode 100644 index 0000000000..d1ba727ca7 --- /dev/null +++ b/e2e/service/AccountService.spec.ts @@ -0,0 +1,94 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { expect } from 'chai'; +import { Account } from '../../src/model/account/Account'; +import { NetworkType } from '../../src/model/network/NetworkType'; +import { Deadline } from '../../src/model/transaction/Deadline'; +import { UInt64 } from '../../src/model/UInt64'; +import { IntegrationTestHelper } from '../infrastructure/IntegrationTestHelper'; +import { AccountService } from '../../src/service/AccountService'; +import { NamespaceRegistrationTransaction } from '../../src/model/transaction/NamespaceRegistrationTransaction'; +import { NamespaceId } from '../../src/model/namespace/NamespaceId'; + +describe('AccountService', () => { + const helper = new IntegrationTestHelper(); + let generationHash: string; + let account: Account; + let networkType: NetworkType; + let accountService: AccountService; + let namespaceId: NamespaceId; + const name = 'root-test-namespace-' + Math.floor(Math.random() * 10000); + + before(() => { + return helper.start().then(() => { + account = helper.account; + generationHash = helper.generationHash; + networkType = helper.networkType; + accountService = new AccountService(helper.repositoryFactory); + }); + }); + before(() => { + return helper.listener.open(); + }); + + after(() => { + helper.listener.close(); + }); + + /** + * ========================= + * Setup test data + * ========================= + */ + describe('Create a namespace', () => { + it('Announce NamespaceRegistrationTransaction', () => { + const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( + Deadline.create(), + name, + UInt64.fromUint(300000), + networkType, + helper.maxFee, + ); + namespaceId = new NamespaceId(name); + const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); + return helper.announce(signedTransaction); + }); + }); + + /** + * ========================= + * Test + * ========================= + */ + describe('call accountInfoWithResolvedMosaic', () => { + it('accountInfoWithResolvedMosaic', async () => { + const info = await accountService.accountInfoWithResolvedMosaic([account.address]).toPromise(); + expect(info).to.not.be.undefined; + expect(info[0].resolvedMosaics).to.not.be.undefined; + expect(info[0].resolvedMosaics?.length).to.be.greaterThan(0); + }); + }); + + describe('call accountNamespacesWithName', () => { + it('accountNamespacesWithName', async () => { + const info = await accountService.accountNamespacesWithName([account.address]).toPromise(); + expect(info).to.not.be.undefined; + expect(info.find((i) => i.id.equals(namespaceId))).to.not.be.undefined; + expect(info.find((i) => i.id.equals(namespaceId))?.namespaceName).to.be.equal(name); + }); + }); +}); diff --git a/e2e/service/BlockService.spec.ts b/e2e/service/BlockService.spec.ts index f7343864b7..d54a9cf1f3 100644 --- a/e2e/service/BlockService.spec.ts +++ b/e2e/service/BlockService.spec.ts @@ -32,7 +32,6 @@ describe('BlockService', () => { let generationHash: string; let account: Account; let account2: Account; - let account3: Account; let networkType: NetworkType; let transactionHash: string; let blockService: BlockService; @@ -43,7 +42,6 @@ describe('BlockService', () => { return helper.start().then(() => { account = helper.account; account2 = helper.account2; - account3 = helper.account3; generationHash = helper.generationHash; networkType = helper.networkType; transactionRepository = helper.repositoryFactory.createTransactionRepository(); diff --git a/e2e/service/MetadataTransactionService.spec.ts b/e2e/service/MetadataTransactionService.spec.ts index 25d5794c92..3fe8be134a 100644 --- a/e2e/service/MetadataTransactionService.spec.ts +++ b/e2e/service/MetadataTransactionService.spec.ts @@ -57,7 +57,6 @@ describe('MetadataTransactionService', () => { */ describe('MosaicDefinitionTransaction', () => { - it('standalone', () => { const nonce = MosaicNonce.createRandom(); mosaicId = MosaicId.createFromNonce(nonce, targetAccount.publicAccount); @@ -68,7 +67,8 @@ describe('MetadataTransactionService', () => { MosaicFlags.create(true, true, true), 3, UInt64.fromUint(1000), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicDefinitionTransaction.signWith(targetAccount, generationHash); return helper.announce(signedTransaction); @@ -76,14 +76,14 @@ describe('MetadataTransactionService', () => { }); describe('Setup test NamespaceId', () => { - it('Announce NamespaceRegistrationTransaction', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( Deadline.create(), namespaceName, UInt64.fromUint(9), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); namespaceId = new NamespaceId(namespaceName); const signedTransaction = registerNamespaceTransaction.signWith(targetAccount, generationHash); @@ -93,7 +93,6 @@ describe('MetadataTransactionService', () => { }); describe('MosaicMetadataTransaction', () => { - it('aggregate', () => { const mosaicMetadataTransaction = MosaicMetadataTransaction.create( Deadline.create(), @@ -106,7 +105,8 @@ describe('MetadataTransactionService', () => { helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicMetadataTransaction.toAggregate(targetAccount.publicAccount)], networkType, [], @@ -119,7 +119,6 @@ describe('MetadataTransactionService', () => { }); describe('NamespaceMetadataTransaction', () => { - it('aggregate', () => { const namespaceMetadataTransaction = NamespaceMetadataTransaction.create( Deadline.create(), @@ -131,7 +130,8 @@ describe('MetadataTransactionService', () => { networkType, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [namespaceMetadataTransaction.toAggregate(targetAccount.publicAccount)], networkType, [], @@ -148,19 +148,20 @@ describe('MetadataTransactionService', () => { * ========================= */ describe('Test new services', () => { - it('should create AccountMetadataTransaction - no current metadata', async () => { const metaDataService = new MetadataTransactionService(metadataRepository); - const transaction = await metaDataService.createMetadataTransaction( - deadline, - networkType, - MetadataType.Account, - targetAccount.publicAccount, - key, - newValue, - targetAccount.publicAccount, - ).toPromise(); + const transaction = await metaDataService + .createMetadataTransaction( + deadline, + networkType, + MetadataType.Account, + targetAccount.publicAccount, + key, + newValue, + targetAccount.publicAccount, + ) + .toPromise(); expect(transaction.type).to.be.equal(TransactionType.ACCOUNT_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); @@ -171,21 +172,24 @@ describe('MetadataTransactionService', () => { it('should create MosaicMetadataTransaction', async () => { const metaDataService = new MetadataTransactionService(metadataRepository); const updateValue = newValue + 'delta'; - const transaction = await metaDataService.createMetadataTransaction( - deadline, - networkType, - MetadataType.Mosaic, - targetAccount.publicAccount, - key, - updateValue, - targetAccount.publicAccount, - mosaicId, - ).toPromise() as MosaicMetadataTransaction; + const transaction = (await metaDataService + .createMetadataTransaction( + deadline, + networkType, + MetadataType.Mosaic, + targetAccount.publicAccount, + key, + updateValue, + targetAccount.publicAccount, + mosaicId, + ) + .toPromise()) as MosaicMetadataTransaction; expect(transaction.type).to.be.equal(TransactionType.MOSAIC_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); expect(transaction.valueSizeDelta).to.be.equal(5); expect(transaction.value).to.be.equals( - Convert.decodeHex(Convert.xor(Convert.utf8ToUint8(newValue), Convert.utf8ToUint8(updateValue)))); + Convert.decodeHex(Convert.xor(Convert.utf8ToUint8(newValue), Convert.utf8ToUint8(updateValue))), + ); expect(transaction.targetPublicKey).to.be.equal(targetAccount.publicKey); expect(transaction.targetMosaicId.toHex()).to.be.equal(mosaicId.toHex()); }); @@ -194,44 +198,49 @@ describe('MetadataTransactionService', () => { const metaDataService = new MetadataTransactionService(metadataRepository); const updateValue = newValue + 'delta'; - const transaction = await metaDataService.createMetadataTransaction( - deadline, - networkType, - MetadataType.Namespace, - targetAccount.publicAccount, - key, - updateValue, - targetAccount.publicAccount, - namespaceId, - ).toPromise() as NamespaceMetadataTransaction; + const transaction = (await metaDataService + .createMetadataTransaction( + deadline, + networkType, + MetadataType.Namespace, + targetAccount.publicAccount, + key, + updateValue, + targetAccount.publicAccount, + namespaceId, + ) + .toPromise()) as NamespaceMetadataTransaction; expect(transaction.type).to.be.equal(TransactionType.NAMESPACE_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); expect(transaction.valueSizeDelta).to.be.equal(5); - expect(transaction.value).to.be.equals( Convert.decodeHex( - Convert.xor(Convert.utf8ToUint8(newValue), Convert.utf8ToUint8(updateValue)))); + expect(transaction.value).to.be.equals( + Convert.decodeHex(Convert.xor(Convert.utf8ToUint8(newValue), Convert.utf8ToUint8(updateValue))), + ); expect(transaction.targetPublicKey).to.be.equal(targetAccount.publicKey); expect(transaction.targetNamespaceId.toHex()).to.be.equal(namespaceId.toHex()); }); }); describe('Announce transaction through service', () => { - it('should create MosaicMetadataTransaction and announce', async () => { const metaDataService = new MetadataTransactionService(metadataRepository); - const transaction = await metaDataService.createMetadataTransaction( - deadline, - networkType, - MetadataType.Mosaic, - targetAccount.publicAccount, - key, - newValue + 'delta', - targetAccount.publicAccount, - mosaicId, - helper.maxFee, - ).toPromise(); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const transaction = await metaDataService + .createMetadataTransaction( + deadline, + networkType, + MetadataType.Mosaic, + targetAccount.publicAccount, + key, + newValue + 'delta', + targetAccount.publicAccount, + mosaicId, + helper.maxFee, + ) + .toPromise(); + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [transaction.toAggregate(targetAccount.publicAccount)], networkType, [], @@ -243,57 +252,63 @@ describe('MetadataTransactionService', () => { }); describe('Announce transaction through service with delta size increase', () => { - it('should create MosaicMetadataTransaction and announce', () => { const metaDataService = new MetadataTransactionService(metadataRepository); - return metaDataService.createMetadataTransaction( - deadline, - networkType, - MetadataType.Mosaic, - targetAccount.publicAccount, - key, - newValue + 'delta' + 'extra delta', - targetAccount.publicAccount, - mosaicId, - helper.maxFee, - ).toPromise().then((transaction: MosaicMetadataTransaction) => { - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), - [transaction.toAggregate(targetAccount.publicAccount)], + return metaDataService + .createMetadataTransaction( + deadline, networkType, - [], + MetadataType.Mosaic, + targetAccount.publicAccount, + key, + newValue + 'delta' + 'extra delta', + targetAccount.publicAccount, + mosaicId, helper.maxFee, - ); - const signedTransaction = aggregateTransaction.signWith(targetAccount, generationHash); - return helper.announce(signedTransaction); - }); + ) + .toPromise() + .then((transaction: MosaicMetadataTransaction) => { + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), + [transaction.toAggregate(targetAccount.publicAccount)], + networkType, + [], + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signWith(targetAccount, generationHash); + return helper.announce(signedTransaction); + }); }); }); describe('Announce transaction through service with delta size decrease', () => { - it('should create MosaicMetadataTransaction and announce', async () => { const metaDataService = new MetadataTransactionService(metadataRepository); - return metaDataService.createMetadataTransaction( - deadline, - networkType, - MetadataType.Mosaic, - targetAccount.publicAccount, - key, - newValue, - targetAccount.publicAccount, - mosaicId, - ).toPromise().then((transaction: MosaicMetadataTransaction) => { - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), - [transaction.toAggregate(targetAccount.publicAccount)], + return metaDataService + .createMetadataTransaction( + deadline, networkType, - [], - helper.maxFee, - ); - const signedTransaction = aggregateTransaction.signWith(targetAccount, generationHash); - return helper.announce(signedTransaction); - }); + MetadataType.Mosaic, + targetAccount.publicAccount, + key, + newValue, + targetAccount.publicAccount, + mosaicId, + ) + .toPromise() + .then((transaction: MosaicMetadataTransaction) => { + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), + [transaction.toAggregate(targetAccount.publicAccount)], + networkType, + [], + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signWith(targetAccount, generationHash); + return helper.announce(signedTransaction); + }); }); }); }); diff --git a/e2e/service/MosaicRestrictionTransactionService.spec.ts b/e2e/service/MosaicRestrictionTransactionService.spec.ts index c05f8d6819..1ecfcf1080 100644 --- a/e2e/service/MosaicRestrictionTransactionService.spec.ts +++ b/e2e/service/MosaicRestrictionTransactionService.spec.ts @@ -61,7 +61,6 @@ describe('MosaicRestrictionTransactionService', () => { */ describe('MosaicDefinitionTransaction', () => { - it('standalone', () => { const nonce = MosaicNonce.createRandom(); mosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); @@ -72,7 +71,8 @@ describe('MosaicRestrictionTransactionService', () => { MosaicFlags.create(true, true, true), 3, UInt64.fromUint(1000), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -80,7 +80,6 @@ describe('MosaicRestrictionTransactionService', () => { }); describe('MosaicGlobalRestrictionTransaction - with referenceMosaicId', () => { - it('standalone', () => { const mosaicGlobalRestrictionTransaction = MosaicGlobalRestrictionTransaction.create( Deadline.create(), @@ -100,7 +99,6 @@ describe('MosaicRestrictionTransactionService', () => { }); describe('MosaicAddressRestrictionTransaction', () => { - it('aggregate', () => { const mosaicAddressRestrictionTransaction = MosaicAddressRestrictionTransaction.create( Deadline.create(), @@ -112,10 +110,12 @@ describe('MosaicRestrictionTransactionService', () => { undefined, helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [mosaicAddressRestrictionTransaction.toAggregate(account.publicAccount)], networkType, - [], helper.maxFee, + [], + helper.maxFee, ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); return helper.announce(signedTransaction); @@ -123,14 +123,14 @@ describe('MosaicRestrictionTransactionService', () => { }); describe('NamespaceRegistrationTransaction', () => { - it('standalone', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( Deadline.create(), namespaceName, UInt64.fromUint(50), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); namespaceIdMosaic = new NamespaceId(namespaceName); const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); @@ -140,14 +140,14 @@ describe('MosaicRestrictionTransactionService', () => { }); describe('NamespaceRegistrationTransaction', () => { - it('standalone', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( Deadline.create(), namespaceName, UInt64.fromUint(50), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); namespaceIdAddress = new NamespaceId(namespaceName); const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); @@ -157,14 +157,14 @@ describe('MosaicRestrictionTransactionService', () => { }); describe('AddressAliasTransaction', () => { - it('standalone', () => { const addressAliasTransaction = AddressAliasTransaction.create( Deadline.create(), AliasAction.Link, namespaceIdAddress, account.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressAliasTransaction.signWith(account, generationHash); @@ -173,14 +173,14 @@ describe('MosaicRestrictionTransactionService', () => { }); describe('MosaicAliasTransaction', () => { - it('standalone', () => { const mosaicAliasTransaction = MosaicAliasTransaction.create( Deadline.create(), AliasAction.Link, namespaceIdMosaic, mosaicId, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicAliasTransaction.signWith(account, generationHash); @@ -197,63 +197,68 @@ describe('MosaicRestrictionTransactionService', () => { it('should create MosaicGlobalRestrictionTransaction', () => { const service = new MosaicRestrictionTransactionService(restrictionRepository, namespaceRepository); - return service.createMosaicGlobalRestrictionTransaction( - deadline, - networkType, - mosaicId, - key, - '1', - MosaicRestrictionType.GE, undefined, helper.maxFee, - ).toPromise().then((transaction: MosaicGlobalRestrictionTransaction) => { - expect(transaction.type).to.be.equal(TransactionType.MOSAIC_GLOBAL_RESTRICTION); - expect(transaction.previousRestrictionValue.toString()).to.be.equal('0'); - expect(transaction.previousRestrictionType).to.be.equal(MosaicRestrictionType.GE); - expect(transaction.newRestrictionValue.toString()).to.be.equal('1'); - expect(transaction.newRestrictionType).to.be.equal(MosaicRestrictionType.GE); - expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); - }); + return service + .createMosaicGlobalRestrictionTransaction( + deadline, + networkType, + mosaicId, + key, + '1', + MosaicRestrictionType.GE, + undefined, + helper.maxFee, + ) + .toPromise() + .then((transaction: MosaicGlobalRestrictionTransaction) => { + expect(transaction.type).to.be.equal(TransactionType.MOSAIC_GLOBAL_RESTRICTION); + expect(transaction.previousRestrictionValue.toString()).to.be.equal('0'); + expect(transaction.previousRestrictionType).to.be.equal(MosaicRestrictionType.GE); + expect(transaction.newRestrictionValue.toString()).to.be.equal('1'); + expect(transaction.newRestrictionType).to.be.equal(MosaicRestrictionType.GE); + expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); + }); }); }); describe('Test new services - MosaicGlobalRestriction', () => { it('should create MosaicGlobalRestrictionTransaction using alias', () => { const service = new MosaicRestrictionTransactionService(restrictionRepository, namespaceRepository); - return service.createMosaicGlobalRestrictionTransaction( - deadline, - networkType, - namespaceIdMosaic, - key, - '2', - MosaicRestrictionType.GE, undefined, helper.maxFee, - ).toPromise().then((transaction: MosaicGlobalRestrictionTransaction) => { - expect(transaction.type).to.be.equal(TransactionType.MOSAIC_GLOBAL_RESTRICTION); - expect(transaction.previousRestrictionValue.toString()).to.be.equal('1'); - expect(transaction.previousRestrictionType).to.be.equal(MosaicRestrictionType.GE); - expect(transaction.newRestrictionValue.toString()).to.be.equal('2'); - expect(transaction.newRestrictionType).to.be.equal(MosaicRestrictionType.GE); - expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); - }); + return service + .createMosaicGlobalRestrictionTransaction( + deadline, + networkType, + namespaceIdMosaic, + key, + '2', + MosaicRestrictionType.GE, + undefined, + helper.maxFee, + ) + .toPromise() + .then((transaction: MosaicGlobalRestrictionTransaction) => { + expect(transaction.type).to.be.equal(TransactionType.MOSAIC_GLOBAL_RESTRICTION); + expect(transaction.previousRestrictionValue.toString()).to.be.equal('1'); + expect(transaction.previousRestrictionType).to.be.equal(MosaicRestrictionType.GE); + expect(transaction.newRestrictionValue.toString()).to.be.equal('2'); + expect(transaction.newRestrictionType).to.be.equal(MosaicRestrictionType.GE); + expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); + }); }); }); describe('Test new services - MosaicAddressRestriction', () => { it('should create MosaicAddressRestrictionTransaction', () => { const service = new MosaicRestrictionTransactionService(restrictionRepository, namespaceRepository); - return service.createMosaicAddressRestrictionTransaction( - deadline, - networkType, - mosaicId, - key, - account.address, - '3', - helper.maxFee, - ).toPromise().then((transaction: MosaicAddressRestrictionTransaction) => { - expect(transaction.type).to.be.equal(TransactionType.MOSAIC_ADDRESS_RESTRICTION); - expect(transaction.previousRestrictionValue.toString()).to.be.equal('2'); - expect(transaction.newRestrictionValue.toString()).to.be.equal('3'); - expect(transaction.targetAddressToString()).to.be.equal(account.address.plain()); - expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); - }); + return service + .createMosaicAddressRestrictionTransaction(deadline, networkType, mosaicId, key, account.address, '3', helper.maxFee) + .toPromise() + .then((transaction: MosaicAddressRestrictionTransaction) => { + expect(transaction.type).to.be.equal(TransactionType.MOSAIC_ADDRESS_RESTRICTION); + expect(transaction.previousRestrictionValue.toString()).to.be.equal('2'); + expect(transaction.newRestrictionValue.toString()).to.be.equal('3'); + expect(transaction.targetAddressToString()).to.be.equal(account.address.plain()); + expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); + }); }); }); @@ -261,70 +266,65 @@ describe('MosaicRestrictionTransactionService', () => { it('should create MosaicAddressRestrictionTransaction with address alias', () => { const service = new MosaicRestrictionTransactionService(restrictionRepository, namespaceRepository); - return service.createMosaicAddressRestrictionTransaction( - deadline, - networkType, - mosaicId, - key, - namespaceIdAddress, - '4', - helper.maxFee, - ).toPromise().then((transaction: MosaicAddressRestrictionTransaction) => { - expect(transaction.type).to.be.equal(TransactionType.MOSAIC_ADDRESS_RESTRICTION); - expect(transaction.previousRestrictionValue.toString()).to.be.equal('3'); - expect(transaction.newRestrictionValue.toString()).to.be.equal('4'); - expect(transaction.targetAddressToString()).to.be.equal(account.address.plain()); - expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); - }); + return service + .createMosaicAddressRestrictionTransaction(deadline, networkType, mosaicId, key, namespaceIdAddress, '4', helper.maxFee) + .toPromise() + .then((transaction: MosaicAddressRestrictionTransaction) => { + expect(transaction.type).to.be.equal(TransactionType.MOSAIC_ADDRESS_RESTRICTION); + expect(transaction.previousRestrictionValue.toString()).to.be.equal('3'); + expect(transaction.newRestrictionValue.toString()).to.be.equal('4'); + expect(transaction.targetAddressToString()).to.be.equal(account.address.plain()); + expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); + }); }); }); describe('Announce MosaicGlobalRestriction through service', () => { - it('should create MosaicGlobalRestriction and announce', () => { const service = new MosaicRestrictionTransactionService(restrictionRepository, namespaceRepository); - return service.createMosaicGlobalRestrictionTransaction( - deadline, - networkType, - mosaicId, - key, - '1', - MosaicRestrictionType.GE, undefined, helper.maxFee, - ).toPromise().then((transaction: MosaicGlobalRestrictionTransaction) => { - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), - [transaction.toAggregate(account.publicAccount)], + return service + .createMosaicGlobalRestrictionTransaction( + deadline, networkType, - [], + mosaicId, + key, + '1', + MosaicRestrictionType.GE, + undefined, helper.maxFee, - ); - const signedTransaction = aggregateTransaction.signWith(account, generationHash); - return helper.announce(signedTransaction); - }); + ) + .toPromise() + .then((transaction: MosaicGlobalRestrictionTransaction) => { + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), + [transaction.toAggregate(account.publicAccount)], + networkType, + [], + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signWith(account, generationHash); + return helper.announce(signedTransaction); + }); }); }); describe('Announce MosaicAddressRestriction through service', () => { - it('should create MosaicAddressRestriction and announce', () => { const service = new MosaicRestrictionTransactionService(restrictionRepository, namespaceRepository); - return service.createMosaicAddressRestrictionTransaction( - deadline, - networkType, - mosaicId, - key, - account.address, - '3', - helper.maxFee, - ).toPromise().then((transaction: MosaicAddressRestrictionTransaction) => { - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), - [transaction.toAggregate(account.publicAccount)], - networkType, - [], - helper.maxFee, - ); - const signedTransaction = aggregateTransaction.signWith(account, generationHash); - return helper.announce(signedTransaction); - }); + return service + .createMosaicAddressRestrictionTransaction(deadline, networkType, mosaicId, key, account.address, '3', helper.maxFee) + .toPromise() + .then((transaction: MosaicAddressRestrictionTransaction) => { + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), + [transaction.toAggregate(account.publicAccount)], + networkType, + [], + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signWith(account, generationHash); + return helper.announce(signedTransaction); + }); }); }); }); diff --git a/e2e/service/MosaicService.spec.ts b/e2e/service/MosaicService.spec.ts index 981699a7b8..3193368f7d 100644 --- a/e2e/service/MosaicService.spec.ts +++ b/e2e/service/MosaicService.spec.ts @@ -17,7 +17,6 @@ import { AccountRepository } from '../../src/infrastructure/AccountRepository'; import { MosaicRepository } from '../../src/infrastructure/MosaicRepository'; import { Address } from '../../src/model/account/Address'; -import { NetworkType } from '../../src/model/network/NetworkType'; import { MosaicService } from '../../src/service/MosaicService'; import { IntegrationTestHelper } from '../infrastructure/IntegrationTestHelper'; @@ -25,25 +24,24 @@ describe('MosaicService', () => { let accountAddress: Address; let accountRepository: AccountRepository; let mosaicRepository: MosaicRepository; - let generationHash: string; const helper = new IntegrationTestHelper(); - let networkType: NetworkType; before(() => { return helper.start().then(() => { accountAddress = helper.account.address; - generationHash = helper.generationHash; - networkType = helper.networkType; accountRepository = helper.repositoryFactory.createAccountRepository(); mosaicRepository = helper.repositoryFactory.createMosaicRepository(); }); }); it('should return the mosaic list skipping the expired mosaics', () => { const mosaicService = new MosaicService(accountRepository, mosaicRepository); - return mosaicService.mosaicsAmountViewFromAddress(accountAddress).toPromise().then((amountViews) => { - return amountViews.map((v) => { - return {mosaicId: v.fullName(), amount: v.relativeAmount()}; + return mosaicService + .mosaicsAmountViewFromAddress(accountAddress) + .toPromise() + .then((amountViews) => { + return amountViews.map((v) => { + return { mosaicId: v.fullName(), amount: v.relativeAmount() }; + }); }); - }); }); }); diff --git a/e2e/service/TransactionService.spec.ts b/e2e/service/TransactionService.spec.ts index 11ef791cd9..bb3c1220c4 100644 --- a/e2e/service/TransactionService.spec.ts +++ b/e2e/service/TransactionService.spec.ts @@ -72,7 +72,9 @@ describe('TransactionService', () => { transactionHashesMultiple = []; transactionRepository = helper.repositoryFactory.createTransactionRepository(); transactionService = new TransactionService( - helper.repositoryFactory.createTransactionRepository(), helper.repositoryFactory.createReceiptRepository()); + helper.repositoryFactory.createTransactionRepository(), + helper.repositoryFactory.createReceiptRepository(), + ); }); }); before(() => { @@ -83,13 +85,81 @@ describe('TransactionService', () => { helper.listener.close(); }); + function buildAggregateTransaction(): AggregateTransaction { + const transferTransaction = TransferTransaction.create( + Deadline.create(), + addressAlias, + [NetworkCurrencyLocal.createAbsolute(1), new Mosaic(mosaicAlias, UInt64.fromUint(1))], + PlainMessage.create('test-message'), + networkType, + helper.maxFee, + ); + // Unlink MosaicAlias + const mosaicAliasTransactionUnlink = MosaicAliasTransaction.create( + Deadline.create(), + AliasAction.Unlink, + mosaicAlias, + mosaicId, + networkType, + helper.maxFee, + ); + + // Create a new Mosaic + const nonce = MosaicNonce.createRandom(); + newMosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); + const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( + Deadline.create(), + nonce, + newMosaicId, + MosaicFlags.create(true, true, false), + 3, + UInt64.fromUint(0), + networkType, + helper.maxFee, + ); + + // Link namespace with new MosaicId + const mosaicAliasTransactionRelink = MosaicAliasTransaction.create( + Deadline.create(), + AliasAction.Link, + mosaicAlias, + newMosaicId, + networkType, + helper.maxFee, + ); + + // Use new mosaicAlias in metadata + const mosaicMetadataTransaction = MosaicMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(5), + mosaicAlias, + 10, + Convert.uint8ToUtf8(new Uint8Array(10)), + networkType, + helper.maxFee, + ); + return AggregateTransaction.createComplete( + Deadline.create(), + [ + transferTransaction.toAggregate(account.publicAccount), + mosaicAliasTransactionUnlink.toAggregate(account.publicAccount), + mosaicDefinitionTransaction.toAggregate(account.publicAccount), + mosaicAliasTransactionRelink.toAggregate(account.publicAccount), + mosaicMetadataTransaction.toAggregate(account.publicAccount), + ], + networkType, + [], + helper.maxFee, + ); + } + /** * ========================= * Setup test data * ========================= */ describe('Create address alias NamespaceId', () => { - it('Announce NamespaceRegistrationTransaction', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( @@ -107,14 +177,14 @@ describe('TransactionService', () => { }); describe('Create mosaic alias NamespaceId', () => { - it('Announce NamespaceRegistrationTransaction', () => { const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000); const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( Deadline.create(), namespaceName, UInt64.fromUint(50), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); mosaicAlias = new NamespaceId(namespaceName); const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); @@ -124,14 +194,14 @@ describe('TransactionService', () => { }); describe('Setup test AddressAlias', () => { - it('Announce addressAliasTransaction', () => { const addressAliasTransaction = AddressAliasTransaction.create( Deadline.create(), AliasAction.Link, addressAlias, account.address, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = addressAliasTransaction.signWith(account, generationHash); transactionHashes.push(signedTransaction.hash); @@ -141,7 +211,6 @@ describe('TransactionService', () => { }); describe('Setup test MosaicId', () => { - it('Announce MosaicDefinitionTransaction', () => { const nonce = MosaicNonce.createRandom(); mosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); @@ -152,7 +221,8 @@ describe('TransactionService', () => { MosaicFlags.create(true, true, false), 3, UInt64.fromUint(50), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); transactionHashes.push(signedTransaction.hash); @@ -162,14 +232,14 @@ describe('TransactionService', () => { }); describe('MosaicSupplyChangeTransaction', () => { - it('standalone', () => { const mosaicSupplyChangeTransaction = MosaicSupplyChangeTransaction.create( Deadline.create(), mosaicId, MosaicSupplyChangeAction.Increase, UInt64.fromUint(200000), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicSupplyChangeTransaction.signWith(account, generationHash); transactionHashes.push(signedTransaction.hash); @@ -178,14 +248,14 @@ describe('TransactionService', () => { }); describe('Setup MosaicAlias', () => { - it('Announce MosaicAliasTransaction', () => { const mosaicAliasTransaction = MosaicAliasTransaction.create( Deadline.create(), AliasAction.Link, mosaicAlias, mosaicId, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = mosaicAliasTransaction.signWith(account, generationHash); transactionHashes.push(signedTransaction.hash); @@ -198,12 +268,10 @@ describe('TransactionService', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), addressAlias, - [ - NetworkCurrencyLocal.createAbsolute(1), - new Mosaic(mosaicAlias, UInt64.fromUint(1)), - ], + [NetworkCurrencyLocal.createAbsolute(1), new Mosaic(mosaicAlias, UInt64.fromUint(1))], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = transferTransaction.signWith(account, generationHash); @@ -220,7 +288,6 @@ describe('TransactionService', () => { */ describe('Create Aggreate TransferTransaction', () => { - it('aggregate', () => { const signedTransaction = buildAggregateTransaction().signWith(account, generationHash); transactionHashes.push(signedTransaction.hash); @@ -235,16 +302,14 @@ describe('TransactionService', () => { */ describe('Transfer mosaic to account 3', () => { - it('Announce TransferTransaction', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account3.address, - [ - new Mosaic(mosaicAlias, UInt64.fromUint(200)), - ], + [new Mosaic(mosaicAlias, UInt64.fromUint(200))], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = transferTransaction.signWith(account, generationHash); transactionHashes.push(signedTransaction.hash); @@ -253,18 +318,16 @@ describe('TransactionService', () => { }); describe('Create multiple transfers with alias', () => { - it('Announce TransferTransaction', (done) => { const transactions: SignedTransaction[] = []; // 1. Transfer A -> B const transaction1 = TransferTransaction.create( Deadline.create(), account2.address, - [ - new Mosaic(mosaicAlias, UInt64.fromUint(1)), - ], + [new Mosaic(mosaicAlias, UInt64.fromUint(1))], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); transactions.push(transaction1.signWith(account, generationHash)); @@ -272,11 +335,10 @@ describe('TransactionService', () => { const transaction2 = TransferTransaction.create( Deadline.create(), cosignAccount4.address, - [ - new Mosaic(mosaicAlias, UInt64.fromUint(1)), - ], + [new Mosaic(mosaicAlias, UInt64.fromUint(1))], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); transactions.push(transaction2.signWith(account3, generationHash)); @@ -312,106 +374,48 @@ describe('TransactionService', () => { describe('should return resolved transaction', () => { it('call transaction service', () => { - return transactionService.resolveAliases(transactionHashes).toPromise().then((transactions) => { - expect(transactions.length).to.be.equal(8); - transactions.map((tx) => { - if (tx instanceof TransferTransaction) { - expect((tx.recipientAddress as Address).plain()).to.be.equal(account.address.plain()); - expect(tx.mosaics.find((m) => m.id.toHex() === mosaicId.toHex())).not.to.equal(undefined); - } else if (tx instanceof AggregateTransaction) { - expect(tx.innerTransactions.length).to.be.equal(5); - // Assert Transfer - expect(((tx.innerTransactions[0] as TransferTransaction).recipientAddress as Address) - .plain()).to.be.equal(account.address.plain()); - expect((tx.innerTransactions[0] as TransferTransaction).mosaics - .find((m) => m.id.toHex() === mosaicId.toHex())).not.to.equal(undefined); - // Assert MosaicMeta - expect((tx.innerTransactions[4] as MosaicMetadataTransaction) - .targetMosaicId.toHex() === newMosaicId.toHex()).to.be.true; - } - return tx; + return transactionService + .resolveAliases(transactionHashes) + .toPromise() + .then((transactions) => { + expect(transactions.length).to.be.equal(8); + transactions.map((tx) => { + if (tx instanceof TransferTransaction) { + expect((tx.recipientAddress as Address).plain()).to.be.equal(account.address.plain()); + expect(tx.mosaics.find((m) => m.id.toHex() === mosaicId.toHex())).not.to.equal(undefined); + } else if (tx instanceof AggregateTransaction) { + expect(tx.innerTransactions.length).to.be.equal(5); + // Assert Transfer + expect(((tx.innerTransactions[0] as TransferTransaction).recipientAddress as Address).plain()).to.be.equal( + account.address.plain(), + ); + expect( + (tx.innerTransactions[0] as TransferTransaction).mosaics.find((m) => m.id.toHex() === mosaicId.toHex()), + ).not.to.equal(undefined); + // Assert MosaicMeta + expect((tx.innerTransactions[4] as MosaicMetadataTransaction).targetMosaicId.toHex() === newMosaicId.toHex()).to + .be.true; + } + return tx; + }); }); - }); }); }); describe('Test resolve alias with multiple transaction in single block', () => { it('call transaction service', () => { - return transactionService.resolveAliases(transactionHashesMultiple).toPromise().then((tx) => { - expect(tx.length).to.be.equal(3); - expect((tx[0] as TransferTransaction).mosaics[0].id.toHex()).to.be.equal(mosaicId.toHex()); - expect((tx[1] as TransferTransaction).mosaics[0].id.toHex()).to.be.equal(mosaicId.toHex()); - expect(((tx[2] as AggregateTransaction).innerTransactions[4] as MosaicMetadataTransaction) - .targetMosaicId.toHex()).to.be.equal(newMosaicId.toHex()); - return tx; - }); + return transactionService + .resolveAliases(transactionHashesMultiple) + .toPromise() + .then((tx) => { + expect(tx.length).to.be.equal(3); + expect((tx[0] as TransferTransaction).mosaics[0].id.toHex()).to.be.equal(mosaicId.toHex()); + expect((tx[1] as TransferTransaction).mosaics[0].id.toHex()).to.be.equal(mosaicId.toHex()); + expect( + ((tx[2] as AggregateTransaction).innerTransactions[4] as MosaicMetadataTransaction).targetMosaicId.toHex(), + ).to.be.equal(newMosaicId.toHex()); + return tx; + }); }); }); - - function buildAggregateTransaction(): AggregateTransaction { - const transferTransaction = TransferTransaction.create( - Deadline.create(), - addressAlias, - [ - NetworkCurrencyLocal.createAbsolute(1), - new Mosaic(mosaicAlias, UInt64.fromUint(1)), - ], - PlainMessage.create('test-message'), - networkType, helper.maxFee, - ); - // Unlink MosaicAlias - const mosaicAliasTransactionUnlink = MosaicAliasTransaction.create( - Deadline.create(), - AliasAction.Unlink, - mosaicAlias, - mosaicId, - networkType, helper.maxFee, - ); - - // Create a new Mosaic - const nonce = MosaicNonce.createRandom(); - newMosaicId = MosaicId.createFromNonce(nonce, account.publicAccount); - const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( - Deadline.create(), - nonce, - newMosaicId, - MosaicFlags.create(true, true, false), - 3, - UInt64.fromUint(0), - networkType, helper.maxFee, - ); - - // Link namespace with new MosaicId - const mosaicAliasTransactionRelink = MosaicAliasTransaction.create( - Deadline.create(), - AliasAction.Link, - mosaicAlias, - newMosaicId, - networkType, helper.maxFee, - ); - - // Use new mosaicAlias in metadata - const mosaicMetadataTransaction = MosaicMetadataTransaction.create( - Deadline.create(), - account.publicKey, - UInt64.fromUint(5), - mosaicAlias, - 10, - Convert.uint8ToUtf8(new Uint8Array(10)), - networkType, helper.maxFee, - ); - return AggregateTransaction.createComplete(Deadline.create(), - [ - transferTransaction.toAggregate(account.publicAccount), - mosaicAliasTransactionUnlink.toAggregate(account.publicAccount), - mosaicDefinitionTransaction.toAggregate(account.publicAccount), - mosaicAliasTransactionRelink.toAggregate(account.publicAccount), - mosaicMetadataTransaction.toAggregate(account.publicAccount), - - ], - networkType, - [], helper.maxFee, - ); - } - }); diff --git a/e2e/service/TransactionService_AggregateBonded.spec.ts b/e2e/service/TransactionService_AggregateBonded.spec.ts index d8e114517b..7e4c3ec7a6 100644 --- a/e2e/service/TransactionService_AggregateBonded.spec.ts +++ b/e2e/service/TransactionService_AggregateBonded.spec.ts @@ -37,7 +37,6 @@ import { TransactionService } from '../../src/service/TransactionService'; import { IntegrationTestHelper } from '../infrastructure/IntegrationTestHelper'; describe('TransactionService', () => { - const helper = new IntegrationTestHelper(); let account: Account; let account2: Account; @@ -62,8 +61,10 @@ describe('TransactionService', () => { generationHash = helper.generationHash; networkType = helper.networkType; namespaceRepository = helper.repositoryFactory.createNamespaceRepository(); - transactionService = new TransactionService(helper.repositoryFactory.createTransactionRepository(), - helper.repositoryFactory.createReceiptRepository()); + transactionService = new TransactionService( + helper.repositoryFactory.createTransactionRepository(), + helper.repositoryFactory.createReceiptRepository(), + ); }); }); before(() => { @@ -74,20 +75,22 @@ describe('TransactionService', () => { helper.listener.close(); }); - const createSignedAggregatedBondTransaction = (aggregatedTo: Account, - signer: Account, - recipient: Address): SignedTransaction => { + const createSignedAggregatedBondTransaction = (aggregatedTo: Account, signer: Account, recipient: Address): SignedTransaction => { const transferTransaction = TransferTransaction.create( Deadline.create(), - recipient, [], + recipient, + [], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const aggregateTransaction = AggregateTransaction.createBonded( Deadline.create(2, ChronoUnit.MINUTES), [transferTransaction.toAggregate(aggregatedTo.publicAccount)], - networkType, [], helper.maxFee, + networkType, + [], + helper.maxFee, ); return signer.sign(aggregateTransaction, generationHash); }; @@ -99,33 +102,39 @@ describe('TransactionService', () => { */ describe('Get network currency mosaic id', () => { it('get mosaicId', () => { - return namespaceRepository.getLinkedMosaicId(new NamespaceId('cat.currency')).toPromise().then((networkMosaicId: MosaicId) => { - NetworkCurrencyLocalId = networkMosaicId; - }); + return namespaceRepository + .getLinkedMosaicId(new NamespaceId('cat.currency')) + .toPromise() + .then((networkMosaicId: MosaicId) => { + NetworkCurrencyLocalId = networkMosaicId; + }); }); }); describe('Setup test multisig account', () => { - it('Announce MultisigAccountModificationTransaction', () => { const modifyMultisigAccountTransaction = MultisigAccountModificationTransaction.create( Deadline.create(), 2, 1, - [ - cosignAccount1.publicAccount, - cosignAccount2.publicAccount, - cosignAccount3.publicAccount, - ], + [cosignAccount1.publicAccount, cosignAccount2.publicAccount, cosignAccount3.publicAccount], [], - networkType, helper.maxFee, + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [modifyMultisigAccountTransaction.toAggregate(multisigAccount.publicAccount)], - networkType, [], helper.maxFee); - const signedTransaction = aggregateTransaction - .signTransactionWithCosignatories(multisigAccount, [cosignAccount1, cosignAccount2, cosignAccount3], generationHash); + networkType, + [], + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signTransactionWithCosignatories( + multisigAccount, + [cosignAccount1, cosignAccount2, cosignAccount3], + generationHash, + ); return helper.announce(signedTransaction); }); @@ -138,28 +147,28 @@ describe('TransactionService', () => { */ describe('should announce transaction', () => { - it('announce', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), account2.address, - [ - NetworkCurrencyLocal.createAbsolute(1), - ], + [NetworkCurrencyLocal.createAbsolute(1)], PlainMessage.create('test-message'), - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedTransaction = transferTransaction.signWith(account, generationHash); - return transactionService.announce(signedTransaction, helper.listener).toPromise().then((tx: TransferTransaction) => { - expect(tx.signer!.publicKey).to.be.equal(account.publicKey); - expect((tx.recipientAddress as Address).equals(account2.address)).to.be.true; - expect(tx.message.payload).to.be.equal('test-message'); - }); + return transactionService + .announce(signedTransaction, helper.listener) + .toPromise() + .then((tx: TransferTransaction) => { + expect(tx.signer!.publicKey).to.be.equal(account.publicKey); + expect((tx.recipientAddress as Address).equals(account2.address)).to.be.true; + expect(tx.message.payload).to.be.equal('test-message'); + }); }); }); describe('should announce aggregate bonded with hashlock', () => { - it('announce', async () => { const signedAggregatedTransaction = createSignedAggregatedBondTransaction(multisigAccount, account, account2.address); const lockFundsTransaction = LockFundsTransaction.create( @@ -167,19 +176,19 @@ describe('TransactionService', () => { new Mosaic(NetworkCurrencyLocalId, UInt64.fromUint(10 * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY))), UInt64.fromUint(1000), signedAggregatedTransaction, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedLockFundsTransaction = lockFundsTransaction.signWith(account, generationHash); - const tx = await transactionService.announceHashLockAggregateBonded( - signedLockFundsTransaction, signedAggregatedTransaction, helper.listener).toPromise(); + const tx = await transactionService + .announceHashLockAggregateBonded(signedLockFundsTransaction, signedAggregatedTransaction, helper.listener) + .toPromise(); expect(tx.signer!.publicKey).to.be.equal(account.publicKey); expect(tx.type).to.be.equal(TransactionType.AGGREGATE_BONDED); - }); }); describe('should announce aggregate bonded transaction', () => { - it('announce', async () => { const signedAggregatedTransaction = createSignedAggregatedBondTransaction(multisigAccount, account, account2.address); const lockFundsTransaction = LockFundsTransaction.create( @@ -187,16 +196,17 @@ describe('TransactionService', () => { new Mosaic(NetworkCurrencyLocalId, UInt64.fromUint(10 * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY))), UInt64.fromUint(1000), signedAggregatedTransaction, - networkType, helper.maxFee, + networkType, + helper.maxFee, ); const signedLockFundsTransaction = lockFundsTransaction.signWith(account, generationHash); - const signedLockFundsTransactionResponse = - await transactionService.announce(signedLockFundsTransaction, helper.listener).toPromise(); + const signedLockFundsTransactionResponse = await transactionService + .announce(signedLockFundsTransaction, helper.listener) + .toPromise(); expect(signedLockFundsTransactionResponse.transactionInfo!.hash).to.be.equal(signedLockFundsTransaction.hash); const tx = await transactionService.announceAggregateBonded(signedAggregatedTransaction, helper.listener).toPromise(); expect(tx.signer!.publicKey).to.be.equal(account.publicKey); expect(tx.type).to.be.equal(TransactionType.AGGREGATE_BONDED); - }); }); @@ -207,26 +217,24 @@ describe('TransactionService', () => { */ describe('Restore test multisig Accounts', () => { - it('Announce MultisigAccountModificationTransaction', async () => { const removeCosigner1 = MultisigAccountModificationTransaction.create( Deadline.create(), -1, 0, [], - [cosignAccount1.publicAccount, - ], - networkType, helper.maxFee, + [cosignAccount1.publicAccount], + networkType, + helper.maxFee, ); const removeCosigner2 = MultisigAccountModificationTransaction.create( Deadline.create(), 0, 0, [], - [ - cosignAccount2.publicAccount, - ], - networkType, helper.maxFee, + [cosignAccount2.publicAccount], + networkType, + helper.maxFee, ); const removeCosigner3 = MultisigAccountModificationTransaction.create( @@ -234,18 +242,27 @@ describe('TransactionService', () => { -1, -1, [], - [ - cosignAccount3.publicAccount, - ], - networkType, helper.maxFee, + [cosignAccount3.publicAccount], + networkType, + helper.maxFee, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), - [removeCosigner1.toAggregate(multisigAccount.publicAccount), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), + [ + removeCosigner1.toAggregate(multisigAccount.publicAccount), removeCosigner2.toAggregate(multisigAccount.publicAccount), - removeCosigner3.toAggregate(multisigAccount.publicAccount)], networkType, [], helper.maxFee); - const signedTransaction = aggregateTransaction - .signTransactionWithCosignatories(cosignAccount1, [cosignAccount2, cosignAccount3], generationHash); + removeCosigner3.toAggregate(multisigAccount.publicAccount), + ], + networkType, + [], + helper.maxFee, + ); + const signedTransaction = aggregateTransaction.signTransactionWithCosignatories( + cosignAccount1, + [cosignAccount2, cosignAccount3], + generationHash, + ); await helper.announce(signedTransaction); }); diff --git a/package-lock.json b/package-lock.json index 008ad5d7b2..6286f3c703 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "symbol-sdk", - "version": "0.17.4", + "version": "0.18.0", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -353,10 +353,10 @@ "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==", "dev": true }, - "@types/crypto-js": { - "version": "3.1.43", - "resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-3.1.43.tgz", - "integrity": "sha512-EHe/YKctU3IYNBsDmSOPX/7jLHPRlx8WaiDKSY9JCTnJ8XJeM4c0ZJvx+9Gxmr2s2ihI92R+3U/gNL1sq5oRuQ==", + "@types/eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-OCutwjDZ4aFS6PB1UZ988C4YgwlBHJd6wCeQqaLdmadZ/7e+w79+hbMUFC1QXDNCmdyoRfAFdm0RypzwR+Qpag==", "dev": true }, "@types/form-data": { @@ -367,6 +367,12 @@ "@types/node": "*" } }, + "@types/json-schema": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.4.tgz", + "integrity": "sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA==", + "dev": true + }, "@types/lodash": { "version": "4.14.106", "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.106.tgz", @@ -430,6 +436,128 @@ "@types/node": "*" } }, + "@typescript-eslint/eslint-plugin": { + "version": "2.27.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.27.0.tgz", + "integrity": "sha512-/my+vVHRN7zYgcp0n4z5A6HAK7bvKGBiswaM5zIlOQczsxj/aiD7RcgD+dvVFuwFaGh5+kM7XA6Q6PN0bvb1tw==", + "dev": true, + "requires": { + "@typescript-eslint/experimental-utils": "2.27.0", + "functional-red-black-tree": "^1.0.1", + "regexpp": "^3.0.0", + "tsutils": "^3.17.1" + }, + "dependencies": { + "regexpp": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.1.0.tgz", + "integrity": "sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q==", + "dev": true + }, + "tsutils": { + "version": "3.17.1", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.17.1.tgz", + "integrity": "sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + } + } + }, + "@typescript-eslint/experimental-utils": { + "version": "2.27.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-2.27.0.tgz", + "integrity": "sha512-vOsYzjwJlY6E0NJRXPTeCGqjv5OHgRU1kzxHKWJVPjDYGbPgLudBXjIlc+OD1hDBZ4l1DLbOc5VjofKahsu9Jw==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.3", + "@typescript-eslint/typescript-estree": "2.27.0", + "eslint-scope": "^5.0.0", + "eslint-utils": "^2.0.0" + }, + "dependencies": { + "eslint-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.0.0.tgz", + "integrity": "sha512-0HCPuJv+7Wv1bACm8y5/ECVfYdfsAm9xmVb7saeFlxjPYALefjhbYoCkBjPdPzGH8wWyTpAez82Fh3VKYEZ8OA==", + "dev": true, + "requires": { + "eslint-visitor-keys": "^1.1.0" + } + } + } + }, + "@typescript-eslint/parser": { + "version": "2.27.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-2.27.0.tgz", + "integrity": "sha512-HFUXZY+EdwrJXZo31DW4IS1ujQW3krzlRjBrFRrJcMDh0zCu107/nRfhk/uBasO8m0NVDbBF5WZKcIUMRO7vPg==", + "dev": true, + "requires": { + "@types/eslint-visitor-keys": "^1.0.0", + "@typescript-eslint/experimental-utils": "2.27.0", + "@typescript-eslint/typescript-estree": "2.27.0", + "eslint-visitor-keys": "^1.1.0" + } + }, + "@typescript-eslint/typescript-estree": { + "version": "2.27.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.27.0.tgz", + "integrity": "sha512-t2miCCJIb/FU8yArjAvxllxbTiyNqaXJag7UOpB5DVoM3+xnjeOngtqlJkLRnMtzaRcJhe3CIR9RmL40omubhg==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "eslint-visitor-keys": "^1.1.0", + "glob": "^7.1.6", + "is-glob": "^4.0.1", + "lodash": "^4.17.15", + "semver": "^6.3.0", + "tsutils": "^3.17.1" + }, + "dependencies": { + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "tsutils": { + "version": "3.17.1", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.17.1.tgz", + "integrity": "sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + } + } + }, + "acorn": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.1.1.tgz", + "integrity": "sha512-add7dgA5ppRPxCFJoAGfMDi7PIBXq1RtGo7BhbLaxwrXPOmw8gq48Y9ozT01hUKy9byMjlR20EJhu5zlkErEkg==", + "dev": true + }, + "acorn-jsx": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.2.0.tgz", + "integrity": "sha512-HiUX/+K2YpkpJ+SzBffkM/AQ2YE03S0U1kjTLVpoJdhZMOWy8qvXVN9JdLqv2QsaQ6MPYQIuNmwD8zOiYUofLQ==", + "dev": true + }, "aggregate-error": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.0.1.tgz", @@ -460,6 +588,23 @@ "ansi-wrap": "^0.1.0" } }, + "ansi-escapes": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.1.tgz", + "integrity": "sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA==", + "dev": true, + "requires": { + "type-fest": "^0.11.0" + }, + "dependencies": { + "type-fest": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.11.0.tgz", + "integrity": "sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ==", + "dev": true + } + } + }, "ansi-gray": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/ansi-gray/-/ansi-gray-0.1.1.tgz", @@ -677,6 +822,12 @@ "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", "dev": true }, + "astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", + "dev": true + }, "async-done": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/async-done/-/async-done-1.3.1.tgz", @@ -1109,12 +1260,6 @@ "resolved": "https://registry.npmjs.org/buffer-reverse/-/buffer-reverse-1.0.1.tgz", "integrity": "sha1-SSg8jvpvkBvAH6MwTQYCeXGuL2A=" }, - "builtin-modules": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", - "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", - "dev": true - }, "cache-base": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", @@ -1144,6 +1289,12 @@ "write-file-atomic": "^3.0.0" } }, + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true + }, "camelcase": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", @@ -1185,6 +1336,12 @@ "supports-color": "^5.3.0" } }, + "chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, "check-error": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", @@ -1248,6 +1405,21 @@ "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", "dev": true }, + "cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "requires": { + "restore-cursor": "^3.1.0" + } + }, + "cli-width": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", + "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=", + "dev": true + }, "cliui": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", @@ -1344,12 +1516,6 @@ "delayed-stream": "~1.0.0" } }, - "commander": { - "version": "2.20.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", - "dev": true - }, "commondir": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", @@ -1449,9 +1615,9 @@ } }, "crypto-js": { - "version": "3.1.9-1", - "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-3.1.9-1.tgz", - "integrity": "sha1-/aGedh/Ad+Af+/3G6f38WeiAbNg=" + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.0.0.tgz", + "integrity": "sha512-bzHZN8Pn+gS7DQA6n+iUmBfl0hO5DJq++QP3U6uTucDtk/0iGpXd/Gg7CGR0p8tJhofJyaKoWBuJI4eAO00BBg==" }, "d": { "version": "1.0.0", @@ -1508,6 +1674,12 @@ "type-detect": "^4.0.0" } }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, "default-compare": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/default-compare/-/default-compare-1.0.0.tgz", @@ -1622,6 +1794,15 @@ "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==" }, + "doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, "duplexify": { "version": "3.7.1", "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.7.1.tgz", @@ -1732,12 +1913,226 @@ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, + "eslint": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-6.8.0.tgz", + "integrity": "sha512-K+Iayyo2LtyYhDSYwz5D5QdWw0hCacNzyq1Y821Xna2xSJj7cijoLLYmLxTQgcgZ9mC61nryMy9S7GRbYpI5Ig==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "ajv": "^6.10.0", + "chalk": "^2.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", + "doctrine": "^3.0.0", + "eslint-scope": "^5.0.0", + "eslint-utils": "^1.4.3", + "eslint-visitor-keys": "^1.1.0", + "espree": "^6.1.2", + "esquery": "^1.0.1", + "esutils": "^2.0.2", + "file-entry-cache": "^5.0.1", + "functional-red-black-tree": "^1.0.1", + "glob-parent": "^5.0.0", + "globals": "^12.1.0", + "ignore": "^4.0.6", + "import-fresh": "^3.0.0", + "imurmurhash": "^0.1.4", + "inquirer": "^7.0.0", + "is-glob": "^4.0.0", + "js-yaml": "^3.13.1", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.14", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.3", + "progress": "^2.0.0", + "regexpp": "^2.0.1", + "semver": "^6.1.2", + "strip-ansi": "^5.2.0", + "strip-json-comments": "^3.0.1", + "table": "^5.2.3", + "text-table": "^0.2.0", + "v8-compile-cache": "^2.0.3" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "dependencies": { + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true + } + } + }, + "glob-parent": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", + "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", + "dev": true, + "requires": { + "is-glob": "^4.0.1" + } + }, + "globals": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz", + "integrity": "sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg==", + "dev": true, + "requires": { + "type-fest": "^0.8.1" + } + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "eslint-config-prettier": { + "version": "6.10.1", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-6.10.1.tgz", + "integrity": "sha512-svTy6zh1ecQojvpbJSgH3aei/Rt7C6i090l5f2WQ4aB05lYHeZIR1qL4wZyyILTbtmnbHP5Yn8MrsOJMGa8RkQ==", + "dev": true, + "requires": { + "get-stdin": "^6.0.0" + } + }, + "eslint-plugin-prettier": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.1.3.tgz", + "integrity": "sha512-+HG5jmu/dN3ZV3T6eCD7a4BlAySdN7mLIbJYo0z1cFQuI+r2DiTJEFeF68ots93PsnrMxbzIZ2S/ieX+mkrBeQ==", + "dev": true, + "requires": { + "prettier-linter-helpers": "^1.0.0" + } + }, + "eslint-scope": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.0.0.tgz", + "integrity": "sha512-oYrhJW7S0bxAFDvWqzvMPRm6pcgcnWc4QnofCAqRTRfQC0JcwenzGglTtsLyIuuWFfkqDG9vz67cnttSd53djw==", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "eslint-utils": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.3.tgz", + "integrity": "sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==", + "dev": true, + "requires": { + "eslint-visitor-keys": "^1.1.0" + } + }, + "eslint-visitor-keys": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz", + "integrity": "sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A==", + "dev": true + }, + "espree": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-6.2.1.tgz", + "integrity": "sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw==", + "dev": true, + "requires": { + "acorn": "^7.1.1", + "acorn-jsx": "^5.2.0", + "eslint-visitor-keys": "^1.1.0" + } + }, "esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true }, + "esquery": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.2.0.tgz", + "integrity": "sha512-weltsSqdeWIX9G2qQZz7KlTRJdkkOCTPgLYJUz1Hacf48R4YOwGPHO3+ORfWedqJKbq5WQmsgK90n+pFLIKt/Q==", + "dev": true, + "requires": { + "estraverse": "^5.0.0" + }, + "dependencies": { + "estraverse": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.0.0.tgz", + "integrity": "sha512-j3acdrMzqrxmJTNj5dbr1YbjacrYgAxVMeF0gK16E3j494mOe7xygM/ZLIguEQ0ETwAg2hlJCtHRGav+y0Ny5A==", + "dev": true + } + } + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "requires": { + "estraverse": "^4.1.0" + } + }, + "estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true + }, "esutils": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", @@ -1822,6 +2217,17 @@ } } }, + "external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "requires": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + } + }, "extglob": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", @@ -1909,11 +2315,41 @@ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=" }, + "fast-diff": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", + "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", + "dev": true + }, "fast-json-stable-stringify": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "file-entry-cache": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", + "integrity": "sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==", + "dev": true, + "requires": { + "flat-cache": "^2.0.1" + } + }, "fill-range": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", @@ -1989,6 +2425,48 @@ "integrity": "sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q==", "dev": true }, + "flat-cache": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", + "integrity": "sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==", + "dev": true, + "requires": { + "flatted": "^2.0.0", + "rimraf": "2.6.3", + "write": "1.0.3" + }, + "dependencies": { + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + } + } + }, + "flatted": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz", + "integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==", + "dev": true + }, "flush-write-stream": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.1.1.tgz", @@ -2631,6 +3109,12 @@ "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, + "functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", + "dev": true + }, "futoin-hkdf": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/futoin-hkdf/-/futoin-hkdf-1.3.1.tgz", @@ -2654,6 +3138,12 @@ "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", "dev": true }, + "get-stdin": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-6.0.0.tgz", + "integrity": "sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==", + "dev": true + }, "get-value": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", @@ -3003,6 +3493,39 @@ "sshpk": "^1.7.0" } }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true + }, + "import-fresh": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.2.1.tgz", + "integrity": "sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ==", + "dev": true, + "requires": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "dependencies": { + "resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true + } + } + }, "imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", @@ -3025,17 +3548,122 @@ "wrappy": "1" } }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" - }, - "ini": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", - "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", - "dev": true - }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", + "dev": true + }, + "inquirer": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-7.1.0.tgz", + "integrity": "sha512-5fJMWEmikSYu0nv/flMc475MhGbB7TSPd/2IpFV4I4rMklboCH2rQjYY5kKiYGHqUF9gvaambupcJFFG9dvReg==", + "dev": true, + "requires": { + "ansi-escapes": "^4.2.1", + "chalk": "^3.0.0", + "cli-cursor": "^3.1.0", + "cli-width": "^2.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.15", + "mute-stream": "0.0.8", + "run-async": "^2.4.0", + "rxjs": "^6.5.3", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", + "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.0" + } + }, + "supports-color": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", + "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, "interpret": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", @@ -3216,6 +3844,12 @@ "isobject": "^3.0.1" } }, + "is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", + "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", + "dev": true + }, "is-relative": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", @@ -3487,9 +4121,9 @@ "dev": true }, "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", "dev": true }, "last-run": { @@ -3535,6 +4169,16 @@ "flush-write-stream": "^1.0.2" } }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, "liftoff": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/liftoff/-/liftoff-3.1.0.tgz", @@ -3603,6 +4247,16 @@ "js-tokens": "^3.0.0 || ^4.0.0" } }, + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, "make-dir": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz", @@ -3702,6 +4356,11 @@ "treeify": "^1.1.0" }, "dependencies": { + "crypto-js": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-3.3.0.tgz", + "integrity": "sha512-DIT51nX0dCfKltpRiXV+/TVZq+Qq2NgF4644+K7Ttnla7zEzqc+kjJyiB96BHNyUTBxyjzRcZYpUdZa+QAqi6Q==" + }, "is-buffer": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.4.tgz", @@ -3743,6 +4402,12 @@ "mime-db": "~1.33.0" } }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true + }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", @@ -3853,6 +4518,12 @@ "integrity": "sha512-kDcwXR4PS7caBpuRYYBUz9iVixUk3anO3f5OYFiIPwK/20vCzKCHyKoulbiDY1S53zD2bxUpxN/IJ+TnXjfvxg==", "dev": true }, + "mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true + }, "nanomatch": { "version": "1.2.13", "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", @@ -3872,12 +4543,24 @@ "to-regex": "^3.0.1" } }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, "next-tick": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=", "dev": true }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, "node-preload": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/node-preload/-/node-preload-0.2.1.tgz", @@ -4268,6 +4951,29 @@ "wrappy": "1" } }, + "onetime": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz", + "integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==", + "dev": true, + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + } + }, "ordered-read-streams": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/ordered-read-streams/-/ordered-read-streams-1.0.1.tgz", @@ -4291,6 +4997,12 @@ "lcid": "^1.0.0" } }, + "os-shim": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/os-shim/-/os-shim-0.1.3.tgz", + "integrity": "sha1-a2LDeRz3kJ6jXtRuF2WLtBfLORc=", + "dev": true + }, "os-tmpdir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", @@ -4341,6 +5053,15 @@ "release-zalgo": "^1.0.0" } }, + "parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "requires": { + "callsites": "^3.0.0" + } + }, "parse-filepath": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", @@ -4514,6 +5235,75 @@ "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", "dev": true }, + "pre-commit": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/pre-commit/-/pre-commit-1.2.2.tgz", + "integrity": "sha1-287g7p3nI15X95xW186UZBpp7sY=", + "dev": true, + "requires": { + "cross-spawn": "^5.0.1", + "spawn-sync": "^1.0.15", + "which": "1.2.x" + }, + "dependencies": { + "cross-spawn": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", + "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", + "dev": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "which": { + "version": "1.2.14", + "resolved": "https://registry.npmjs.org/which/-/which-1.2.14.tgz", + "integrity": "sha1-mofEN48D6CfOyvGs31bHNsAcFOU=", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "prettier": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.4.tgz", + "integrity": "sha512-SVJIQ51spzFDvh4fIbCLvciiDMCrRhlN3mbZvv/+ycjvmF5E73bKdGfU8QDLNmjYJf+lsGnDBC4UUnvTe5OO0w==", + "dev": true + }, + "prettier-linter-helpers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", + "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", + "dev": true, + "requires": { + "fast-diff": "^1.1.2" + } + }, "pretty-hrtime": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz", @@ -4540,6 +5330,18 @@ "fromentries": "^1.2.0" } }, + "progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", + "dev": true + }, "psl": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/psl/-/psl-1.4.0.tgz", @@ -4647,6 +5449,12 @@ "safe-regex": "^1.1.0" } }, + "regexpp": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", + "dev": true + }, "release-zalgo": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/release-zalgo/-/release-zalgo-1.0.0.tgz", @@ -4846,6 +5654,16 @@ "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", "dev": true }, + "restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "requires": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + } + }, "ret": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", @@ -4895,6 +5713,15 @@ "inherits": "^2.0.1" } }, + "run-async": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.0.tgz", + "integrity": "sha512-xJTbh/d7Lm7SBhc1tNvTpeCHaEzoyxPrqNlvSdMfBTYwaY++UJFyXUOxAtsRUXjlqOfj8luNaR9vjCh4KeV+pg==", + "dev": true, + "requires": { + "is-promise": "^2.1.0" + } + }, "rxjs": { "version": "6.5.3", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.3.tgz", @@ -4922,6 +5749,12 @@ "ret": "~0.1.10" } }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, "secure-random": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/secure-random/-/secure-random-1.1.1.tgz", @@ -4998,6 +5831,25 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=" }, + "slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + }, + "dependencies": { + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + } + } + }, "snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", @@ -5152,6 +6004,16 @@ "integrity": "sha512-dSO0DDYUahUt/0/pD/Is3VIm5TGJjludZ0HVymmhYF6eNA53PVLhnUk0znSYbH8IYBuJdCE+1luR22jNLMaQdw==", "dev": true }, + "spawn-sync": { + "version": "1.0.15", + "resolved": "https://registry.npmjs.org/spawn-sync/-/spawn-sync-1.0.15.tgz", + "integrity": "sha1-sAeZVX63+wyDdsKdROih6mfldHY=", + "dev": true, + "requires": { + "concat-stream": "^1.4.7", + "os-shim": "^0.1.2" + } + }, "spawn-wrap": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/spawn-wrap/-/spawn-wrap-2.0.0.tgz", @@ -5328,6 +6190,12 @@ "is-utf8": "^0.2.0" } }, + "strip-json-comments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.0.tgz", + "integrity": "sha512-e6/d0eBu7gHtdCqFt0xJr642LdToM5/cN4Qb9DbHjVx1CP5RyeM+zH7pbecEmDv/lBqb0QH+6Uqq75rxFPkM0w==", + "dev": true + }, "supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", @@ -5367,6 +6235,58 @@ "rewire": "^3.0.2" } }, + "table": { + "version": "5.4.6", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", + "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==", + "dev": true, + "requires": { + "ajv": "^6.10.2", + "lodash": "^4.17.14", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, "test-exclude": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", @@ -5394,6 +6314,18 @@ } } }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, "through2": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", @@ -5420,6 +6352,15 @@ "integrity": "sha1-dkpaEa9QVhkhsTPztE5hhofg9cM=", "dev": true }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.2" + } + }, "to-absolute-glob": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/to-absolute-glob/-/to-absolute-glob-2.0.2.tgz", @@ -5550,44 +6491,6 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.0.tgz", "integrity": "sha512-f/qGG2tUkrISBlQZEjEqoZ3B2+npJjIf04H1wuAv9iA8i04Icp+61KRXxFdha22670NJopsZCIjhC3SnjPRKrQ==" }, - "tslint": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/tslint/-/tslint-6.0.0.tgz", - "integrity": "sha512-9nLya8GBtlFmmFMW7oXXwoXS1NkrccqTqAtwXzdPV9e2mqSEvCki6iHL/Fbzi5oqbugshzgGPk7KBb2qNP1DSA==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "builtin-modules": "^1.1.1", - "chalk": "^2.3.0", - "commander": "^2.12.1", - "diff": "^4.0.1", - "glob": "^7.1.1", - "js-yaml": "^3.13.1", - "minimatch": "^3.0.4", - "mkdirp": "^0.5.1", - "resolve": "^1.3.2", - "semver": "^5.3.0", - "tslib": "^1.10.0", - "tsutils": "^2.29.0" - }, - "dependencies": { - "tslib": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", - "integrity": "sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA==", - "dev": true - } - } - }, - "tsutils": { - "version": "2.29.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", - "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", - "dev": true, - "requires": { - "tslib": "^1.8.1" - } - }, "tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", @@ -5601,6 +6504,15 @@ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + }, "type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -5808,6 +6720,12 @@ "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.3.tgz", "integrity": "sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ==" }, + "v8-compile-cache": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.1.0.tgz", + "integrity": "sha512-usZBT3PW+LOjM25wbqIlZwPeJV+3OSz3M1k1Ws8snlW39dZyYL9lOGC5FgPVHfk0jKmjiDV8Z0mIbVQPiwFs7g==", + "dev": true + }, "v8flags": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-3.1.3.tgz", @@ -5912,6 +6830,12 @@ "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=", "dev": true }, + "word-wrap": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", + "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", + "dev": true + }, "wrap-ansi": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", @@ -5928,6 +6852,15 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, + "write": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/write/-/write-1.0.3.tgz", + "integrity": "sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig==", + "dev": true, + "requires": { + "mkdirp": "^0.5.1" + } + }, "write-file-atomic": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", @@ -5957,6 +6890,12 @@ "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", "dev": true }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + }, "yargs": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/yargs/-/yargs-7.1.0.tgz", diff --git a/package.json b/package.json index 8e49a2ce36..80c2f5dbb2 100644 --- a/package.json +++ b/package.json @@ -1,95 +1,108 @@ { - "name": "symbol-sdk", - "version": "0.17.4", - "description": "Reactive symbol sdk for typescript and javascript", - "scripts": { - "pretest": "npm run build", - "test": "mocha --ui bdd --recursive ./dist/test --timeout 90000", - "e2econfigcopy": "gulp", - "test:e2e": "npm run build && mocha --ui bdd --recursive ./dist/e2e --timeout 90000", - "test:all": "mocha --ui bdd --recursive ./dist/ --timeout 90000", - "build": "rm -rf dist/ && tsc && npm run e2econfigcopy", - "test:cov": "nyc --reporter=lcov --reporter=text-summary npm t", - "test:coveralls": "npm run test:cov | coveralls", - "coveralls-report": "cat ./coverage/lcov.info | coveralls", - "version": "echo $npm_package_version" - }, - "contributors": [ - { - "name": "Aleix", - "email": "aleix@nemeurope.eu" + "name": "symbol-sdk", + "version": "0.18.0", + "description": "Reactive symbol sdk for typescript and javascript", + "scripts": { + "pretest": "npm run build", + "test": "mocha --ui bdd --recursive ./dist/test --timeout 90000", + "e2econfigcopy": "gulp", + "test:e2e": "npm run build && mocha --ui bdd --recursive ./dist/e2e --timeout 90000", + "test:all": "mocha --ui bdd --recursive ./dist/ --timeout 90000", + "build": "rm -rf dist/ && tsc && npm run e2econfigcopy", + "test:cov": "nyc --reporter=lcov --reporter=text-summary npm t", + "test:coveralls": "npm run test:cov | coveralls", + "coveralls-report": "cat ./coverage/lcov.info | coveralls", + "version": "echo $npm_package_version", + "prettier": "prettier --write ./src ./test ./e2e", + "lint": "eslint --cache src/ test/ e2e/ --ext .ts", + "lint:fix": "eslint src/ test/ e2e/ --ext .ts --fix", + "style:fix": "npm run prettier && npm run lint:fix" }, - { - "name": "Guillem", - "email": "guillem@nemeurope.eu" + "pre-commit": [ + "lint" + ], + "contributors": [ + { + "name": "Aleix", + "email": "aleix@nemeurope.eu" + }, + { + "name": "Guillem", + "email": "guillem@nemeurope.eu" + } + ], + "bugs": "https://github.com/nemtech/symbol-sdk-typescript-javascript/issues", + "repository": { + "type": "git", + "url": "https://github.com/nemtech/symbol-sdk-typescript-javascript.git" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/nemtech/symbol-sdk-typescript-javascript#readme", + "main": "dist/index.js", + "typings": "dist/index.d.ts", + "devDependencies": { + "@types/chai": "^4.0.4", + "@types/lodash": "^4.14.85", + "@types/long": "^4.0.0", + "@types/mocha": "^2.2.44", + "@types/request": "^2.47.0", + "@types/request-promise-native": "^1.0.14", + "@types/utf8": "^2.1.6", + "@types/ws": "^3.2.0", + "@typescript-eslint/eslint-plugin": "^2.27.0", + "@typescript-eslint/parser": "^2.27.0", + "assert": "^1.4.1", + "chai": "^4.1.2", + "coveralls": "^3.0.9", + "eslint": "^6.8.0", + "eslint-config-prettier": "^6.10.1", + "eslint-plugin-prettier": "^3.1.3", + "gulp": "^4.0.2", + "gulp-typescript": "^5.0.1", + "kind-of": ">=6.0.3", + "mocha": "^4.0.1", + "nyc": "^15.0.0", + "pre-commit": "^1.2.2", + "prettier": "^2.0.4", + "secure-random": "^1.1.1", + "ts-mockito": "^2.4.0", + "ts-node": "^8.6.2", + "typescript": "^3.7.5", + "typescript-require": "^0.2.10" + }, + "dependencies": { + "bluebird": "^3.7.2", + "catbuffer-typescript": "0.0.11", + "crypto-js": "^4.0.0", + "diff": "^4.0.2", + "futoin-hkdf": "^1.3.1", + "js-joda": "^1.6.2", + "js-sha256": "^0.9.0", + "js-sha3": "^0.8.0", + "js-sha512": "^0.8.0", + "long": "^4.0.0", + "merkletreejs": "^0.1.7", + "minimist": "^1.2.5", + "request": "^2.88.0", + "request-promise-native": "^1.0.5", + "ripemd160": "^2.0.2", + "rxjs": "^6.5.3", + "rxjs-compat": "^6.5.3", + "symbol-openapi-typescript-node-client": "0.8.9", + "tweetnacl": "^1.0.3", + "utf8": "^3.0.0", + "ws": "^7.2.3" + }, + "peerDependencies": { + "js-joda": "^1.6.2", + "utf8": "^2.1.2", + "rxjs": "^6.5.3" + }, + "nyc": { + "exclude-after-remap": false, + "exclude": [ + "**/*.spec.js", + "gulpfile.js" + ] } - ], - "bugs": "https://github.com/nemtech/symbol-sdk-typescript-javascript/issues", - "repository": { - "type": "git", - "url": "https://github.com/nemtech/symbol-sdk-typescript-javascript.git" - }, - "license": "Apache-2.0", - "homepage": "https://github.com/nemtech/symbol-sdk-typescript-javascript#readme", - "main": "dist/index.js", - "typings": "dist/index.d.ts", - "devDependencies": { - "@types/chai": "^4.0.4", - "@types/crypto-js": "^3.1.43", - "@types/lodash": "^4.14.85", - "@types/long": "^4.0.0", - "@types/mocha": "^2.2.44", - "@types/request": "^2.47.0", - "@types/request-promise-native": "^1.0.14", - "@types/utf8": "^2.1.6", - "@types/ws": "^3.2.0", - "assert": "^1.4.1", - "chai": "^4.1.2", - "coveralls": "^3.0.9", - "gulp": "^4.0.2", - "gulp-typescript": "^5.0.1", - "mocha": "^4.0.1", - "nyc": "^15.0.0", - "secure-random": "^1.1.1", - "ts-mockito": "^2.4.0", - "ts-node": "^8.6.2", - "tslint": "^6.0.0", - "typescript": "^3.7.5", - "typescript-require": "^0.2.10" - }, - "dependencies": { - "bluebird": "^3.7.2", - "catbuffer-typescript": "0.0.11", - "crypto-js": "^3.1.9-1", - "diff": "^4.0.2", - "futoin-hkdf": "^1.3.1", - "js-joda": "^1.6.2", - "js-sha256": "^0.9.0", - "js-sha3": "^0.8.0", - "js-sha512": "^0.8.0", - "long": "^4.0.0", - "merkletreejs": "^0.1.7", - "minimist": "^1.2.5", - "request": "^2.88.0", - "request-promise-native": "^1.0.5", - "ripemd160": "^2.0.2", - "rxjs": "^6.5.3", - "rxjs-compat": "^6.5.3", - "symbol-openapi-typescript-node-client": "0.8.9", - "tweetnacl": "^1.0.3", - "utf8": "^3.0.0", - "ws": "^7.2.3" - }, - "peerDependencies": { - "js-joda": "^1.6.2", - "utf8": "^2.1.2", - "rxjs": "^6.5.3" - }, - "nyc": { - "exclude-after-remap": false, - "exclude": [ - "**/*.spec.js", - "gulpfile.js" - ] - } } diff --git a/src/core/crypto/Crypto.ts b/src/core/crypto/Crypto.ts index 924f55039f..4db28ca259 100644 --- a/src/core/crypto/Crypto.ts +++ b/src/core/crypto/Crypto.ts @@ -1,5 +1,5 @@ /* - * Copyright 2019 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,202 +14,67 @@ * limitations under the License. */ -import { WalletAlgorithm } from '../../model/wallet/WalletAlgorithm'; import { Convert as convert } from '../format/Convert'; import { KeyPair } from './KeyPair'; import * as utility from './Utilities'; -// tslint:disable-next-line: no-var-requires +// eslint-disable-next-line @typescript-eslint/no-var-requires const CryptoJS = require('crypto-js'); + export class Crypto { /** - * Encrypt a private key for mobile apps (AES_PBKF2) - * - * @param {string} password - A wallet password - * @param {string} privateKey - An account private key - * - * @return {object} - The encrypted data + * Encrypt data + * @param {string} data + * @param {string} salt + * @param {string} password */ - public static toMobileKey = (password, privateKey) => { - // Errors - if (!password || !privateKey) { throw new Error('Missing argument !'); } - // Processing - const salt = CryptoJS.lib.WordArray.random(256 / 8); + public static encrypt(data: string, password: string): string { + const salt = CryptoJS.lib.WordArray.random(16); + + // generate password based key const key = CryptoJS.PBKDF2(password, salt, { - keySize: 256 / 32, - iterations: 2000, + keySize: 8, + iterations: 1024, }); - const iv = Crypto.randomBytes(16); - const encIv = { - iv: utility.ua2words(iv, 16), - }; - const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Hex.parse(privateKey), key, encIv); - // Result - return { - encrypted: convert.uint8ToHex(iv) + encrypted.ciphertext, - salt: salt.toString(), - }; - } - /** - * Derive a private key from a password using count iterations of SHA3-256 - * - * @param {string} password - A wallet password - * @param {number} count - A number of iterations above 0 - * - * @return {object} - The derived private key - */ - public static derivePassSha = (password, count) => { - // Errors - if (!password) { throw new Error('Missing argument !'); } - if (!count || count <= 0) { throw new Error('Please provide a count number above 0'); } - // Processing - let data = password; - for (let i = 0; i < count; ++i) { - data = CryptoJS.SHA3(data, { - outputLength: 256, - }); - } - // Result - return { - priv: CryptoJS.enc.Hex.stringify(data), - }; - } + // encrypt using random IV + const iv = CryptoJS.lib.WordArray.random(16); + const encrypted = CryptoJS.AES.encrypt(data, key, { + iv: iv, + padding: CryptoJS.pad.Pkcs7, + mode: CryptoJS.mode.CBC, + }); - /** - * Encrypt hex data using a key - * - * @param {string} data - An hex string - * @param {Uint8Array} key - An Uint8Array key - * - * @return {object} - The encrypted data - */ - public static encrypt = (data, key) => { - // Errors - if (!data || !key) { throw new Error('Missing argument !'); } - // Processing - const iv = Crypto.randomBytes(16); - const encKey = utility.ua2words(key, 32); - const encIv = { - iv: utility.ua2words(iv, 16), - }; - const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Hex.parse(data), encKey, encIv); - // Result - return { - ciphertext: encrypted.ciphertext, - iv, - key, - }; + // salt (16 bytes) + iv (16 bytes) + // prepend them to the ciphertext for use in decryption + return salt.toString() + iv.toString() + encrypted.toString(); } /** * Decrypt data - * - * @param {object} data - An encrypted data object - * - * @return {string} - The decrypted hex string + * @param {string} data + * @param {string} salt + * @param {string} password */ - public static decrypt = (data) => { - // Errors - if (!data) { throw new Error('Missing argument !'); } - // Processing - const encKey = utility.ua2words(data.key, 32); - const encIv = { - iv: utility.ua2words(data.iv, 16), - }; - // Result - return CryptoJS.enc.Hex.stringify(CryptoJS.AES.decrypt(data, encKey, encIv)); - } + public static decrypt(data: string, password: string): string { + const salt = CryptoJS.enc.Hex.parse(data.substr(0, 32)); + const iv = CryptoJS.enc.Hex.parse(data.substr(32, 32)); + const encrypted = data.substring(64); - /** - * Reveal the private key of an account or derive it from the wallet password - * - * @param {object} common- An object containing password and privateKey field - * @param {object} walletAccount - A wallet account object - * @param {WalletAlgorithm} algo - A wallet algorithm - * - * @return {object|boolean} - The account private key in and object or false - */ - public static passwordToPrivateKey = (common, walletAccount, algo) => { - // Errors - if (!common || !common.password || !walletAccount || !algo) { throw new Error('Missing argument !'); } - // Processing - let r; - if (algo === WalletAlgorithm.Pass_6k) { // Brain wallets - if (!walletAccount.encrypted && !walletAccount.iv) { - // Account private key is generated simply using a passphrase so it has no encrypted and iv - r = Crypto.derivePassSha(common.password, 6000); - } else if (!walletAccount.encrypted || !walletAccount.iv) { - // Else if one is missing there is a problem - return false; - } else { - // Else child accounts have encrypted and iv so we decrypt - const pass = Crypto.derivePassSha(common.password, 20); - const obj = { - ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted), - iv: convert.hexToUint8(walletAccount.iv), - key: convert.hexToUint8(pass.priv), - }; - const d = Crypto.decrypt(obj); - r = { priv: d }; - } - } else if (algo === WalletAlgorithm.Pass_bip32) { // Wallets from PRNG - const pass = Crypto.derivePassSha(common.password, 20); - const obj = { - ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted), - iv: convert.hexToUint8(walletAccount.iv), - key: convert.hexToUint8(pass.priv), - }; - const d = Crypto.decrypt(obj); - r = { priv: d }; - } else if (algo === WalletAlgorithm.Pass_enc) { // Private Key wallets - const pass = Crypto.derivePassSha(common.password, 20); - const obj = { - ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted), - iv: convert.hexToUint8(walletAccount.iv), - key: convert.hexToUint8(pass.priv), - }; - const d = Crypto.decrypt(obj); - r = { priv: d }; - } else if (algo === WalletAlgorithm.Trezor) { // HW wallet - r = { priv: '' }; - common.isHW = true; - } else { - return false; - } - // Result - common.privateKey = r.priv; - return true; - } + // generate password based key + const key = CryptoJS.PBKDF2(password, salt, { + keySize: 8, + iterations: 1024, + }); - /** - * Generate a random key - * - * @return {Uint8Array} - A random key - */ - public static randomKey = () => { - return Crypto.randomBytes(32); - } + // decrypt using custom IV + const decrypted = CryptoJS.AES.decrypt(encrypted, key, { + iv: iv, + padding: CryptoJS.pad.Pkcs7, + mode: CryptoJS.mode.CBC, + }); - /** - * Encode a private key using a password - * - * @param {string} privateKey - An hex private key - * @param {string} password - A password - * - * @return {object} - The encoded data - */ - public static encodePrivateKey = (privateKey, password) => { - // Errors - if (!privateKey || !password) { throw new Error('Missing argument !'); } - // Processing - const pass = Crypto.derivePassSha(password, 20); - const r = Crypto.encrypt(privateKey, convert.hexToUint8(pass.priv)); - // Result - return { - ciphertext: CryptoJS.enc.Hex.stringify(r.ciphertext), - iv: convert.uint8ToHex(r.iv), - }; + return decrypted.toString(CryptoJS.enc.Utf8); } /*** @@ -222,12 +87,11 @@ export class Crypto { * @param {Uint8Array} salt - A salt * @return {string} - The encoded message */ - public static _encode = (senderPriv: string, - recipientPub: string, - msg: string, - iv: Uint8Array): string => { + public static _encode = (senderPriv: string, recipientPub: string, msg: string, iv: Uint8Array): string => { // Errors - if (!senderPriv || !recipientPub || !msg || !iv) { throw new Error('Missing argument !'); } + if (!senderPriv || !recipientPub || !msg || !iv) { + throw new Error('Missing argument !'); + } // Processing const keyPair = KeyPair.createKeyPairFromPrivateKeyString(senderPriv); const pk = convert.hexToUint8(recipientPub); @@ -239,7 +103,7 @@ export class Crypto { // Result const result = convert.uint8ToHex(iv) + CryptoJS.enc.Hex.stringify(encrypted.ciphertext); return result; - } + }; /** * Encode a message @@ -250,18 +114,17 @@ export class Crypto { * @param {boolean} isHexString - Is payload string a hexadecimal string (default = false) * @return {string} - The encoded message */ - public static encode = (senderPriv: string, - recipientPub: string, - msg: string, - isHexString: boolean = false): string => { + public static encode = (senderPriv: string, recipientPub: string, msg: string, isHexString = false): string => { // Errors - if (!senderPriv || !recipientPub || !msg) { throw new Error('Missing argument !'); } + if (!senderPriv || !recipientPub || !msg) { + throw new Error('Missing argument !'); + } // Processing const iv = Crypto.randomBytes(16); const encoded = Crypto._encode(senderPriv, recipientPub, isHexString ? msg : convert.utf8ToHex(msg), iv); // Result return encoded; - } + }; /** * Decode an encrypted message payload @@ -272,12 +135,11 @@ export class Crypto { * @param {Uint8Array} iv - 16-byte AES initialization vector * @return {string} - The decoded payload as hex */ - public static _decode = (recipientPrivate: string, - senderPublic: string, - payload: Uint8Array, - iv: Uint8Array): string => { + public static _decode = (recipientPrivate: string, senderPublic: string, payload: Uint8Array, iv: Uint8Array): string => { // Error - if (!recipientPrivate || !senderPublic || !payload) { throw new Error('Missing argument !'); } + if (!recipientPrivate || !senderPublic || !payload) { + throw new Error('Missing argument !'); + } // Processing const keyPair = KeyPair.createKeyPairFromPrivateKeyString(recipientPrivate); const pk = convert.hexToUint8(senderPublic); @@ -291,7 +153,7 @@ export class Crypto { const plain = CryptoJS.AES.decrypt(encrypted, encKey, encIv); // Result return CryptoJS.enc.Hex.stringify(plain); - } + }; /** * Decode an encrypted message payload @@ -301,18 +163,18 @@ export class Crypto { * @param {string} payload - An encrypted message payload * @return {string} - The decoded payload as hex */ - public static decode = (recipientPrivate: string, - senderPublic: string, - payload: string): string => { + public static decode = (recipientPrivate: string, senderPublic: string, payload: string): string => { // Error - if (!recipientPrivate || !senderPublic || !payload) { throw new Error('Missing argument !'); } + if (!recipientPrivate || !senderPublic || !payload) { + throw new Error('Missing argument !'); + } // Processing const binPayload = convert.hexToUint8(payload); const payloadBuffer = new Uint8Array(binPayload.buffer, 16); const iv = new Uint8Array(binPayload.buffer, 0, 16); const decoded = Crypto._decode(recipientPrivate, senderPublic, payloadBuffer, iv); return decoded.toUpperCase(); - } + }; /** * Generate random bytes by length @@ -320,8 +182,9 @@ export class Crypto { * * @return {Uint8Array} */ - public static randomBytes = (length) => { + public static randomBytes = (length: number): any => { + // eslint-disable-next-line @typescript-eslint/no-var-requires const crypto = require('crypto'); return crypto.randomBytes(length); - } + }; } diff --git a/src/core/crypto/KeyPair.ts b/src/core/crypto/KeyPair.ts index 320175cdae..02fd78906d 100644 --- a/src/core/crypto/KeyPair.ts +++ b/src/core/crypto/KeyPair.ts @@ -1,5 +1,5 @@ /* - * Copyright 2019 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,16 +23,18 @@ export class KeyPair { * @param {string} privateKeyString A hex encoded private key string. * @returns {module:crypto/keyPair~KeyPair} The key pair. */ - public static createKeyPairFromPrivateKeyString(privateKeyString: string) { + public static createKeyPairFromPrivateKeyString( + privateKeyString: string, + ): { + privateKey: Uint8Array; + publicKey: Uint8Array; + } { const privateKey = convert.hexToUint8(privateKeyString); if (Utility.Key_Size !== privateKey.length) { throw Error(`private key has unexpected size: ${privateKey.length}`); } - const keyPair = nacl.sign.keyPair.fromSeed(privateKey); - return { - privateKey, - publicKey: keyPair.publicKey, - }; + const { publicKey } = nacl.sign.keyPair.fromSeed(privateKey); + return { privateKey, publicKey }; } /** diff --git a/src/core/crypto/MerkleHashBuilder.ts b/src/core/crypto/MerkleHashBuilder.ts index 5228cbeb9b..f540ed6679 100644 --- a/src/core/crypto/MerkleHashBuilder.ts +++ b/src/core/crypto/MerkleHashBuilder.ts @@ -16,7 +16,6 @@ import { SHA3Hasher } from './SHA3Hasher'; export class MerkleHashBuilder { - /** * The list of hashes used to calculate root hash. * @@ -28,13 +27,14 @@ export class MerkleHashBuilder { * Constructor * @param length Hash size */ - constructor(/** - * Length of produced merkle hash in bytes. - * - * @var {number} - */ - public readonly length: number) { - } + constructor( + /** + * Length of produced merkle hash in bytes. + * + * @var {number} + */ + public readonly length: number, + ) {} /** * Hash inner transactions @@ -64,7 +64,6 @@ export class MerkleHashBuilder { * @return {Uint8Array} */ protected calculateRootHash(hashes: Uint8Array[]): Uint8Array { - if (hashes.length === 0) { return new Uint8Array(this.length); } diff --git a/src/core/crypto/SHA3Hasher.ts b/src/core/crypto/SHA3Hasher.ts index 28ecc06847..3884abc35b 100644 --- a/src/core/crypto/SHA3Hasher.ts +++ b/src/core/crypto/SHA3Hasher.ts @@ -22,26 +22,26 @@ export class SHA3Hasher { * Calculates the hash of data. * @param {Uint8Array} dest The computed hash destination. * @param {Uint8Array} data The data to hash. - * @param {numeric} length The hash length in bytes. + * @param {number} length The hash length in bytes. */ - public static func = (dest, data, length) => { + public static func = (dest: Uint8Array, data: Uint8Array, length: number): void => { const hasher = SHA3Hasher.getHasher(length); const hash = hasher.arrayBuffer(data); array.copy(dest, array.uint8View(hash)); - } + }; /** * Creates a hasher object. - * @param {numeric} length The hash length in bytes. + * @param {number} length The hash length in bytes. * @returns {object} The hasher. */ - public static createHasher = (length = 64) => { + public static createHasher = (length = 64): any => { let hash; return { - reset: () => { + reset: (): void => { hash = SHA3Hasher.getHasher(length).create(); }, - update: (data: any) => { + update: (data: any): void => { if (data instanceof Uint8Array) { hash.update(data); } else if ('string' === typeof data) { @@ -50,21 +50,21 @@ export class SHA3Hasher { throw Error('unsupported data type'); } }, - finalize: (result: any) => { + finalize: (result: any): void => { array.copy(result, array.uint8View(hash.arrayBuffer())); }, }; - } + }; /** * Get a hasher instance. * @param {numeric} length The hash length in bytes. * @returns {object} The hasher. */ - public static getHasher = (length = 64) => { + public static getHasher = (length = 64): any => { return { 32: sha3_256, 64: sha3_512, - } [length]; - } + }[length]; + }; } diff --git a/src/core/crypto/Utilities.ts b/src/core/crypto/Utilities.ts index 56f9ca6ff2..2064259d14 100644 --- a/src/core/crypto/Utilities.ts +++ b/src/core/crypto/Utilities.ts @@ -16,16 +16,17 @@ import { RawArray as array } from '../format'; import * as nacl from './nacl_catapult'; -// tslint:disable-next-line: no-var-requires +// eslint-disable-next-line @typescript-eslint/no-var-requires export const CryptoJS = require('crypto-js'); export const Key_Size = 32; export const Signature_Size = 64; export const Half_Signature_Size = Signature_Size / 2; export const Hash_Size = 64; export const Half_Hash_Size = Hash_Size / 2; -// tslint:disable-next-line: no-var-requires +// eslint-disable-next-line @typescript-eslint/no-var-requires export const hkdf = require('futoin-hkdf'); import { sha512 } from 'js-sha512'; +import { WordArray } from 'crypto-js'; /** * Convert an Uint8Array to WordArray @@ -35,11 +36,11 @@ import { sha512 } from 'js-sha512'; * * @return {WordArray} */ -export const ua2words = (ua, uaLength) => { +export const ua2words = (ua, uaLength): WordArray => { const temp: number[] = []; for (let i = 0; i < uaLength; i += 4) { const x = ua[i] * 0x1000000 + (ua[i + 1] || 0) * 0x10000 + (ua[i + 2] || 0) * 0x100 + (ua[i + 3] || 0); - temp.push((x > 0x7fffffff) ? x - 0x100000000 : x); + temp.push(x > 0x7fffffff ? x - 0x100000000 : x); } return CryptoJS.lib.WordArray.create(temp, uaLength); }; @@ -52,11 +53,13 @@ export const ua2words = (ua, uaLength) => { * * @return {Uint8Array} */ -export const words2ua = (destUa, cryptoWords) => { +export const words2ua = (destUa, cryptoWords): Uint8Array => { for (let i = 0; i < destUa.length; i += 4) { let v = cryptoWords.words[i / 4]; - if (v < 0) { v += 0x100000000; } - destUa[i] = (v >>> 24); + if (v < 0) { + v += 0x100000000; + } + destUa[i] = v >>> 24; destUa[i + 1] = (v >>> 16) & 0xff; destUa[i + 2] = (v >>> 8) & 0xff; destUa[i + 3] = v & 0xff; @@ -65,14 +68,14 @@ export const words2ua = (destUa, cryptoWords) => { }; // custom catapult crypto functions -export const catapult_crypto = (() => { - function clamp(d) { +export const catapult_crypto = ((): any => { + function clamp(d): void { d[0] &= 248; d[31] &= 127; d[31] |= 64; } - function prepareForScalarMult(sk) { + function prepareForScalarMult(sk): Uint8Array { const d = new Uint8Array(64); const hash = sha512.arrayBuffer(sk); array.copy(d, array.uint8View(hash), 32); @@ -85,7 +88,7 @@ export const catapult_crypto = (() => { const sharedSecret = catapult_crypto.deriveSharedSecret(privateKey, publicKey); const info = 'catapult'; const hash = 'SHA-256'; - return hkdf(sharedSecret, 32, {salt: new Uint8Array(32), info, hash}); + return hkdf(sharedSecret, 32, { salt: new Uint8Array(32), info, hash }); }, deriveSharedSecret: (privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array => { diff --git a/src/core/crypto/index.ts b/src/core/crypto/index.ts index ff2288b1e3..6ffaea0a02 100644 --- a/src/core/crypto/index.ts +++ b/src/core/crypto/index.ts @@ -1,6 +1,5 @@ /* -import { SHA3Hasher } from './SHA3Hasher'; - * Copyright 2019 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/core/crypto/nacl_catapult.ts b/src/core/crypto/nacl_catapult.ts index 30022073c6..dd4ee08581 100644 --- a/src/core/crypto/nacl_catapult.ts +++ b/src/core/crypto/nacl_catapult.ts @@ -22,12 +22,12 @@ // Implementation derived from TweetNaCl version 20140427. // See for details: http://tweetnacl.cr.yp.to/ +/* eslint-disable */ const _0 = new Uint8Array(16); const _9 = new Uint8Array(32); _9[0] = 9; -export const gf = (init ? ) => { - // tslint:disable-next-line:one-variable-per-declaration +export const gf = (init?) => { let i; const r = new Float64Array(16); if (init) { @@ -38,27 +38,132 @@ export const gf = (init ? ) => { return r; }; -// tslint:disable-next-line:one-variable-per-declaration const gf0 = gf(), gf1 = gf([1]), _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, - 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203, + D = gf([ + 0x78a3, + 0x1359, + 0x4dca, + 0x75eb, + 0xd8ab, + 0x4141, + 0x0a4d, + 0x0070, + 0xe898, + 0x7779, + 0x4079, + 0x8cc7, + 0xfe73, + 0x2b6f, + 0x6cee, + 0x5203, ]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, - 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406, + D2 = gf([ + 0xf159, + 0x26b2, + 0x9b94, + 0xebd6, + 0xb156, + 0x8283, + 0x149a, + 0x00e0, + 0xd130, + 0xeef3, + 0x80f2, + 0x198e, + 0xfce7, + 0x56df, + 0xd9dc, + 0x2406, ]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, - 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169, + X = gf([ + 0xd51a, + 0x8f25, + 0x2d60, + 0xc956, + 0xa7b2, + 0x9525, + 0xc760, + 0x692c, + 0xdc5c, + 0xfdd6, + 0xe231, + 0xc0a4, + 0x53fe, + 0xcd6e, + 0x36d3, + 0x2169, ]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, - 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, + Y = gf([ + 0x6658, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, ]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, - 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83, + I = gf([ + 0xa0b0, + 0x4a0e, + 0x1b27, + 0xc4ee, + 0xe478, + 0xad2f, + 0x1806, + 0x2f43, + 0xd7a7, + 0x3dfb, + 0x0099, + 0x2b4d, + 0xdf0b, + 0x4fc1, + 0x2480, + 0x2b83, ]); -const L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, - 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10, +const L = new Float64Array([ + 0xed, + 0xd3, + 0xf5, + 0x5c, + 0x1a, + 0x63, + 0x12, + 0x58, + 0xd6, + 0x9c, + 0xf7, + 0xa2, + 0xde, + 0xf9, + 0xde, + 0x14, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0x10, ]); const A = (o, a, b) => { @@ -74,8 +179,8 @@ const Z = (o, a, b) => { }; const M = (o, a, b) => { - // tslint:disable-next-line:one-variable-per-declaration - let v, c, + let v, + c, t0 = 0, t1 = 0, t2 = 0, @@ -106,9 +211,8 @@ const M = (o, a, b) => { t27 = 0, t28 = 0, t29 = 0, - t30 = 0, - // tslint:disable: prefer-const - b0 = b[0], + t30 = 0; + const b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], @@ -541,8 +645,8 @@ const S = (o, a) => { M(o, a, a); }; const vn = (x, xi, y, yi, n) => { - // tslint:disable-next-line:one-variable-per-declaration - let i, d = 0; + let i, + d = 0; for (i = 0; i < n; i++) { d |= x[xi + i] ^ y[yi + i]; } @@ -589,8 +693,9 @@ const set25519 = (r, a) => { }; const car25519 = (o) => { - // tslint:disable-next-line:one-variable-per-declaration - let i, v, c = 1; + let i, + v, + c = 1; for (i = 0; i < 16; i++) { v = o[i] + c + 65535; c = Math.floor(v / 65536); @@ -600,8 +705,9 @@ const car25519 = (o) => { }; const sel25519 = (p, q, b) => { - // tslint:disable-next-line:one-variable-per-declaration - let t, c = ~(b - 1); + let t, + // eslint-disable-next-line prefer-const + c = ~(b - 1); for (let i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); p[i] ^= t; @@ -610,9 +716,7 @@ const sel25519 = (p, q, b) => { }; const pack25519 = (o, n) => { - // tslint:disable-next-line:one-variable-per-declaration let i, j, b; - // tslint:disable-next-line:one-variable-per-declaration const m = gf(), t = gf(); for (i = 0; i < 16; i++) { @@ -646,12 +750,10 @@ const cswap = (p, q, b) => { }; const neq25519 = (a, b) => { - // tslint:disable-next-line:one-variable-per-declaration const c = new Uint8Array(32), d = new Uint8Array(32); pack25519(c, a); pack25519(d, b); - // tslint:disable-next-line: no-use-before-declare return crypto_verify_32(c, 0, d, 0); }; @@ -674,7 +776,6 @@ export const crypto_verify_32 = (x, xi, y, yi) => { }; export const add = (p, q) => { - // tslint:disable-next-line:one-variable-per-declaration const a = gf(), b = gf(), c = gf(), @@ -707,7 +808,6 @@ export const add = (p, q) => { }; export const pack = (r, p) => { - // tslint:disable-next-line:one-variable-per-declaration const tx = gf(), ty = gf(), zi = gf(); @@ -719,7 +819,6 @@ export const pack = (r, p) => { }; export const scalarmult = (p, q, s) => { - // tslint:disable-next-line:one-variable-per-declaration let b, i; set25519(p[0], gf0); set25519(p[1], gf1); @@ -735,7 +834,6 @@ export const scalarmult = (p, q, s) => { }; export const unpack = (r, p) => { - // tslint:disable-next-line:one-variable-per-declaration const t = gf(), chk = gf(), num = gf(), @@ -779,7 +877,7 @@ export const unpack = (r, p) => { return -1; } - if (par25519(r[0]) !== (p[31] >> 7)) { + if (par25519(r[0]) !== p[31] >> 7) { Z(r[0], gf0, r[0]); } diff --git a/src/core/format/Base32.ts b/src/core/format/Base32.ts index ac5314f457..d9cd0fd6e4 100644 --- a/src/core/format/Base32.ts +++ b/src/core/format/Base32.ts @@ -26,12 +26,12 @@ export class Base32 { if (0 !== data.length % utilities.Decoded_Block_Size) { throw Error(`decoded size must be multiple of ${utilities.Decoded_Block_Size}`); } - const output = new Array(data.length / utilities.Decoded_Block_Size * utilities.Encoded_Block_Size); + const output = new Array((data.length / utilities.Decoded_Block_Size) * utilities.Encoded_Block_Size); for (let i = 0; i < data.length / utilities.Decoded_Block_Size; ++i) { utilities.encodeBlock(data, i * utilities.Decoded_Block_Size, output, i * utilities.Encoded_Block_Size); } return output.join(''); - } + }; /** * Base32 decodes a base32 encoded string. @@ -43,10 +43,10 @@ export class Base32 { throw Error(`encoded size must be multiple of ${utilities.Encoded_Block_Size}`); } - const output = new Uint8Array(encoded.length / utilities.Encoded_Block_Size * utilities.Decoded_Block_Size); + const output = new Uint8Array((encoded.length / utilities.Encoded_Block_Size) * utilities.Decoded_Block_Size); for (let i = 0; i < encoded.length / utilities.Encoded_Block_Size; ++i) { utilities.decodeBlock(encoded, i * utilities.Encoded_Block_Size, output, i * utilities.Decoded_Block_Size); } return output; - } + }; } diff --git a/src/core/format/Convert.ts b/src/core/format/Convert.ts index 4c16dc0489..a2f3054cc7 100644 --- a/src/core/format/Convert.ts +++ b/src/core/format/Convert.ts @@ -17,7 +17,6 @@ import { decode } from 'utf8'; import * as utilities from './Utilities'; export class Convert { - /** * Decodes two hex characters into a byte. * @param {string} char1 The first hex digit. @@ -30,7 +29,7 @@ export class Convert { throw Error(`unrecognized hex char`); } return byte; - } + }; /** * Determines whether or not a string is a hex string. @@ -47,7 +46,7 @@ export class Convert { } } return true; - } + }; /** * Converts a hex string to a uint8 array. @@ -63,7 +62,7 @@ export class Convert { output[i / 2] = Convert.toByte(input[i], input[i + 1]); } return output; - } + }; /** * Reversed convertion hex string to a uint8 array. @@ -76,10 +75,10 @@ export class Convert { } const output = new Uint8Array(input.length / 2); for (let i = 0; i < input.length; i += 2) { - output[output.length - 1 - (i / 2)] = Convert.toByte(input[i], input[i + 1]); + output[output.length - 1 - i / 2] = Convert.toByte(input[i], input[i + 1]); } return output; - } + }; /** * Converts a uint8 array to a hex string. @@ -90,18 +89,18 @@ export class Convert { let s = ''; for (const byte of input) { s += utilities.Nibble_To_Char_Map[byte >> 4]; - s += utilities.Nibble_To_Char_Map[byte & 0x0F]; + s += utilities.Nibble_To_Char_Map[byte & 0x0f]; } return s; - } + }; /** * Converts a uint8 array to a uint32 array. * @param {Uint8Array} input A uint8 array. * @returns {Uint32Array} A uint32 array created from the input. */ - public static uint8ToUint32 = (input) => new Uint32Array(input.buffer); + public static uint8ToUint32 = (input): Uint32Array => new Uint32Array(input.buffer); /** * Converts a uint32 array to a uint8 array. @@ -116,11 +115,11 @@ export class Convert { * */ public static uint8ToInt8 = (input: number): number => { - if (0xFF < input) { + if (0xff < input) { throw Error(`input '${input}' is out of range`); } - return input << 24 >> 24; - } + return (input << 24) >> 24; + }; /** Converts a signed byte to an unsigned byte with the same binary representation. * @param {number} input A signed byte. @@ -130,8 +129,8 @@ export class Convert { if (127 < input || -128 > input) { throw Error(`input '${input}' is out of range`); } - return input & 0xFF; - } + return input & 0xff; + }; /** * Converts a raw javascript string into a string of single byte characters using utf8 encoding. @@ -147,7 +146,7 @@ export class Convert { if (128 > c) { output += String.fromCharCode(c); - } else if ((127 < c) && (2048 > c)) { + } else if (127 < c && 2048 > c) { output += String.fromCharCode((c >> 6) | 192); output += String.fromCharCode((c & 63) | 128); } else { @@ -158,7 +157,7 @@ export class Convert { } return output; - } + }; /** * Convert UTF-8 to hex @@ -172,7 +171,7 @@ export class Convert { result += rawString.charCodeAt(i).toString(16).padStart(2, '0'); } return result.toUpperCase(); - } + }; /** * Convert UTF-8 string to Uint8Array @@ -182,7 +181,7 @@ export class Convert { public static utf8ToUint8 = (input: string): Uint8Array => { const hex = Convert.utf8ToHex(Convert.rstr2utf8(input)); return Convert.hexToUint8(hex); - } + }; /** * Convert Uint8Array to string with UTF-8 encoding @@ -193,7 +192,7 @@ export class Convert { // return new TextDecoder().decode(input); const hex = Convert.uint8ToHex(input); return Convert.decodeHex(hex); - } + }; /** * decode hex to uft8 string @@ -210,7 +209,7 @@ export class Convert { } catch (e) { return str; } - } + }; /** * Generate xor for two byte arrays and return in hex string @@ -239,7 +238,7 @@ export class Convert { const uint8Array = new Uint8Array(arraySize); for (let index = 0; index < uint8Array.length; index++) { const byte = number & 0xff; - uint8Array [index] = byte; + uint8Array[index] = byte; number = (number - byte) / 256; } return uint8Array; diff --git a/src/core/format/IdGenerator.ts b/src/core/format/IdGenerator.ts index 957a6eceaf..f0052d95a6 100644 --- a/src/core/format/IdGenerator.ts +++ b/src/core/format/IdGenerator.ts @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {sha3_256} from 'js-sha3'; +import { sha3_256 } from 'js-sha3'; import * as utilities from './Utilities'; -import { idGeneratorConst } from './Utilities'; export class IdGenerator { /** @@ -24,20 +23,20 @@ export class IdGenerator { * @param {object} ownerPublicId The public id. * @returns {module:coders/uint64~uint64} The mosaic id. */ - public static generateMosaicId = (nonce, ownerPublicId) => { + public static generateMosaicId = (nonce: any, ownerPublicId: any): number[] => { const hash = sha3_256.create(); hash.update(nonce); hash.update(ownerPublicId); const result = new Uint32Array(hash.arrayBuffer()); - return [result[0], result[1] & 0x7FFFFFFF]; - } + return [result[0], result[1] & 0x7fffffff]; + }; /** * Parses a unified namespace name into a path. * @param {string} name The unified namespace name. * @returns {array} The namespace path. */ - public static generateNamespacePath = (name: string) => { + public static generateNamespacePath = (name: string): number[] => { if (0 >= name.length) { utilities.throwInvalidFqn('having zero length', name); } @@ -45,10 +44,10 @@ export class IdGenerator { const path = []; const start = utilities.split(name, (substringStart, size) => { namespaceId = utilities.generateNamespaceId(namespaceId, utilities.extractPartName(name, substringStart, size)); - utilities.append(path, namespaceId, name); + utilities.append(path, namespaceId); }); namespaceId = utilities.generateNamespaceId(namespaceId, utilities.extractPartName(name, start, name.length - start)); - utilities.append(path, namespaceId, name); + utilities.append(path, namespaceId); return path; - } + }; } diff --git a/src/core/format/RawAddress.ts b/src/core/format/RawAddress.ts index d1245a2626..fc5fc6f524 100644 --- a/src/core/format/RawAddress.ts +++ b/src/core/format/RawAddress.ts @@ -42,7 +42,7 @@ export class RawAddress { } return Base32.Base32Decode(encoded); - } + }; /** * Format a namespaceId *alias* into a valid recipient field value. @@ -57,7 +57,7 @@ export class RawAddress { padded.set(namespaceId.reverse(), 1); padded.set(Convert.hexToUint8('00'.repeat(16)), 9); return padded; - } + }; /** * Converts a decoded address to an encoded address string. @@ -69,7 +69,7 @@ export class RawAddress { throw Error(`${Convert.uint8ToHex(decoded)} does not represent a valid decoded address`); } return Base32.Base32Encode(decoded); - } + }; /** * Converts a public key to a decoded address for a specific network. @@ -77,8 +77,7 @@ export class RawAddress { * @param {NetworkType} networkType The network identifier. * @returns {Uint8Array} The decoded address corresponding to the inputs. */ - public static publicKeyToAddress = (publicKey: Uint8Array, - networkType: NetworkType): Uint8Array => { + public static publicKeyToAddress = (publicKey: Uint8Array, networkType: NetworkType): Uint8Array => { // step 1: sha3 hash of the public key const publicKeyHash = sha3_256.arrayBuffer(publicKey); @@ -93,19 +92,22 @@ export class RawAddress { // step 4: concatenate (3) and the checksum of (3) const hash = sha3_256.arrayBuffer(decodedAddress.subarray(0, RawAddress.constants.sizes.ripemd160 + 1)); - RawArray.copy(decodedAddress, RawArray.uint8View(hash), - RawAddress.constants.sizes.checksum, RawAddress.constants.sizes.ripemd160 + 1); + RawArray.copy( + decodedAddress, + RawArray.uint8View(hash), + RawAddress.constants.sizes.checksum, + RawAddress.constants.sizes.ripemd160 + 1, + ); return decodedAddress; - } + }; /** * Determines the validity of a decoded address. * @param {Uint8Array} decoded The decoded address. - * @param {NetworkType} networkType The network identifier. * @returns {boolean} true if the decoded address is valid, false otherwise. */ - public static isValidAddress = (decoded: Uint8Array, networkType: NetworkType): boolean => { + public static isValidAddress = (decoded: Uint8Array): boolean => { if (RawAddress.constants.sizes.addressDecoded !== decoded.length) { return false; } @@ -115,5 +117,5 @@ export class RawAddress { const checksum = new Uint8Array(RawAddress.constants.sizes.checksum); RawArray.copy(checksum, RawArray.uint8View(hash.arrayBuffer()), RawAddress.constants.sizes.checksum); return RawArray.deepEqual(checksum, decoded.subarray(checksumBegin)); - } + }; } diff --git a/src/core/format/RawArray.ts b/src/core/format/RawArray.ts index f1c16d641b..2f29ec8e29 100644 --- a/src/core/format/RawArray.ts +++ b/src/core/format/RawArray.ts @@ -20,7 +20,7 @@ export class RawArray { * @param {ArrayBuffer|Uint8Array} input The input array. * @returns {Uint8Array} A Uint8Array view on top of input. */ - public static uint8View = (input) => { + public static uint8View = (input): Uint8Array => { if (ArrayBuffer === input.constructor) { return new Uint8Array(input); } else if (Uint8Array === input.constructor) { @@ -28,7 +28,7 @@ export class RawArray { } throw Error('unsupported type passed to uint8View'); - } + }; /** * Copies elements from a source array to a destination array. @@ -38,19 +38,19 @@ export class RawArray { * @param {number} [destOffset=0] The first index of the destination to write. * @param {number} [srcOffset=0] The first index of the source to read. */ - public static copy = (dest, src, numElementsToCopy?, destOffset = 0, srcOffset = 0) => { + public static copy = (dest, src, numElementsToCopy?, destOffset = 0, srcOffset = 0): any => { const length = undefined === numElementsToCopy ? dest.length : numElementsToCopy; for (let i = 0; i < length; ++i) { dest[destOffset + i] = src[srcOffset + i]; } - } + }; /** * Determines whether or not an array is zero-filled. * @param {Array} array The array to check. * @returns {boolean} true if the array is zero-filled, false otherwise. */ - public static isZeroFilled = (array) => array.every((value) => 0 === value); + public static isZeroFilled = (array): boolean => array.every((value) => 0 === value); /** * Deeply checks the equality of two arrays. @@ -59,7 +59,7 @@ export class RawArray { * @param {number} [numElementsToCompare=undefined] The number of elements to compare. * @returns {boolean} true if all compared elements are equal, false otherwise. */ - public static deepEqual = (lhs, rhs, numElementsToCompare?) => { + public static deepEqual = (lhs, rhs, numElementsToCompare?): boolean => { let length = numElementsToCompare; if (undefined === length) { if (lhs.length !== rhs.length) { @@ -80,5 +80,5 @@ export class RawArray { } return true; - } + }; } diff --git a/src/core/format/RawUInt64.ts b/src/core/format/RawUInt64.ts index 81eaf3bf1e..dcc1487e52 100644 --- a/src/core/format/RawUInt64.ts +++ b/src/core/format/RawUInt64.ts @@ -17,7 +17,7 @@ import { Convert } from './Convert'; export class RawUInt64 { - static readonly readUint32At = (bytes, i) => (bytes[i] + (bytes[i + 1] << 8) + (bytes[i + 2] << 16) + (bytes[i + 3] << 24)) >>> 0; + static readonly readUint32At = (bytes, i): any => (bytes[i] + (bytes[i + 1] << 8) + (bytes[i + 2] << 16) + (bytes[i + 3] << 24)) >>> 0; /** * An exact uint64 representation composed of two 32bit values. @@ -31,7 +31,7 @@ export class RawUInt64 { * @returns {number|module:coders/uint64~uint64} * A numeric if the uint64 is no greater than Number.MAX_SAFE_INTEGER or the original uint64 value otherwise. */ - public static compact = (uint64) => { + public static compact = (uint64: number[]): number | number[] => { const low = uint64[0]; const high = uint64[1]; @@ -41,49 +41,49 @@ export class RawUInt64 { } // multiply because javascript bit operations operate on 32bit values - return (high * 0x100000000) + low; - } + return high * 0x100000000 + low; + }; /** * Converts a numeric unsigned integer into a uint64. * @param {number} number The unsigned integer. * @returns {module:coders/uint64~uint64} The uint64 representation of the input. */ - public static fromUint = (number) => { - const value = [(number & 0xFFFFFFFF) >>> 0, (number / 0x100000000) >>> 0]; + public static fromUint = (number): number[] => { + const value = [(number & 0xffffffff) >>> 0, (number / 0x100000000) >>> 0]; return value; - } + }; /** * Converts a (64bit) uint8 array into a uint64. * @param {Uint8Array} uint8Array A uint8 array. * @returns {module:coders/uint64~uint64} The uint64 representation of the input. */ - public static fromBytes = (uint8Array) => { + public static fromBytes = (uint8Array): number[] => { if (8 !== uint8Array.length) { throw Error(`byte array has unexpected size '${uint8Array.length}'`); } return [RawUInt64.readUint32At(uint8Array, 0), RawUInt64.readUint32At(uint8Array, 4)]; - } + }; /** * Converts a (32bit) uint8 array into a uint64. * @param {Uint8Array} uint8Array A uint8 array. * @returns {module:coders/uint64~uint64} The uint64 representation of the input. */ - public static fromBytes32 = (uint8Array) => { + public static fromBytes32 = (uint8Array): number[] => { if (4 !== uint8Array.length) { throw Error(`byte array has unexpected size '${uint8Array.length}'`); } return [RawUInt64.readUint32At(uint8Array, 0), 0]; - } + }; /** * Parses a hex string into a uint64. * @param {string} input A hex encoded string. * @returns {module:coders/uint64~uint64} The uint64 representation of the input. */ - public static fromHex = (input) => { + public static fromHex = (input): number[] => { if (16 !== input.length) { throw Error(`hex string has unexpected size '${input.length}'`); } @@ -94,23 +94,23 @@ export class RawUInt64 { const uint8Array = Convert.hexToUint8(hexString); const view = new DataView(uint8Array.buffer); return [view.getUint32(4), view.getUint32(0)]; - } + }; /** * Converts a uint64 into a hex string. * @param {module:coders/uint64~uint64} uint64 A uint64 value. * @returns {string} A hex encoded string representing the uint64. */ - public static toHex = (uint64) => { + public static toHex = (uint64): string => { const uint32Array = new Uint32Array(uint64); const uint8Array = Convert.uint32ToUint8(uint32Array).reverse(); return Convert.uint8ToHex(uint8Array); - } + }; /** * Returns true if a uint64 is zero. * @param {module:coders/uint64~uint64} uint64 A uint64 value. * @returns {boolean} true if the value is zero. */ - public static isZero = (uint64) => 0 === uint64[0] && 0 === uint64[1]; + public static isZero = (uint64): boolean => 0 === uint64[0] && 0 === uint64[1]; } diff --git a/src/core/format/Utilities.ts b/src/core/format/Utilities.ts index 4c52f72e25..9dc0dbb02a 100644 --- a/src/core/format/Utilities.ts +++ b/src/core/format/Utilities.ts @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {sha3_256} from 'js-sha3'; +import { sha3_256 } from 'js-sha3'; -export const createBuilder = () => { +export const createBuilder = (): any => { const map = {}; return { map, @@ -27,7 +27,7 @@ export const createBuilder = () => { * @memberof module:utils/charMapping~CharacterMapBuilder * @instance */ - addRange: (start, end, base) => { + addRange: (start: string, end: string, base: number): void => { const startCode = start.charCodeAt(0); const endCode = end.charCodeAt(0); @@ -38,7 +38,7 @@ export const createBuilder = () => { }; }; -const Char_To_Nibble_Map = () => { +const Char_To_Nibble_Map = (): any => { const builder = createBuilder(); builder.addRange('0', '9', 0); builder.addRange('a', 'f', 10); @@ -46,7 +46,7 @@ const Char_To_Nibble_Map = () => { return builder.map; }; -const Char_To_Digit_Map = () => { +const Char_To_Digit_Map = (): any => { const builder = createBuilder(); builder.addRange('0', '9', 0); return builder.map; @@ -54,23 +54,21 @@ const Char_To_Digit_Map = () => { export const Nibble_To_Char_Map = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']; export const Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; -export const Decoded_Block_Size = 5; +export const Decoded_Block_Size = 5; export const Encoded_Block_Size = 8; -export const tryParseByte = (char1, char2) => { +export const tryParseByte = (char1, char2): any => { const charMap = Char_To_Nibble_Map(); const nibble1 = charMap[char1]; const nibble2 = charMap[char2]; - return undefined === nibble1 || undefined === nibble2 ? - undefined : - (nibble1 << 4) | nibble2; + return undefined === nibble1 || undefined === nibble2 ? undefined : (nibble1 << 4) | nibble2; }; /** * Tries to parse a string representing an unsigned integer. * @param {string} str The string to parse. - * @returns {number} The number represented by the input or undefined. + * @returns { number | undefined} The number represented by the input or undefined. */ -export const tryParseUint = (str) => { +export const tryParseUint = (str: string): number | undefined => { if ('0' === str) { return 0; } @@ -97,11 +95,11 @@ export const idGeneratorConst = { name_pattern: /^[a-z0-9][a-z0-9-_]*$/, }; -export const throwInvalidFqn = (reason, name) => { +export const throwInvalidFqn = (reason: any, name: any): void => { throw Error(`fully qualified id is invalid due to ${reason} (${name})`); }; -export const extractPartName = (name, start, size) => { +export const extractPartName = (name: string, start: number, size: number): string => { if (0 === size) { this.throwInvalidFqn('empty part', name); } @@ -112,11 +110,11 @@ export const extractPartName = (name, start, size) => { return partName; }; -export const append = (path, id, name) => { +export const append = (path: any, id: any): any => { path.push(id); }; -export const split = (name, processor) => { +export const split = (name: string, processor: any): any => { let start = 0; for (let index = 0; index < name.length; ++index) { if ('.' === name[index]) { @@ -127,7 +125,7 @@ export const split = (name, processor) => { return start; }; -export const generateNamespaceId = (parentId, name) => { +export const generateNamespaceId = (parentId: number[], name: string): number[] => { const hash = sha3_256.create(); hash.update(Uint32Array.from(parentId).buffer as any); hash.update(name); @@ -136,25 +134,25 @@ export const generateNamespaceId = (parentId, name) => { return [result[0], (result[1] | 0x80000000) >>> 0]; }; -export const encodeBlock = (input, inputOffset, output, outputOffset) => { +export const encodeBlock = (input: any, inputOffset: number, output: any, outputOffset: number): any => { output[outputOffset + 0] = Alphabet[input[inputOffset + 0] >> 3]; output[outputOffset + 1] = Alphabet[((input[inputOffset + 0] & 0x07) << 2) | (input[inputOffset + 1] >> 6)]; - output[outputOffset + 2] = Alphabet[(input[inputOffset + 1] & 0x3E) >> 1]; + output[outputOffset + 2] = Alphabet[(input[inputOffset + 1] & 0x3e) >> 1]; output[outputOffset + 3] = Alphabet[((input[inputOffset + 1] & 0x01) << 4) | (input[inputOffset + 2] >> 4)]; - output[outputOffset + 4] = Alphabet[((input[inputOffset + 2] & 0x0F) << 1) | (input[inputOffset + 3] >> 7)]; - output[outputOffset + 5] = Alphabet[(input[inputOffset + 3] & 0x7F) >> 2]; + output[outputOffset + 4] = Alphabet[((input[inputOffset + 2] & 0x0f) << 1) | (input[inputOffset + 3] >> 7)]; + output[outputOffset + 5] = Alphabet[(input[inputOffset + 3] & 0x7f) >> 2]; output[outputOffset + 6] = Alphabet[((input[inputOffset + 3] & 0x03) << 3) | (input[inputOffset + 4] >> 5)]; - output[outputOffset + 7] = Alphabet[input[inputOffset + 4] & 0x1F]; + output[outputOffset + 7] = Alphabet[input[inputOffset + 4] & 0x1f]; }; -export const Char_To_Decoded_Char_Map = () => { +export const Char_To_Decoded_Char_Map = (): any => { const builder = createBuilder(); builder.addRange('A', 'Z', 0); builder.addRange('2', '7', 26); return builder.map; }; -export const decodeChar = (c) => { +export const decodeChar = (c: any): any => { const charMap = Char_To_Decoded_Char_Map(); const decodedChar = charMap[c]; if (undefined !== decodedChar) { @@ -163,7 +161,7 @@ export const decodeChar = (c) => { throw Error(`illegal base32 character ${c}`); }; -export const decodeBlock = (input, inputOffset, output, outputOffset) => { +export const decodeBlock = (input: any, inputOffset: number, output: any, outputOffset: number): any => { const bytes = new Uint8Array(Encoded_Block_Size); for (let i = 0; i < Encoded_Block_Size; ++i) { bytes[i] = decodeChar(input[inputOffset + i]); @@ -171,7 +169,7 @@ export const decodeBlock = (input, inputOffset, output, outputOffset) => { output[outputOffset + 0] = (bytes[0] << 3) | (bytes[1] >> 2); output[outputOffset + 1] = ((bytes[1] & 0x03) << 6) | (bytes[2] << 1) | (bytes[3] >> 4); - output[outputOffset + 2] = ((bytes[3] & 0x0F) << 4) | (bytes[4] >> 1); + output[outputOffset + 2] = ((bytes[3] & 0x0f) << 4) | (bytes[4] >> 1); output[outputOffset + 3] = ((bytes[4] & 0x01) << 7) | (bytes[5] << 2) | (bytes[6] >> 3); output[outputOffset + 4] = ((bytes[6] & 0x07) << 5) | bytes[7]; }; diff --git a/src/core/utils/DtoMapping.ts b/src/core/utils/DtoMapping.ts index 6c62abc026..389f64d00f 100644 --- a/src/core/utils/DtoMapping.ts +++ b/src/core/utils/DtoMapping.ts @@ -22,7 +22,6 @@ import { AccountRestrictionsInfo } from '../../model/restriction/AccountRestrict import { AccountRestrictionFlags } from '../../model/restriction/AccountRestrictionType'; export class DtoMapping { - /** * Create AccountRestrictionsInfo class from Json. * @param {object} dataJson The account restriction json object. @@ -31,28 +30,35 @@ export class DtoMapping { public static extractAccountRestrictionFromDto(accountRestrictions): AccountRestrictionsInfo { return new AccountRestrictionsInfo( accountRestrictions.meta, - new AccountRestrictions(Address.createFromEncoded(accountRestrictions.accountRestrictions.address), + new AccountRestrictions( + Address.createFromEncoded(accountRestrictions.accountRestrictions.address), accountRestrictions.accountRestrictions.restrictions.map((prop) => { - switch (prop.restrictionFlags) { - case AccountRestrictionFlags.AllowIncomingAddress: - case AccountRestrictionFlags.BlockIncomingAddress: - case AccountRestrictionFlags.AllowOutgoingAddress: - case AccountRestrictionFlags.BlockOutgoingAddress: - return new AccountRestriction(prop.restrictionFlags, - prop.values.map((value) => Address.createFromEncoded(value))); - case AccountRestrictionFlags.AllowMosaic: - case AccountRestrictionFlags.BlockMosaic: - return new AccountRestriction(prop.restrictionFlags, - prop.values.map((value) => new MosaicId(value))); - case AccountRestrictionFlags.AllowIncomingTransactionType: - case AccountRestrictionFlags.AllowOutgoingTransactionType: - case AccountRestrictionFlags.BlockIncomingTransactionType: - case AccountRestrictionFlags.BlockOutgoingTransactionType: - return new AccountRestriction(prop.restrictionFlags, prop.values); - default: - throw new Error(`Invalid restriction type: ${prop.restrictionFlags}`); - } - }))); + switch (prop.restrictionFlags) { + case AccountRestrictionFlags.AllowIncomingAddress: + case AccountRestrictionFlags.BlockIncomingAddress: + case AccountRestrictionFlags.AllowOutgoingAddress: + case AccountRestrictionFlags.BlockOutgoingAddress: + return new AccountRestriction( + prop.restrictionFlags, + prop.values.map((value) => Address.createFromEncoded(value)), + ); + case AccountRestrictionFlags.AllowMosaic: + case AccountRestrictionFlags.BlockMosaic: + return new AccountRestriction( + prop.restrictionFlags, + prop.values.map((value) => new MosaicId(value)), + ); + case AccountRestrictionFlags.AllowIncomingTransactionType: + case AccountRestrictionFlags.AllowOutgoingTransactionType: + case AccountRestrictionFlags.BlockIncomingTransactionType: + case AccountRestrictionFlags.BlockOutgoingTransactionType: + return new AccountRestriction(prop.restrictionFlags, prop.values); + default: + throw new Error(`Invalid restriction type: ${prop.restrictionFlags}`); + } + }), + ), + ); } /** @@ -62,7 +68,6 @@ export class DtoMapping { * @returns a copy of the first object with the new attributes added. */ public static assign(object: T, attributes: any): T { - return Object.assign({__proto__: Object.getPrototypeOf(object)}, object, attributes); + return Object.assign({ __proto__: Object.getPrototypeOf(object) }, object, attributes); } - } diff --git a/src/core/utils/LockHashUtils.ts b/src/core/utils/LockHashUtils.ts new file mode 100644 index 0000000000..a107c8af47 --- /dev/null +++ b/src/core/utils/LockHashUtils.ts @@ -0,0 +1,73 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { sha3_256 } from 'js-sha3'; +import { LockHashAlgorithm } from '../../model/transaction/LockHashAlgorithm'; + +/** + * Hash utilities for SecretLock hashing + */ +export class LockHashUtils { + private static sha256 = require('js-sha256'); + private static ripemd160 = require('ripemd160'); + /** + * Perform SHA3_256 hash + * @param input buffer to be hashed + * @returns {string} Hash in hexidecimal format + */ + public static Op_Sha3_256(input: Uint8Array): string { + return sha3_256.create().update(input).hex().toUpperCase(); + } + + /** + * Perform SHA256 hash + * @param input buffer to be hashed + * @returns {string} Hash in hexidecimal format + */ + public static Op_Hash_256(input: Uint8Array): string { + const hash = LockHashUtils.sha256(input, 'hex'); + return LockHashUtils.sha256(Buffer.from(hash, 'hex')).toUpperCase(); + } + + /** + * Perform ripemd160 hash + * @param input buffer to be hashed + * @returns {string} Hash in hexidecimal format + */ + public static Op_Hash_160(input: Uint8Array): string { + const sha256Hash = LockHashUtils.sha256(input); + return new LockHashUtils.ripemd160().update(Buffer.from(sha256Hash, 'hex')).digest('hex').toUpperCase(); + } + + /** + * Perform hash for SecretLock with proficed hash algorithm + * @param hashAlgorithm Hash algorithm + * @param input buffer to be hashed + * @returns {string} Hash in hexidecimal format + */ + public static Hash(hashAlgorithm: LockHashAlgorithm, input: Uint8Array): string { + switch (hashAlgorithm) { + case LockHashAlgorithm.Op_Hash_160: + return LockHashUtils.Op_Hash_160(input); + case LockHashAlgorithm.Op_Hash_256: + return LockHashUtils.Op_Hash_256(input); + case LockHashAlgorithm.Op_Sha3_256: + return LockHashUtils.Op_Sha3_256(input); + default: + throw new Error('HashAlgorithm is invalid.'); + } + } +} diff --git a/src/core/utils/TransactionMapping.ts b/src/core/utils/TransactionMapping.ts index b579fd0cb6..d6ee61d2da 100644 --- a/src/core/utils/TransactionMapping.ts +++ b/src/core/utils/TransactionMapping.ts @@ -20,7 +20,6 @@ import { InnerTransaction } from '../../model/transaction/InnerTransaction'; import { Transaction } from '../../model/transaction/Transaction'; export class TransactionMapping { - /** * Create transaction class from Json. * @param {object} dataJson The transaction json object. @@ -36,8 +35,7 @@ export class TransactionMapping { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} The transaction class. */ - public static createFromPayload(payload: string, - isEmbedded = false): Transaction | InnerTransaction { + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { return CreateTransactionFromPayload(payload, isEmbedded); } } diff --git a/src/core/utils/UnresolvedMapping.ts b/src/core/utils/UnresolvedMapping.ts index f70f9d45c6..b1bc089a4a 100644 --- a/src/core/utils/UnresolvedMapping.ts +++ b/src/core/utils/UnresolvedMapping.ts @@ -24,7 +24,6 @@ import { RawAddress } from '../format/RawAddress'; * @internal */ export class UnresolvedMapping { - /** * @internal * Map unresolved mosaic string to MosaicId or NamespaceId diff --git a/src/core/utils/utility.ts b/src/core/utils/utility.ts index 71274052db..c6c1a30814 100644 --- a/src/core/utils/utility.ts +++ b/src/core/utils/utility.ts @@ -16,3 +16,4 @@ export * from './TransactionMapping'; export * from './DtoMapping'; +export * from './LockHashUtils'; diff --git a/src/infrastructure/AccountHttp.ts b/src/infrastructure/AccountHttp.ts index 514d91df72..ef9489aa80 100644 --- a/src/infrastructure/AccountHttp.ts +++ b/src/infrastructure/AccountHttp.ts @@ -88,21 +88,12 @@ export class AccountHttp extends Http implements AccountRepository { dto.account.accountType.valueOf(), dto.account.linkedAccountKey, dto.account.activityBuckets.map((bucket) => { - return new ActivityBucket( - bucket.startHeight, - bucket.totalFeesPaid, - bucket.beneficiaryCount, - bucket.rawScore, - ); + return new ActivityBucket(bucket.startHeight, bucket.totalFeesPaid, bucket.beneficiaryCount, bucket.rawScore); }), - dto.account.mosaics.map((mosaicDTO) => new Mosaic( - new MosaicId(mosaicDTO.id), - UInt64.fromNumericString(mosaicDTO.amount), - )), + dto.account.mosaics.map((mosaicDTO) => new Mosaic(new MosaicId(mosaicDTO.id), UInt64.fromNumericString(mosaicDTO.amount))), UInt64.fromNumericString(dto.account.importance), UInt64.fromNumericString(dto.account.importanceHeight), ); - } /** @@ -112,16 +103,21 @@ export class AccountHttp extends Http implements AccountRepository { * @param transactionFilter - (Optional) Transaction filter * @returns Observable */ - public getAccountTransactions(address: Address, - queryParams?: QueryParams, - transactionFilter?: TransactionFilter): Observable { - - return this.call(this.accountRoutesApi.getAccountConfirmedTransactions(address.plain(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering, - this.transactionFilter(transactionFilter).type), - (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO))); + public getAccountTransactions( + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable { + return this.call( + this.accountRoutesApi.getAccountConfirmedTransactions( + address.plain(), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering, + this.transactionFilter(transactionFilter).type, + ), + (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO)), + ); } /** @@ -132,15 +128,21 @@ export class AccountHttp extends Http implements AccountRepository { * @param transactionFilter - (Optional) Transaction filter * @returns Observable */ - public getAccountIncomingTransactions(address: Address, - queryParams?: QueryParams, - transactionFilter?: TransactionFilter): Observable { - return this.call(this.accountRoutesApi.getAccountIncomingTransactions(address.plain(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering, - this.transactionFilter(transactionFilter).type), - (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO))); + public getAccountIncomingTransactions( + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable { + return this.call( + this.accountRoutesApi.getAccountIncomingTransactions( + address.plain(), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering, + this.transactionFilter(transactionFilter).type, + ), + (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO)), + ); } /** @@ -151,15 +153,21 @@ export class AccountHttp extends Http implements AccountRepository { * @param transactionFilter - (Optional) Transaction filter * @returns Observable */ - public getAccountOutgoingTransactions(address: Address, - queryParams?: QueryParams, - transactionFilter?: TransactionFilter): Observable { - return this.call(this.accountRoutesApi.getAccountOutgoingTransactions(address.plain(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering, - this.transactionFilter(transactionFilter).type), - (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO))); + public getAccountOutgoingTransactions( + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable { + return this.call( + this.accountRoutesApi.getAccountOutgoingTransactions( + address.plain(), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering, + this.transactionFilter(transactionFilter).type, + ), + (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO)), + ); } /** @@ -171,15 +179,21 @@ export class AccountHttp extends Http implements AccountRepository { * @param transactionFilter - (Optional) Transaction filter * @returns Observable */ - public getAccountUnconfirmedTransactions(address: Address, - queryParams?: QueryParams, - transactionFilter?: TransactionFilter): Observable { - return this.call(this.accountRoutesApi.getAccountUnconfirmedTransactions(address.plain(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering, - this.transactionFilter(transactionFilter).type), - (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO))); + public getAccountUnconfirmedTransactions( + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable { + return this.call( + this.accountRoutesApi.getAccountUnconfirmedTransactions( + address.plain(), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering, + this.transactionFilter(transactionFilter).type, + ), + (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO)), + ); } /** @@ -190,14 +204,20 @@ export class AccountHttp extends Http implements AccountRepository { * @param transactionFilter - (Optional) Transaction filter * @returns Observable */ - public getAccountPartialTransactions(address: Address, - queryParams?: QueryParams, - transactionFilter?: TransactionFilter): Observable { - return this.call(this.accountRoutesApi.getAccountPartialTransactions(address.plain(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering, - this.transactionFilter(transactionFilter).type), - (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO) as AggregateTransaction)); + public getAccountPartialTransactions( + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable { + return this.call( + this.accountRoutesApi.getAccountPartialTransactions( + address.plain(), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering, + this.transactionFilter(transactionFilter).type, + ), + (body) => body.map((transactionDTO) => CreateTransactionFromDTO(transactionDTO) as AggregateTransaction), + ); } } diff --git a/src/infrastructure/AccountRepository.ts b/src/infrastructure/AccountRepository.ts index bf6c77ae3f..c00033c9d6 100644 --- a/src/infrastructure/AccountRepository.ts +++ b/src/infrastructure/AccountRepository.ts @@ -14,11 +14,11 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; -import {AccountInfo} from '../model/account/AccountInfo'; -import {Address} from '../model/account/Address'; -import {AggregateTransaction} from '../model/transaction/AggregateTransaction'; -import {Transaction} from '../model/transaction/Transaction'; +import { Observable } from 'rxjs'; +import { AccountInfo } from '../model/account/AccountInfo'; +import { Address } from '../model/account/Address'; +import { AggregateTransaction } from '../model/transaction/AggregateTransaction'; +import { Transaction } from '../model/transaction/Transaction'; import { QueryParams } from './QueryParams'; import { TransactionFilter } from './TransactionFilter'; @@ -28,7 +28,6 @@ import { TransactionFilter } from './TransactionFilter'; * @since 1.0 */ export interface AccountRepository { - /** * Gets an AccountInfo for an account. * @param address Address @@ -61,7 +60,10 @@ export interface AccountRepository { * @returns Observable */ getAccountIncomingTransactions( - address: Address, queryParams?: QueryParams, transactionFilter?: TransactionFilter): Observable; + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable; /** * Gets an array of transactions for which an account is the sender a transaction. @@ -72,7 +74,10 @@ export interface AccountRepository { * @returns Observable */ getAccountOutgoingTransactions( - address: Address, queryParams?: QueryParams, transactionFilter?: TransactionFilter): Observable; + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable; /** * Gets the array of transactions for which an account is the sender or receiver and which have not yet been included in a block. @@ -84,7 +89,10 @@ export interface AccountRepository { * @returns Observable */ getAccountUnconfirmedTransactions( - address: Address, queryParams?: QueryParams, transactionFilter?: TransactionFilter): Observable; + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable; /** * Gets an array of transactions for which an account is the sender or has sign the transaction. @@ -95,5 +103,8 @@ export interface AccountRepository { * @returns Observable */ getAccountPartialTransactions( - address: Address, queryParams?: QueryParams, transactionFilter?: TransactionFilter): Observable; + address: Address, + queryParams?: QueryParams, + transactionFilter?: TransactionFilter, + ): Observable; } diff --git a/src/infrastructure/BlockHttp.ts b/src/infrastructure/BlockHttp.ts index 0442305715..944d691486 100644 --- a/src/infrastructure/BlockHttp.ts +++ b/src/infrastructure/BlockHttp.ts @@ -64,14 +64,18 @@ export class BlockHttp extends Http implements BlockRepository { * @param queryParams - (Optional) Query params * @returns Observable */ - public getBlockTransactions(height: UInt64, - queryParams?: QueryParams): Observable { - return this.call(this.blockRoutesApi.getBlockTransactions(height.toString(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering), (body) => body.map((transactionDTO) => { - return CreateTransactionFromDTO(transactionDTO); - }), + public getBlockTransactions(height: UInt64, queryParams?: QueryParams): Observable { + return this.call( + this.blockRoutesApi.getBlockTransactions( + height.toString(), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering, + ), + (body) => + body.map((transactionDTO) => { + return CreateTransactionFromDTO(transactionDTO); + }), ); } @@ -83,7 +87,8 @@ export class BlockHttp extends Http implements BlockRepository { */ public getBlocksByHeightWithLimit(height: UInt64, limit: number): Observable { return this.call(this.blockRoutesApi.getBlocksByHeightWithLimit(height.toString(), limit), (body) => - body.map((blockDTO) => this.toBlockInfo(blockDTO))); + body.map((blockDTO) => this.toBlockInfo(blockDTO)), + ); } /** @@ -130,9 +135,8 @@ export class BlockHttp extends Http implements BlockRepository { */ public getMerkleTransaction(height: UInt64, hash: string): Observable { return this.call( - this.blockRoutesApi.getMerkleTransaction(height.toString(), hash), (body) => new MerkleProofInfo( - body.merklePath!.map((payload) => new MerklePathItem(payload.position, payload.hash)), - )); + this.blockRoutesApi.getMerkleTransaction(height.toString(), hash), + (body) => new MerkleProofInfo(body.merklePath!.map((payload) => new MerklePathItem(payload.position, payload.hash))), + ); } - } diff --git a/src/infrastructure/BlockRepository.ts b/src/infrastructure/BlockRepository.ts index c4c6d97af1..05751cd13b 100644 --- a/src/infrastructure/BlockRepository.ts +++ b/src/infrastructure/BlockRepository.ts @@ -14,12 +14,12 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; -import {BlockInfo} from '../model/blockchain/BlockInfo'; +import { Observable } from 'rxjs'; +import { BlockInfo } from '../model/blockchain/BlockInfo'; import { MerkleProofInfo } from '../model/blockchain/MerkleProofInfo'; -import {Transaction} from '../model/transaction/Transaction'; +import { Transaction } from '../model/transaction/Transaction'; import { UInt64 } from '../model/UInt64'; -import {QueryParams} from './QueryParams'; +import { QueryParams } from './QueryParams'; /** * Blockchain interface repository. @@ -27,7 +27,6 @@ import {QueryParams} from './QueryParams'; * @since 1.0 */ export interface BlockRepository { - /** * Gets a BlockInfo for a given block height * @param height - Block height @@ -41,8 +40,7 @@ export interface BlockRepository { * @param queryParams - (Optional) Query params * @returns Observable */ - getBlockTransactions(height: UInt64, - queryParams?: QueryParams): Observable; + getBlockTransactions(height: UInt64, queryParams?: QueryParams): Observable; /** * Gets array of BlockInfo for a block height with limit diff --git a/src/infrastructure/ChainHttp.ts b/src/infrastructure/ChainHttp.ts index 2613adba75..1ff21aec5a 100644 --- a/src/infrastructure/ChainHttp.ts +++ b/src/infrastructure/ChainHttp.ts @@ -56,10 +56,9 @@ export class ChainHttp extends Http implements ChainRepository { * @returns Observable */ public getChainScore(): Observable { - return this.call(this.chainRoutesApi.getChainScore(), (body) => new BlockchainScore( - UInt64.fromNumericString(body.scoreLow), - UInt64.fromNumericString(body.scoreHigh), - ), + return this.call( + this.chainRoutesApi.getChainScore(), + (body) => new BlockchainScore(UInt64.fromNumericString(body.scoreLow), UInt64.fromNumericString(body.scoreHigh)), ); } } diff --git a/src/infrastructure/ChainRepository.ts b/src/infrastructure/ChainRepository.ts index f081e621e6..d79484bef9 100644 --- a/src/infrastructure/ChainRepository.ts +++ b/src/infrastructure/ChainRepository.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; -import {BlockchainScore} from '../model/blockchain/BlockchainScore'; +import { Observable } from 'rxjs'; +import { BlockchainScore } from '../model/blockchain/BlockchainScore'; import { UInt64 } from '../model/UInt64'; /** diff --git a/src/infrastructure/Http.ts b/src/infrastructure/Http.ts index cfb8a86ee1..e57624961a 100644 --- a/src/infrastructure/Http.ts +++ b/src/infrastructure/Http.ts @@ -15,7 +15,6 @@ */ import * as http from 'http'; -// tslint:disable-next-line: ordered-imports import { from as observableFrom, Observable, of as observableOf, throwError } from 'rxjs'; import { catchError, map, shareReplay } from 'rxjs/operators'; import { NodeRoutesApi } from 'symbol-openapi-typescript-node-client'; @@ -43,10 +42,12 @@ export abstract class Http { } else if (networkType) { return observableOf(networkType as NetworkType); } else { - return observableFrom(new NodeRoutesApi(this.url).getNodeInfo()).pipe( - map(({body}) => body.networkIdentifier), - catchError((error) => throwError(this.errorHandling(error))), - ).pipe(shareReplay(1)); + return observableFrom(new NodeRoutesApi(this.url).getNodeInfo()) + .pipe( + map(({ body }) => body.networkIdentifier), + catchError((error) => throwError(this.errorHandling(error))), + ) + .pipe(shareReplay(1)); } } @@ -90,9 +91,12 @@ export abstract class Http { * @param remoteCall the remote call * @param mapper the mapper from dto to the model object. */ - protected call(remoteCall: Promise<{ response: http.IncomingMessage; body: D; }>, mapper: (value: D, index: number) => M) { + protected call( + remoteCall: Promise<{ response: http.IncomingMessage; body: D }>, + mapper: (value: D, index: number) => M, + ): Observable { return observableFrom(remoteCall).pipe( - map(({body}, index) => mapper(body, index)), + map(({ body }, index) => mapper(body, index)), catchError((error) => throwError(this.errorHandling(error))), ); } diff --git a/src/infrastructure/IListener.ts b/src/infrastructure/IListener.ts index 60b27a81ce..d41460b307 100644 --- a/src/infrastructure/IListener.ts +++ b/src/infrastructure/IListener.ts @@ -26,7 +26,6 @@ import { TransactionStatusError } from '../model/transaction/TransactionStatusEr * Listener service */ export interface IListener { - /** * Open web socket connection. * @returns Promise @@ -74,7 +73,7 @@ export interface IListener { * @param address address we listen when a transaction is in unconfirmed state * @return an observable stream of Transaction with state unconfirmed */ - unconfirmedAdded(address: Address): Observable; + unconfirmedAdded(address: Address): Observable; /** * Returns an observable stream of Transaction Hashes for specific address. @@ -126,5 +125,4 @@ export interface IListener { * @return an observable stream of {@link CosignatureSignedTransaction} */ cosignatureAdded(address: Address): Observable; - } diff --git a/src/infrastructure/Listener.ts b/src/infrastructure/Listener.ts index 986f56ecc1..176c2e3d57 100644 --- a/src/infrastructure/Listener.ts +++ b/src/infrastructure/Listener.ts @@ -77,14 +77,16 @@ export class Listener implements IListener { * @param config - Listener configuration * @param websocketInjected - (Optional) WebSocket injected when using listeners in client */ - constructor(/** - * Listener configuration. - */ - private config: string, - /** - * WebSocket injected when using listeners in client. - */ - private websocketInjected?: any) { + constructor( + /** + * Listener configuration. + */ + private config: string, + /** + * WebSocket injected when using listeners in client. + */ + private websocketInjected?: any, + ) { this.config = config.replace(/\/$/, ''); this.url = `${this.config}/ws`; this.messageSubject = new Subject(); @@ -102,12 +104,12 @@ export class Listener implements IListener { } else { this.webSocket = new WebSocket(this.url); } - this.webSocket.onopen = () => { - }; - this.webSocket.onerror = (err) => { + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.webSocket.onopen = (): void => {}; + this.webSocket.onerror = (err: Error): void => { reject(err); }; - this.webSocket.onmessage = (msg) => { + this.webSocket.onmessage = (msg: any): void => { const message = JSON.parse(msg.data as string); this.handleMessage(message, resolve); }; @@ -125,7 +127,7 @@ export class Listener implements IListener { * @param message the object payload. * @param resolve the method to notify when the uid has been resolved and the listener connection has been stablished. */ - handleMessage(message: any, resolve) { + handleMessage(message: any, resolve: any): void { if (message.uid) { this.uid = message.uid; resolve(); @@ -136,7 +138,8 @@ export class Listener implements IListener { }); } else if (message.block) { this.messageSubject.next({ - channelName: ListenerChannelName.block, message: new BlockInfo( + channelName: ListenerChannelName.block, + message: new BlockInfo( message.meta.hash, message.meta.generationHash, message.meta.totalFee ? UInt64.fromNumericString(message.meta.totalFee) : new UInt64([0, 0]), @@ -159,11 +162,13 @@ export class Listener implements IListener { }); } else if (message.code) { this.messageSubject.next({ - channelName: ListenerChannelName.status, message: new TransactionStatusError( + channelName: ListenerChannelName.status, + message: new TransactionStatusError( Address.createFromEncoded(message.address), message.hash, message.code, - Deadline.createFromDTO(message.deadline)), + Deadline.createFromDTO(message.deadline), + ), }); } else if (message.parentHash) { this.messageSubject.next({ @@ -208,12 +213,12 @@ export class Listener implements IListener { */ public newBlock(): Observable { this.subscribeTo('block'); - return this.messageSubject - .asObservable().pipe( + return this.messageSubject.asObservable().pipe( share(), filter((_) => _.channelName === ListenerChannelName.block), filter((_) => _.message instanceof BlockInfo), - map((_) => _.message as BlockInfo)); + map((_) => _.message as BlockInfo), + ); } /** @@ -238,7 +243,8 @@ export class Listener implements IListener { } else { const metaHash = _.transactionInfo!.hash; return metaHash !== undefined ? metaHash.toUpperCase() === transactionHash.toUpperCase() : false; - }}), + } + }), ); } @@ -256,7 +262,8 @@ export class Listener implements IListener { filter((_) => _.channelName === ListenerChannelName.unconfirmedAdded), filter((_) => _.message instanceof Transaction), map((_) => _.message as Transaction), - filter((_) => this.transactionFromAddress(_, address))); + filter((_) => this.transactionFromAddress(_, address)), + ); } /** @@ -272,7 +279,8 @@ export class Listener implements IListener { return this.messageSubject.asObservable().pipe( filter((_) => _.channelName === ListenerChannelName.unconfirmedRemoved), filter((_) => typeof _.message === 'string'), - map((_) => _.message as string)); + map((_) => _.message as string), + ); } /** @@ -297,7 +305,8 @@ export class Listener implements IListener { } else { const metaHash = _.transactionInfo!.hash; return metaHash !== undefined ? metaHash.toUpperCase() === transactionHash.toUpperCase() : false; - }}), + } + }), ); } @@ -314,7 +323,8 @@ export class Listener implements IListener { return this.messageSubject.asObservable().pipe( filter((_) => _.channelName === ListenerChannelName.aggregateBondedRemoved), filter((_) => typeof _.message === 'string'), - map((_) => _.message as string)); + map((_) => _.message as string), + ); } /** @@ -331,7 +341,8 @@ export class Listener implements IListener { filter((_) => _.channelName === ListenerChannelName.status), filter((_) => _.message instanceof TransactionStatusError), map((_) => _.message as TransactionStatusError), - filter((_) => address.equals(_.address))); + filter((_) => address.equals(_.address)), + ); } /** @@ -347,7 +358,8 @@ export class Listener implements IListener { return this.messageSubject.asObservable().pipe( filter((_) => _.channelName.toUpperCase() === ListenerChannelName.cosignature.toUpperCase()), filter((_) => _.message instanceof CosignatureSignedTransaction), - map((_) => _.message as CosignatureSignedTransaction)); + map((_) => _.message as CosignatureSignedTransaction), + ); } /** @@ -355,7 +367,7 @@ export class Listener implements IListener { * Subscribes to a channelName. * @param channel - Channel subscribed to. */ - private subscribeTo(channel: string) { + private subscribeTo(channel: string): void { const subscriptionMessage = { uid: this.uid, subscribe: channel, @@ -380,8 +392,10 @@ export class Listener implements IListener { } }); transaction.innerTransactions.map((innerTransaction: InnerTransaction) => { - if (this.transactionHasSignerOrReceptor(innerTransaction, address) || - this.accountAddedToMultiSig(innerTransaction, address)) { + if ( + this.transactionHasSignerOrReceptor(innerTransaction, address) || + this.accountAddedToMultiSig(innerTransaction, address) + ) { transactionFromAddress = true; } }); @@ -396,15 +410,13 @@ export class Listener implements IListener { * @returns {boolean} */ private transactionHasSignerOrReceptor(transaction: Transaction, address: Address | NamespaceId): boolean { - if (address instanceof NamespaceId) { - return transaction instanceof TransferTransaction - && (transaction.recipientAddress as NamespaceId).equals(address); + return transaction instanceof TransferTransaction && (transaction.recipientAddress as NamespaceId).equals(address); } - return transaction.signer!.address.equals(address) || ( - transaction instanceof TransferTransaction - && (transaction.recipientAddress as Address).equals(address) + return ( + transaction.signer!.address.equals(address) || + (transaction instanceof TransferTransaction && (transaction.recipientAddress as Address).equals(address)) ); } @@ -417,10 +429,10 @@ export class Listener implements IListener { */ private accountAddedToMultiSig(transaction: Transaction, address: Address): boolean { if (transaction instanceof MultisigAccountModificationTransaction) { - return transaction.publicKeyAdditions.find((_: PublicAccount) => - _.address.equals(address)) !== undefined || - transaction.publicKeyDeletions.find((_: PublicAccount) => - _.address.equals(address)) !== undefined; + return ( + transaction.publicKeyAdditions.find((_: PublicAccount) => _.address.equals(address)) !== undefined || + transaction.publicKeyDeletions.find((_: PublicAccount) => _.address.equals(address)) !== undefined + ); } return false; } diff --git a/src/infrastructure/MetadataHttp.ts b/src/infrastructure/MetadataHttp.ts index 23c1aa0b67..4cc5e11320 100644 --- a/src/infrastructure/MetadataHttp.ts +++ b/src/infrastructure/MetadataHttp.ts @@ -58,11 +58,13 @@ export class MetadataHttp extends Http implements MetadataRepository { */ public getAccountMetadata(address: Address, queryParams?: QueryParams): Observable { return this.call( - this.metadataRoutesApi.getAccountMetadata(address.plain(), + this.metadataRoutesApi.getAccountMetadata( + address.plain(), this.queryParams(queryParams).pageSize, this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering), - (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)) + this.queryParams(queryParams).ordering, + ), + (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)), ); } @@ -73,9 +75,8 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getAccountMetadataByKey(address: Address, key: string): Observable { - return this.call( - this.metadataRoutesApi.getAccountMetadataByKey(address.plain(), key), - (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)) + return this.call(this.metadataRoutesApi.getAccountMetadataByKey(address.plain(), key), (body) => + body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)), ); } @@ -87,9 +88,8 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getAccountMetadataByKeyAndSender(address: Address, key: string, publicKey: string): Observable { - return this.call( - this.metadataRoutesApi.getAccountMetadataByKeyAndSender(address.plain(), key, publicKey), - (body) => this.buildMetadata(body) + return this.call(this.metadataRoutesApi.getAccountMetadataByKeyAndSender(address.plain(), key, publicKey), (body) => + this.buildMetadata(body), ); } @@ -101,11 +101,13 @@ export class MetadataHttp extends Http implements MetadataRepository { */ getMosaicMetadata(mosaicId: MosaicId, queryParams?: QueryParams): Observable { return this.call( - this.metadataRoutesApi.getMosaicMetadata(mosaicId.toHex(), + this.metadataRoutesApi.getMosaicMetadata( + mosaicId.toHex(), this.queryParams(queryParams).pageSize, this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering), - (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)) + this.queryParams(queryParams).ordering, + ), + (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)), ); } @@ -116,9 +118,8 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getMosaicMetadataByKey(mosaicId: MosaicId, key: string): Observable { - return this.call( - this.metadataRoutesApi.getMosaicMetadataByKey(mosaicId.toHex(), key), - (body) => body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)) + return this.call(this.metadataRoutesApi.getMosaicMetadataByKey(mosaicId.toHex(), key), (body) => + body.metadataEntries.map((metadataEntry) => this.buildMetadata(metadataEntry)), ); } @@ -130,9 +131,7 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ getMosaicMetadataByKeyAndSender(mosaicId: MosaicId, key: string, publicKey: string): Observable { - return this.call( - this.metadataRoutesApi.getMosaicMetadataByKeyAndSender(mosaicId.toHex(), key, publicKey), this.buildMetadata - ); + return this.call(this.metadataRoutesApi.getMosaicMetadataByKeyAndSender(mosaicId.toHex(), key, publicKey), this.buildMetadata); } /** @@ -143,10 +142,13 @@ export class MetadataHttp extends Http implements MetadataRepository { */ public getNamespaceMetadata(namespaceId: NamespaceId, queryParams?: QueryParams): Observable { return this.call( - this.metadataRoutesApi.getNamespaceMetadata(namespaceId.toHex(), + this.metadataRoutesApi.getNamespaceMetadata( + namespaceId.toHex(), this.queryParams(queryParams).pageSize, this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering), body => body.metadataEntries.map(this.buildMetadata) + this.queryParams(queryParams).ordering, + ), + (body) => body.metadataEntries.map(this.buildMetadata), ); } @@ -157,9 +159,8 @@ export class MetadataHttp extends Http implements MetadataRepository { * @returns Observable */ public getNamespaceMetadataByKey(namespaceId: NamespaceId, key: string): Observable { - return this.call( - this.metadataRoutesApi.getNamespaceMetadataByKey(namespaceId.toHex(), key), - (body) => body.metadataEntries.map(this.buildMetadata) + return this.call(this.metadataRoutesApi.getNamespaceMetadataByKey(namespaceId.toHex(), key), (body) => + body.metadataEntries.map(this.buildMetadata), ); } @@ -172,7 +173,9 @@ export class MetadataHttp extends Http implements MetadataRepository { */ public getNamespaceMetadataByKeyAndSender(namespaceId: NamespaceId, key: string, publicKey: string): Observable { return this.call( - this.metadataRoutesApi.getNamespaceMetadataByKeyAndSender(namespaceId.toHex(), key, publicKey), this.buildMetadata); + this.metadataRoutesApi.getNamespaceMetadataByKeyAndSender(namespaceId.toHex(), key, publicKey), + this.buildMetadata, + ); } /** diff --git a/src/infrastructure/MetadataRepository.ts b/src/infrastructure/MetadataRepository.ts index 53178f1c2b..734f9f187b 100644 --- a/src/infrastructure/MetadataRepository.ts +++ b/src/infrastructure/MetadataRepository.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; +import { Observable } from 'rxjs'; import { Address } from '../model/account/Address'; import { Metadata } from '../model/metadata/Metadata'; -import {MosaicId} from '../model/mosaic/MosaicId'; +import { MosaicId } from '../model/mosaic/MosaicId'; import { NamespaceId } from '../model/namespace/NamespaceId'; import { QueryParams } from './QueryParams'; @@ -27,7 +27,6 @@ import { QueryParams } from './QueryParams'; * @since 1.0 */ export interface MetadataRepository { - /** * Returns the account metadata given an account id. * @param address - Account address to be created from PublicKey or RawAddress @@ -101,7 +100,5 @@ export interface MetadataRepository { * @param publicKey - Sender public key * @returns Observable */ - getNamespaceMetadataByKeyAndSender(namespaceId: NamespaceId, - key: string, - publicKey: string): Observable; + getNamespaceMetadataByKeyAndSender(namespaceId: NamespaceId, key: string, publicKey: string): Observable; } diff --git a/src/infrastructure/MosaicHttp.ts b/src/infrastructure/MosaicHttp.ts index 42491a23f1..12a4920c49 100644 --- a/src/infrastructure/MosaicHttp.ts +++ b/src/infrastructure/MosaicHttp.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -import { Observable, throwError } from 'rxjs'; -import { catchError, mergeMap } from 'rxjs/operators'; -import { MosaicRoutesApi, MosaicIds, AccountIds, MosaicInfoDTO, MosaicDTO } from 'symbol-openapi-typescript-node-client'; +import { Observable } from 'rxjs'; +import { mergeMap } from 'rxjs/operators'; +import { AccountIds, MosaicDTO, MosaicIds, MosaicInfoDTO, MosaicRoutesApi } from 'symbol-openapi-typescript-node-client'; import { Address } from '../model/account/Address'; import { PublicAccount } from '../model/account/PublicAccount'; import { MosaicFlags } from '../model/mosaic/MosaicFlags'; @@ -64,8 +64,9 @@ export class MosaicHttp extends Http implements MosaicRepository { public getMosaic(mosaicId: MosaicId): Observable { return this.networkTypeObservable.pipe( mergeMap((networkType) => - this.call(this.mosaicRoutesApi.getMosaic(mosaicId.toHex()), (body) => this.toMosaicInfo(body, networkType))), - ); + this.call(this.mosaicRoutesApi.getMosaic(mosaicId.toHex()), (body) => this.toMosaicInfo(body, networkType)), + ), + ); } /** @@ -78,7 +79,8 @@ export class MosaicHttp extends Http implements MosaicRepository { ids.mosaicIds = mosaicIds.map((id) => id.toHex()); return this.networkTypeObservable.pipe( mergeMap((networkType) => - this.call(this.mosaicRoutesApi.getMosaics(ids), (body) => body.map((b) => this.toMosaicInfo(b, networkType)))), + this.call(this.mosaicRoutesApi.getMosaics(ids), (body) => body.map((b) => this.toMosaicInfo(b, networkType))), + ), ); } @@ -90,8 +92,10 @@ export class MosaicHttp extends Http implements MosaicRepository { public getMosaicsFromAccount(address: Address): Observable { return this.networkTypeObservable.pipe( mergeMap((networkType) => - this.call(this.mosaicRoutesApi.getMosaicsFromAccount(address.plain()), - (body) => body.mosaics.map((b) => this.toMosaicInfoFromMosaicDto(b, networkType)))), + this.call(this.mosaicRoutesApi.getMosaicsFromAccount(address.plain()), (body) => + body.mosaics.map((b) => this.toMosaicInfoFromMosaicDto(b, networkType)), + ), + ), ); } @@ -105,8 +109,10 @@ export class MosaicHttp extends Http implements MosaicRepository { accountIds.addresses = addresses.map((address) => address.plain()); return this.networkTypeObservable.pipe( mergeMap((networkType) => - this.call(this.mosaicRoutesApi.getMosaicsFromAccounts(accountIds), - (body) => body.mosaics.map((b) => this.toMosaicInfoFromMosaicDto(b, networkType)))), + this.call(this.mosaicRoutesApi.getMosaicsFromAccounts(accountIds), (body) => + body.mosaics.map((b) => this.toMosaicInfoFromMosaicDto(b, networkType)), + ), + ), ); } @@ -119,13 +125,13 @@ export class MosaicHttp extends Http implements MosaicRepository { private toMosaicInfo(mosaicInfo: MosaicInfoDTO, networkType: NetworkType): MosaicInfo { return new MosaicInfo( new MosaicId(mosaicInfo.mosaic.id), - UInt64.fromNumericString(mosaicInfo.mosaic.supply), - UInt64.fromNumericString(mosaicInfo.mosaic.startHeight), - PublicAccount.createFromPublicKey(mosaicInfo.mosaic.ownerPublicKey, networkType), - mosaicInfo.mosaic.revision, - new MosaicFlags(mosaicInfo.mosaic.flags), - mosaicInfo.mosaic.divisibility, - UInt64.fromNumericString(mosaicInfo.mosaic.duration), + UInt64.fromNumericString(mosaicInfo.mosaic.supply), + UInt64.fromNumericString(mosaicInfo.mosaic.startHeight), + PublicAccount.createFromPublicKey(mosaicInfo.mosaic.ownerPublicKey, networkType), + mosaicInfo.mosaic.revision, + new MosaicFlags(mosaicInfo.mosaic.flags), + mosaicInfo.mosaic.divisibility, + UInt64.fromNumericString(mosaicInfo.mosaic.duration), ); } @@ -138,13 +144,13 @@ export class MosaicHttp extends Http implements MosaicRepository { private toMosaicInfoFromMosaicDto(mosaicInfo: MosaicDTO, networkType: NetworkType): MosaicInfo { return new MosaicInfo( new MosaicId(mosaicInfo.id), - UInt64.fromNumericString(mosaicInfo.supply), - UInt64.fromNumericString(mosaicInfo.startHeight), - PublicAccount.createFromPublicKey(mosaicInfo.ownerPublicKey, networkType), - mosaicInfo.revision, - new MosaicFlags(mosaicInfo.flags), - mosaicInfo.divisibility, - UInt64.fromNumericString(mosaicInfo.duration), + UInt64.fromNumericString(mosaicInfo.supply), + UInt64.fromNumericString(mosaicInfo.startHeight), + PublicAccount.createFromPublicKey(mosaicInfo.ownerPublicKey, networkType), + mosaicInfo.revision, + new MosaicFlags(mosaicInfo.flags), + mosaicInfo.divisibility, + UInt64.fromNumericString(mosaicInfo.duration), ); } } diff --git a/src/infrastructure/MosaicRepository.ts b/src/infrastructure/MosaicRepository.ts index 1913432e46..3fa1624185 100644 --- a/src/infrastructure/MosaicRepository.ts +++ b/src/infrastructure/MosaicRepository.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; +import { Observable } from 'rxjs'; import { Address } from '../model/account/Address'; -import {MosaicId} from '../model/mosaic/MosaicId'; -import {MosaicInfo} from '../model/mosaic/MosaicInfo'; +import { MosaicId } from '../model/mosaic/MosaicId'; +import { MosaicInfo } from '../model/mosaic/MosaicInfo'; /** * Mosaic interface repository. @@ -25,7 +25,6 @@ import {MosaicInfo} from '../model/mosaic/MosaicInfo'; * @since 1.0 */ export interface MosaicRepository { - /** * Gets a MosaicInfo for a given mosaicId * @param mosaicId - Mosaic id @@ -40,11 +39,11 @@ export interface MosaicRepository { */ getMosaics(mosaicIds: MosaicId[]): Observable; - /** - * Gets mosaics created for a given address. - * @summary Get mosaics created for given address - * @param address Address - */ + /** + * Gets mosaics created for a given address. + * @summary Get mosaics created for given address + * @param address Address + */ getMosaicsFromAccount(address: Address): Observable; /** diff --git a/src/infrastructure/MultisigHttp.ts b/src/infrastructure/MultisigHttp.ts index fa056718ae..c08ed01981 100644 --- a/src/infrastructure/MultisigHttp.ts +++ b/src/infrastructure/MultisigHttp.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -import { from as observableFrom, Observable, throwError } from 'rxjs'; -import { catchError, map, mergeMap } from 'rxjs/operators'; -import { MultisigRoutesApi } from 'symbol-openapi-typescript-node-client'; +import { Observable } from 'rxjs'; +import { mergeMap } from 'rxjs/operators'; +import { MultisigAccountInfoDTO, MultisigRoutesApi } from 'symbol-openapi-typescript-node-client'; import { Address } from '../model/account/Address'; import { MultisigAccountGraphInfo } from '../model/account/MultisigAccountGraphInfo'; import { MultisigAccountInfo } from '../model/account/MultisigAccountInfo'; @@ -41,6 +41,7 @@ export class MultisigHttp extends Http implements MultisigRepository { * network type for the mappings. */ private readonly networkTypeObservable: Observable; + /** * Constructor * @param url @@ -60,19 +61,12 @@ export class MultisigHttp extends Http implements MultisigRepository { */ public getMultisigAccountInfo(address: Address): Observable { return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.multisigRoutesApi.getAccountMultisig(address.plain())) - .pipe(map(({body}) => new MultisigAccountInfo( - PublicAccount.createFromPublicKey(body.multisig.accountPublicKey, networkType), - body.multisig.minApproval, - body.multisig.minRemoval, - body.multisig.cosignatoryPublicKeys - .map((cosigner) => PublicAccount.createFromPublicKey(cosigner, networkType)), - body.multisig.multisigPublicKeys - .map((multisigAccount) => PublicAccount.createFromPublicKey(multisigAccount, networkType)), - )), - catchError((error) => throwError(this.errorHandling(error))), - ))); + mergeMap((networkType) => + this.call(this.multisigRoutesApi.getAccountMultisig(address.plain()), (body) => + this.toMultisigAccountInfo(body, networkType), + ), + ), + ); } /** @@ -82,29 +76,36 @@ export class MultisigHttp extends Http implements MultisigRepository { */ public getMultisigAccountGraphInfo(address: Address): Observable { return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.multisigRoutesApi.getAccountMultisigGraph(address.plain())) - .pipe(map(({body}) => { - const multisigAccountGraphInfosDTO = body; - const multisigAccounts = new Map(); - multisigAccountGraphInfosDTO.map((multisigAccountGraphInfoDTO) => { - multisigAccounts.set(multisigAccountGraphInfoDTO.level, - multisigAccountGraphInfoDTO.multisigEntries.map((multisigAccountInfoDTO) => { - return new MultisigAccountInfo( - PublicAccount.createFromPublicKey(multisigAccountInfoDTO.multisig.accountPublicKey, networkType), - multisigAccountInfoDTO.multisig.minApproval, - multisigAccountInfoDTO.multisig.minRemoval, - multisigAccountInfoDTO.multisig.cosignatoryPublicKeys - .map((cosigner) => PublicAccount.createFromPublicKey(cosigner, networkType)), - multisigAccountInfoDTO.multisig.multisigPublicKeys - .map((multisigAccountDTO) => - PublicAccount.createFromPublicKey(multisigAccountDTO, networkType))); - }), - ); - }); - return new MultisigAccountGraphInfo(multisigAccounts); - }), - catchError((error) => throwError(this.errorHandling(error))), - ))); + mergeMap((networkType) => + this.call(this.multisigRoutesApi.getAccountMultisigGraph(address.plain()), (body) => { + const multisigAccountGraphInfosDTO = body; + const multisigAccounts = new Map(); + multisigAccountGraphInfosDTO.map((multisigAccountGraphInfoDTO) => { + multisigAccounts.set( + multisigAccountGraphInfoDTO.level, + multisigAccountGraphInfoDTO.multisigEntries.map((multisigAccountInfoDTO) => { + return this.toMultisigAccountInfo(multisigAccountInfoDTO, networkType); + }), + ); + }); + return new MultisigAccountGraphInfo(multisigAccounts); + }), + ), + ); + } + + /** + * It maps from MultisigAccountInfoDTO to MultisigAccountInfo + * @param dto the DTO + * @param networkType the network type + */ + private toMultisigAccountInfo(dto: MultisigAccountInfoDTO, networkType: NetworkType): MultisigAccountInfo { + return new MultisigAccountInfo( + PublicAccount.createFromPublicKey(dto.multisig.accountPublicKey, networkType), + dto.multisig.minApproval, + dto.multisig.minRemoval, + dto.multisig.cosignatoryPublicKeys.map((cosigner) => PublicAccount.createFromPublicKey(cosigner, networkType)), + dto.multisig.multisigPublicKeys.map((multisigAccount) => PublicAccount.createFromPublicKey(multisigAccount, networkType)), + ); } } diff --git a/src/infrastructure/MultisigRepository.ts b/src/infrastructure/MultisigRepository.ts index 876a15eb02..c8613d336a 100644 --- a/src/infrastructure/MultisigRepository.ts +++ b/src/infrastructure/MultisigRepository.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; -import {Address} from '../model/account/Address'; -import {MultisigAccountGraphInfo} from '../model/account/MultisigAccountGraphInfo'; -import {MultisigAccountInfo} from '../model/account/MultisigAccountInfo'; +import { Observable } from 'rxjs'; +import { Address } from '../model/account/Address'; +import { MultisigAccountGraphInfo } from '../model/account/MultisigAccountGraphInfo'; +import { MultisigAccountInfo } from '../model/account/MultisigAccountInfo'; /** * Multisig interface repository. @@ -25,7 +25,6 @@ import {MultisigAccountInfo} from '../model/account/MultisigAccountInfo'; * @since 1.0 */ export interface MultisigRepository { - /** * Gets a MultisigAccountInfo for an account. * @param address - * Address can be created rawAddress or publicKey @@ -39,5 +38,4 @@ export interface MultisigRepository { * @returns Observable */ getMultisigAccountGraphInfo(address: Address): Observable; - } diff --git a/src/infrastructure/NamespaceHttp.ts b/src/infrastructure/NamespaceHttp.ts index 152a97ef6c..288ef9cd01 100644 --- a/src/infrastructure/NamespaceHttp.ts +++ b/src/infrastructure/NamespaceHttp.ts @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { from as observableFrom, Observable, throwError } from 'rxjs'; -import { catchError, map, mergeMap } from 'rxjs/operators'; -import { NamespaceRoutesApi } from 'symbol-openapi-typescript-node-client'; +import { Observable } from 'rxjs'; +import { mergeMap } from 'rxjs/operators'; +import { NamespaceDTO, NamespaceInfoDTO, NamespaceRoutesApi } from 'symbol-openapi-typescript-node-client'; import { Convert as convert, RawAddress as AddressLibrary } from '../core/format'; import { AccountNames } from '../model/account/AccountNames'; import { Address } from '../model/account/Address'; @@ -53,6 +53,7 @@ export class NamespaceHttp extends Http implements NamespaceRepository { * network type for the mappings. */ private readonly networkTypeObservable: Observable; + /** * Constructor * @param url @@ -74,17 +75,16 @@ export class NamespaceHttp extends Http implements NamespaceRepository { const accountIdsBody = { addresses: addresses.map((address) => address.plain()), }; - return observableFrom( - this.namespaceRoutesApi.getAccountsNames(accountIdsBody)).pipe( - map(({body}) => body.accountNames.map((accountName) => { - return new AccountNames( + return this.call(this.namespaceRoutesApi.getAccountsNames(accountIdsBody), (body) => + body.accountNames.map( + (accountName) => + new AccountNames( Address.createFromEncoded(accountName.address), accountName.names.map((name) => { return new NamespaceName(new NamespaceId(name), name); }), - ); - })), - catchError((error) => throwError(this.errorHandling(error))), + ), + ), ); } @@ -98,18 +98,17 @@ export class NamespaceHttp extends Http implements NamespaceRepository { const mosaicIdsBody = { mosaicIds: mosaicIds.map((id) => id.toHex()), }; - return observableFrom( - this.namespaceRoutesApi.getMosaicsNames(mosaicIdsBody)).pipe( - map(({body}) => body.mosaicNames.map((mosaic) => { - return new MosaicNames( + return this.call(this.namespaceRoutesApi.getMosaicsNames(mosaicIdsBody), (body) => + body.mosaicNames.map( + (mosaic) => + new MosaicNames( new MosaicId(mosaic.mosaicId), mosaic.names.map((name) => { - return new NamespaceName(new NamespaceId(name), name); + return new NamespaceName(new NamespaceId(name), name); }), - ); - })), - catchError((error) => throwError(this.errorHandling(error))), - ); + ), + ), + ); } /** @@ -119,23 +118,8 @@ export class NamespaceHttp extends Http implements NamespaceRepository { */ public getNamespace(namespaceId: NamespaceId): Observable { return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.namespaceRoutesApi.getNamespace(namespaceId.toHex())).pipe( - map(({body}) => new NamespaceInfo( - body.meta.active, - body.meta.index, - body.meta.id, - body.namespace.registrationType as number, - body.namespace.depth, - this.extractLevels(body.namespace), - NamespaceId.createFromEncoded(body.namespace.parentId), - PublicAccount.createFromPublicKey(body.namespace.ownerPublicKey, networkType), - UInt64.fromNumericString(body.namespace.startHeight), - UInt64.fromNumericString(body.namespace.endHeight), - this.extractAlias(body.namespace), - )), - catchError((error) => throwError(this.errorHandling(error))), - ), + mergeMap((networkType) => + this.call(this.namespaceRoutesApi.getNamespace(namespaceId.toHex()), (body) => this.toNamespaceInfo(body, networkType)), ), ); } @@ -146,32 +130,20 @@ export class NamespaceHttp extends Http implements NamespaceRepository { * @param queryParams - (Optional) Query params * @returns Observable */ - public getNamespacesFromAccount(address: Address, - queryParams?: QueryParams): Observable { + public getNamespacesFromAccount(address: Address, queryParams?: QueryParams): Observable { return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.namespaceRoutesApi.getNamespacesFromAccount(address.plain(), - this.queryParams(queryParams).pageSize, - this.queryParams(queryParams).id, - this.queryParams(queryParams).ordering)).pipe( - map(({body}) => body.namespaces.map((namespaceInfoDTO) => { - return new NamespaceInfo( - namespaceInfoDTO.meta.active, - namespaceInfoDTO.meta.index, - namespaceInfoDTO.meta.id, - namespaceInfoDTO.namespace.registrationType as number, - namespaceInfoDTO.namespace.depth, - this.extractLevels(namespaceInfoDTO.namespace), - NamespaceId.createFromEncoded(namespaceInfoDTO.namespace.parentId), - PublicAccount.createFromPublicKey(namespaceInfoDTO.namespace.ownerPublicKey, networkType), - UInt64.fromNumericString(namespaceInfoDTO.namespace.startHeight), - UInt64.fromNumericString(namespaceInfoDTO.namespace.endHeight), - this.extractAlias(namespaceInfoDTO.namespace), - ); - })), - catchError((error) => throwError(this.errorHandling(error))), + mergeMap((networkType) => + this.call( + this.namespaceRoutesApi.getNamespacesFromAccount( + address.plain(), + this.queryParams(queryParams).pageSize, + this.queryParams(queryParams).id, + this.queryParams(queryParams).ordering, + ), + (body) => body.namespaces.map((namespaceInfoDTO) => this.toNamespaceInfo(namespaceInfoDTO, networkType)), + ), ), - )); + ); } /** @@ -180,32 +152,17 @@ export class NamespaceHttp extends Http implements NamespaceRepository { * @param queryParams - (Optional) Query params * @returns Observable */ - public getNamespacesFromAccounts(addresses: Address[], - queryParams?: QueryParams): Observable { + public getNamespacesFromAccounts(addresses: Address[]): Observable { const publicKeysBody = { addresses: addresses.map((address) => address.plain()), }; return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.namespaceRoutesApi.getNamespacesFromAccounts(publicKeysBody)).pipe( - map(({body}) => body.namespaces.map((namespaceInfoDTO) => { - return new NamespaceInfo( - namespaceInfoDTO.meta.active, - namespaceInfoDTO.meta.index, - namespaceInfoDTO.meta.id, - namespaceInfoDTO.namespace.registrationType as number, - namespaceInfoDTO.namespace.depth, - this.extractLevels(namespaceInfoDTO.namespace), - NamespaceId.createFromEncoded(namespaceInfoDTO.namespace.parentId), - PublicAccount.createFromPublicKey(namespaceInfoDTO.namespace.ownerPublicKey, networkType), - UInt64.fromNumericString(namespaceInfoDTO.namespace.startHeight), - UInt64.fromNumericString(namespaceInfoDTO.namespace.endHeight), - this.extractAlias(namespaceInfoDTO.namespace), - ); - })), - catchError((error) => throwError(this.errorHandling(error))), + mergeMap((networkType) => + this.call(this.namespaceRoutesApi.getNamespacesFromAccounts(publicKeysBody), (body) => + body.namespaces.map((namespaceInfoDTO) => this.toNamespaceInfo(namespaceInfoDTO, networkType)), + ), ), - )); + ); } /** @@ -217,16 +174,14 @@ export class NamespaceHttp extends Http implements NamespaceRepository { const namespaceIdsBody = { namespaceIds: namespaceIds.map((id) => id.toHex()), }; - return observableFrom( - this.namespaceRoutesApi.getNamespacesNames(namespaceIdsBody)).pipe( - map(({body}) => body.map((namespaceNameDTO) => { - return new NamespaceName( - NamespaceId.createFromEncoded(namespaceNameDTO.id), - namespaceNameDTO.name, - namespaceNameDTO.parentId ? NamespaceId.createFromEncoded(namespaceNameDTO.parentId) : undefined, - ); - })), - catchError((error) => throwError(this.errorHandling(error))), + return this.call(this.namespaceRoutesApi.getNamespacesNames(namespaceIdsBody), (body) => + body.map((namespaceNameDTO) => { + return new NamespaceName( + NamespaceId.createFromEncoded(namespaceNameDTO.id), + namespaceNameDTO.name, + namespaceNameDTO.parentId ? NamespaceId.createFromEncoded(namespaceNameDTO.parentId) : undefined, + ); + }), ); } @@ -237,25 +192,24 @@ export class NamespaceHttp extends Http implements NamespaceRepository { */ public getLinkedMosaicId(namespaceId: NamespaceId): Observable { return this.networkTypeObservable.pipe( - mergeMap(() => observableFrom( - this.namespaceRoutesApi.getNamespace(namespaceId.toHex())).pipe( - map(({body}) => { + mergeMap(() => + this.call(this.namespaceRoutesApi.getNamespace(namespaceId.toHex()), (body) => { const namespaceInfoDTO = body; if (namespaceInfoDTO.namespace === undefined) { // forward catapult-rest error throw namespaceInfoDTO; } - - if (namespaceInfoDTO.namespace.alias.type.valueOf() === AliasType.None - || namespaceInfoDTO.namespace.alias.type.valueOf() !== AliasType.Mosaic - || !namespaceInfoDTO.namespace.alias.mosaicId) { - throw new Error('No mosaicId is linked to namespace \'' + namespaceInfoDTO.namespace.level0 + '\''); + if ( + namespaceInfoDTO.namespace.alias.type.valueOf() === AliasType.None || + namespaceInfoDTO.namespace.alias.type.valueOf() !== AliasType.Mosaic || + !namespaceInfoDTO.namespace.alias.mosaicId + ) { + throw new Error(`No mosaicId is linked to namespace '${namespaceInfoDTO.namespace.level0}'`); } return new MosaicId(namespaceInfoDTO.namespace.alias.mosaicId); }), - catchError((error) => throwError(this.errorHandling(error))), ), - )); + ); } /** @@ -265,31 +219,51 @@ export class NamespaceHttp extends Http implements NamespaceRepository { */ public getLinkedAddress(namespaceId: NamespaceId): Observable
{ return this.networkTypeObservable.pipe( - mergeMap(() => observableFrom( - this.namespaceRoutesApi.getNamespace(namespaceId.toHex())).pipe( - map(({body}) => { + mergeMap(() => + this.call(this.namespaceRoutesApi.getNamespace(namespaceId.toHex()), (body) => { const namespaceInfoDTO = body; if (namespaceInfoDTO.namespace === undefined) { // forward catapult-rest error throw namespaceInfoDTO; } - - if (namespaceInfoDTO.namespace.alias.type.valueOf() === AliasType.None - || namespaceInfoDTO.namespace.alias.type.valueOf() !== AliasType.Address - || !namespaceInfoDTO.namespace.alias.address) { - throw new Error('No address is linked to namespace \'' + namespaceInfoDTO.namespace.level0 + '\''); + if ( + namespaceInfoDTO.namespace.alias.type.valueOf() === AliasType.None || + namespaceInfoDTO.namespace.alias.type.valueOf() !== AliasType.Address || + !namespaceInfoDTO.namespace.alias.address + ) { + throw new Error(`No address is linked to namespace '${namespaceInfoDTO.namespace.level0}'`); } const addressDecoded = namespaceInfoDTO.namespace.alias.address; const address = AddressLibrary.addressToString(convert.hexToUint8(addressDecoded)); return Address.createFromRawAddress(address); }), - catchError((error) => throwError(this.errorHandling(error))), ), - )); + ); + } + + /** + * It maps from a NamespaceInfoDTO to NamespaceInfo + * @param dto the dto + * @param networkType the network type + */ + private toNamespaceInfo(dto: NamespaceInfoDTO, networkType: NetworkType): NamespaceInfo { + return new NamespaceInfo( + dto.meta.active, + dto.meta.index, + dto.meta.id, + dto.namespace.registrationType as number, + dto.namespace.depth, + this.extractLevels(dto.namespace), + NamespaceId.createFromEncoded(dto.namespace.parentId), + PublicAccount.createFromPublicKey(dto.namespace.ownerPublicKey, networkType), + UInt64.fromNumericString(dto.namespace.startHeight), + UInt64.fromNumericString(dto.namespace.endHeight), + this.extractAlias(dto.namespace), + ); } - private extractLevels(namespace: any): NamespaceId[] { + private extractLevels(namespace: NamespaceDTO): NamespaceId[] { const result: NamespaceId[] = []; if (namespace.level0) { result.push(NamespaceId.createFromEncoded(namespace.level0)); @@ -310,13 +284,12 @@ export class NamespaceHttp extends Http implements NamespaceRepository { * @access private * @param namespace */ - private extractAlias(namespace: any): Alias { - if (namespace.alias && namespace.alias.type === AliasType.Mosaic) { - return new MosaicAlias(new MosaicId(namespace.alias.mosaicId)); - } else if (namespace.alias && namespace.alias.type === AliasType.Address) { - return new AddressAlias(Address.createFromEncoded(namespace.alias.address)); + private extractAlias(namespace: NamespaceDTO): Alias { + if (namespace.alias && namespace.alias.type.valueOf() === AliasType.Mosaic) { + return new MosaicAlias(new MosaicId(namespace.alias.mosaicId!)); + } else if (namespace.alias && namespace.alias.type.valueOf() === AliasType.Address) { + return new AddressAlias(Address.createFromEncoded(namespace.alias.address!)); } - return new EmptyAlias(); } } diff --git a/src/infrastructure/NamespaceRepository.ts b/src/infrastructure/NamespaceRepository.ts index 2db911234a..97a8ffc742 100644 --- a/src/infrastructure/NamespaceRepository.ts +++ b/src/infrastructure/NamespaceRepository.ts @@ -14,15 +14,15 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; +import { Observable } from 'rxjs'; import { AccountNames } from '../model/account/AccountNames'; -import {Address} from '../model/account/Address'; -import {MosaicId} from '../model/mosaic/MosaicId'; +import { Address } from '../model/account/Address'; +import { MosaicId } from '../model/mosaic/MosaicId'; import { MosaicNames } from '../model/mosaic/MosaicNames'; -import {NamespaceId} from '../model/namespace/NamespaceId'; -import {NamespaceInfo} from '../model/namespace/NamespaceInfo'; -import {NamespaceName} from '../model/namespace/NamespaceName'; -import {QueryParams} from './QueryParams'; +import { NamespaceId } from '../model/namespace/NamespaceId'; +import { NamespaceInfo } from '../model/namespace/NamespaceInfo'; +import { NamespaceName } from '../model/namespace/NamespaceName'; +import { QueryParams } from './QueryParams'; /** * Namespace interface repository. @@ -30,7 +30,6 @@ import {QueryParams} from './QueryParams'; * @since 1.0 */ export interface NamespaceRepository { - /** * Get readable names for a set of accountIds. * Returns friendly names for accounts. @@ -60,8 +59,7 @@ export interface NamespaceRepository { * @param queryParams - (Optional) Query params * @returns Observable */ - getNamespacesFromAccount(address: Address, - queryParams?: QueryParams): Observable; + getNamespacesFromAccount(address: Address, queryParams?: QueryParams): Observable; /** * Gets array of NamespaceInfo for different account @@ -69,8 +67,7 @@ export interface NamespaceRepository { * @param queryParams - (Optional) Query params * @returns Observable */ - getNamespacesFromAccounts(addresses: Address[], - queryParams?: QueryParams): Observable; + getNamespacesFromAccounts(addresses: Address[], queryParams?: QueryParams): Observable; /** * Gets array of NamespaceName for different namespaceIds @@ -84,12 +81,12 @@ export interface NamespaceRepository { * @param namespaceId - the namespaceId of the namespace * @returns Observable */ - getLinkedMosaicId(namespaceId: NamespaceId): Observable; + getLinkedMosaicId(namespaceId: NamespaceId): Observable; /** * Gets the Address from a AddressAlias * @param namespaceId - the namespaceId of the namespace * @returnsObservable
*/ - getLinkedAddress(namespaceId: NamespaceId): Observable
; + getLinkedAddress(namespaceId: NamespaceId): Observable
; } diff --git a/src/infrastructure/NetworkHttp.ts b/src/infrastructure/NetworkHttp.ts index fc89966d07..4775e178df 100644 --- a/src/infrastructure/NetworkHttp.ts +++ b/src/infrastructure/NetworkHttp.ts @@ -64,7 +64,6 @@ export class NetworkHttp extends Http implements NetworkRepository { this.nodeHttp = new NodeHttp(url); this.networkRoutesApi = new NetworkRoutesApi(url); this.networkRoutesApi.useQuerystring = true; - } /** @@ -92,9 +91,7 @@ export class NetworkHttp extends Http implements NetworkRepository { * @summary Get the network properties */ public getNetworkProperties(): Observable { - return this.call(this.networkRoutesApi.getNetworkProperties(), (body) => - this.mapNetworkConfigurationDto(body), - ); + return this.call(this.networkRoutesApi.getNetworkProperties(), (body) => this.mapNetworkConfigurationDto(body)); } /** @@ -104,10 +101,15 @@ export class NetworkHttp extends Http implements NetworkRepository { * @summary Get rental fees information */ public getRentalFees(): Observable { - return this.call(this.networkRoutesApi.getRentalFees(), (body) => - new RentalFees(UInt64.fromNumericString(body.effectiveRootNamespaceRentalFeePerBlock), - UInt64.fromNumericString(body.effectiveChildNamespaceRentalFee), - UInt64.fromNumericString(body.effectiveMosaicRentalFee))); + return this.call( + this.networkRoutesApi.getRentalFees(), + (body) => + new RentalFees( + UInt64.fromNumericString(body.effectiveRootNamespaceRentalFeePerBlock), + UInt64.fromNumericString(body.effectiveChildNamespaceRentalFee), + UInt64.fromNumericString(body.effectiveMosaicRentalFee), + ), + ); } /** @@ -117,8 +119,16 @@ export class NetworkHttp extends Http implements NetworkRepository { * @summary Get transaction fees information */ public getTransactionFees(): Observable { - return this.call(this.networkRoutesApi.getTransactionFees(), (body) => - new TransactionFees(body.averageFeeMultiplier, body.medianFeeMultiplier, body.highestFeeMultiplier, body.lowestFeeMultiplier)); + return this.call( + this.networkRoutesApi.getTransactionFees(), + (body) => + new TransactionFees( + body.averageFeeMultiplier, + body.medianFeeMultiplier, + body.highestFeeMultiplier, + body.lowestFeeMultiplier, + ), + ); } /** @@ -127,35 +137,76 @@ export class NetworkHttp extends Http implements NetworkRepository { */ private mapNetworkConfigurationDto(dto: NetworkConfigurationDTO): NetworkConfiguration { return new NetworkConfiguration( - new NetworkProperties(dto.network.identifier, dto.network.nodeEqualityStrategy, - dto.network.publicKey, dto.network.generationHash, dto.network.epochAdjustment), - new ChainProperties(dto.chain.enableVerifiableState, dto.chain.enableVerifiableReceipts, - dto.chain.currencyMosaicId, dto.chain.harvestingMosaicId, dto.chain.blockGenerationTargetTime, - dto.chain.blockTimeSmoothingFactor, dto.chain.importanceGrouping, dto.chain.importanceActivityPercentage, - dto.chain.maxRollbackBlocks, dto.chain.maxDifficultyBlocks, dto.chain.defaultDynamicFeeMultiplier, - dto.chain.maxTransactionLifetime, dto.chain.maxBlockFutureTime, dto.chain.initialCurrencyAtomicUnits, - dto.chain.maxMosaicAtomicUnits, dto.chain.totalChainImportance, dto.chain.minHarvesterBalance, - dto.chain.maxHarvesterBalance, dto.chain.harvestBeneficiaryPercentage, dto.chain.blockPruneInterval, - dto.chain.maxTransactionsPerBlock), + new NetworkProperties( + dto.network.identifier, + dto.network.nodeEqualityStrategy, + dto.network.publicKey, + dto.network.generationHash, + dto.network.epochAdjustment, + ), + new ChainProperties( + dto.chain.enableVerifiableState, + dto.chain.enableVerifiableReceipts, + dto.chain.currencyMosaicId, + dto.chain.harvestingMosaicId, + dto.chain.blockGenerationTargetTime, + dto.chain.blockTimeSmoothingFactor, + dto.chain.importanceGrouping, + dto.chain.importanceActivityPercentage, + dto.chain.maxRollbackBlocks, + dto.chain.maxDifficultyBlocks, + dto.chain.defaultDynamicFeeMultiplier, + dto.chain.maxTransactionLifetime, + dto.chain.maxBlockFutureTime, + dto.chain.initialCurrencyAtomicUnits, + dto.chain.maxMosaicAtomicUnits, + dto.chain.totalChainImportance, + dto.chain.minHarvesterBalance, + dto.chain.maxHarvesterBalance, + dto.chain.harvestBeneficiaryPercentage, + dto.chain.blockPruneInterval, + dto.chain.maxTransactionsPerBlock, + ), new PluginProperties( new AccountLinkNetworkProperties(dto.plugins.accountlink?.dummy), - new AggregateNetworkProperties(dto.plugins.aggregate?.maxTransactionsPerAggregate, - dto.plugins.aggregate?.maxCosignaturesPerAggregate, dto.plugins.aggregate?.enableStrictCosignatureCheck, - dto.plugins.aggregate?.enableBondedAggregateSupport, dto.plugins.aggregate?.maxBondedTransactionLifetime), + new AggregateNetworkProperties( + dto.plugins.aggregate?.maxTransactionsPerAggregate, + dto.plugins.aggregate?.maxCosignaturesPerAggregate, + dto.plugins.aggregate?.enableStrictCosignatureCheck, + dto.plugins.aggregate?.enableBondedAggregateSupport, + dto.plugins.aggregate?.maxBondedTransactionLifetime, + ), new HashLockNetworkProperties(dto.plugins.lockhash?.lockedFundsPerAggregate, dto.plugins.lockhash?.maxHashLockDuration), - new SecretLockNetworkProperties(dto.plugins.locksecret?.maxSecretLockDuration, dto.plugins.locksecret?.minProofSize, - dto.plugins.locksecret?.maxProofSize), + new SecretLockNetworkProperties( + dto.plugins.locksecret?.maxSecretLockDuration, + dto.plugins.locksecret?.minProofSize, + dto.plugins.locksecret?.maxProofSize, + ), new MetadataNetworkProperties(dto.plugins.metadata?.maxValueSize), - new MosaicNetworkProperties(dto.plugins.mosaic?.maxMosaicsPerAccount, dto.plugins.mosaic?.maxMosaicDuration, - dto.plugins.mosaic?.maxMosaicDivisibility, dto.plugins.mosaic?.mosaicRentalFeeSinkPublicKey, - dto.plugins.mosaic?.mosaicRentalFee), - new MultisigNetworkProperties(dto.plugins.multisig?.maxMultisigDepth, dto.plugins.multisig?.maxCosignatoriesPerAccount, - dto.plugins.multisig?.maxCosignedAccountsPerAccount), - new NamespaceNetworkProperties(dto.plugins.namespace?.maxNameSize, dto.plugins.namespace?.maxChildNamespaces, - dto.plugins.namespace?.maxNamespaceDepth, dto.plugins.namespace?.minNamespaceDuration, - dto.plugins.namespace?.maxNamespaceDuration, dto.plugins.namespace?.namespaceGracePeriodDuration, - dto.plugins.namespace?.reservedRootNamespaceNames, dto.plugins.namespace?.namespaceRentalFeeSinkPublicKey, - dto.plugins.namespace?.rootNamespaceRentalFeePerBlock, dto.plugins.namespace?.childNamespaceRentalFee), + new MosaicNetworkProperties( + dto.plugins.mosaic?.maxMosaicsPerAccount, + dto.plugins.mosaic?.maxMosaicDuration, + dto.plugins.mosaic?.maxMosaicDivisibility, + dto.plugins.mosaic?.mosaicRentalFeeSinkPublicKey, + dto.plugins.mosaic?.mosaicRentalFee, + ), + new MultisigNetworkProperties( + dto.plugins.multisig?.maxMultisigDepth, + dto.plugins.multisig?.maxCosignatoriesPerAccount, + dto.plugins.multisig?.maxCosignedAccountsPerAccount, + ), + new NamespaceNetworkProperties( + dto.plugins.namespace?.maxNameSize, + dto.plugins.namespace?.maxChildNamespaces, + dto.plugins.namespace?.maxNamespaceDepth, + dto.plugins.namespace?.minNamespaceDuration, + dto.plugins.namespace?.maxNamespaceDuration, + dto.plugins.namespace?.namespaceGracePeriodDuration, + dto.plugins.namespace?.reservedRootNamespaceNames, + dto.plugins.namespace?.namespaceRentalFeeSinkPublicKey, + dto.plugins.namespace?.rootNamespaceRentalFeePerBlock, + dto.plugins.namespace?.childNamespaceRentalFee, + ), new AccountRestrictionNetworkProperties(dto.plugins.restrictionaccount?.maxAccountRestrictionValues), new MosaicRestrictionNetworkProperties(dto.plugins.restrictionmosaic?.maxMosaicRestrictionValues), new TransferNetworkProperties(dto.plugins.transfer?.maxMessageSize), diff --git a/src/infrastructure/NetworkRepository.ts b/src/infrastructure/NetworkRepository.ts index 60c3020ff2..e17fc265d3 100644 --- a/src/infrastructure/NetworkRepository.ts +++ b/src/infrastructure/NetworkRepository.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; +import { Observable } from 'rxjs'; import { NetworkConfiguration } from '../model/network/NetworkConfiguration'; import { NetworkName } from '../model/network/NetworkName'; -import {NetworkType} from '../model/network/NetworkType'; +import { NetworkType } from '../model/network/NetworkType'; import { RentalFees } from '../model/network/RentalFees'; import { TransactionFees } from '../model/network/TransactionFees'; @@ -27,7 +27,6 @@ import { TransactionFees } from '../model/network/TransactionFees'; * @since 1.0 */ export interface NetworkRepository { - /** * Get current network type name and description * diff --git a/src/infrastructure/NodeHttp.ts b/src/infrastructure/NodeHttp.ts index db30197731..2b590d947b 100644 --- a/src/infrastructure/NodeHttp.ts +++ b/src/infrastructure/NodeHttp.ts @@ -45,7 +45,6 @@ export class NodeHttp extends Http implements NodeRepository { super(url); this.nodeRoutesApi = new NodeRoutesApi(url); this.nodeRoutesApi.useQuerystring = true; - } /** @@ -69,16 +68,16 @@ export class NodeHttp extends Http implements NodeRepository { * @summary Get the node time */ public getNodeTime(): Observable { - return this.call(this.nodeRoutesApi.getNodeTime(), - (body) => { - const nodeTimeDTO = body; - if (nodeTimeDTO.communicationTimestamps.sendTimestamp && nodeTimeDTO.communicationTimestamps.receiveTimestamp) { - return new NodeTime(UInt64.fromNumericString(nodeTimeDTO.communicationTimestamps.sendTimestamp), - UInt64.fromNumericString(nodeTimeDTO.communicationTimestamps.receiveTimestamp)); - } - throw Error('Node time not available'); - }, - ); + return this.call(this.nodeRoutesApi.getNodeTime(), (body) => { + const nodeTimeDTO = body; + if (nodeTimeDTO.communicationTimestamps.sendTimestamp && nodeTimeDTO.communicationTimestamps.receiveTimestamp) { + return new NodeTime( + UInt64.fromNumericString(nodeTimeDTO.communicationTimestamps.sendTimestamp), + UInt64.fromNumericString(nodeTimeDTO.communicationTimestamps.receiveTimestamp), + ); + } + throw Error('Node time not available'); + }); } /** @@ -88,11 +87,7 @@ export class NodeHttp extends Http implements NodeRepository { public getStorageInfo(): Observable { return this.call( this.nodeRoutesApi.getNodeStorage(), - (body) => new StorageInfo( - body.numBlocks, - body.numTransactions, - body.numAccounts, - ), + (body) => new StorageInfo(body.numBlocks, body.numTransactions, body.numAccounts), ); } @@ -101,7 +96,8 @@ export class NodeHttp extends Http implements NodeRepository { * @returns Observable */ public getServerInfo(): Observable { - return this.call(this.nodeRoutesApi.getServerInfo(), + return this.call( + this.nodeRoutesApi.getServerInfo(), (body) => new ServerInfo(body.serverInfo.restVersion, body.serverInfo.sdkVersion), ); } @@ -111,8 +107,7 @@ export class NodeHttp extends Http implements NodeRepository { * @returns Observable */ public getNodeHealth(): Observable { - return this.call(this.nodeRoutesApi.getNodeHealth(), - (body) => new NodeHealth(body.status.apiNode, body.status.db)); + return this.call(this.nodeRoutesApi.getNodeHealth(), (body) => new NodeHealth(body.status.apiNode, body.status.db)); } /** diff --git a/src/infrastructure/NodeRepository.ts b/src/infrastructure/NodeRepository.ts index f9b372c09a..b39ffeb705 100644 --- a/src/infrastructure/NodeRepository.ts +++ b/src/infrastructure/NodeRepository.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; +import { Observable } from 'rxjs'; import { StorageInfo } from '../model/blockchain/StorageInfo'; import { NodeHealth } from '../model/node/NodeHealth'; import { NodeInfo } from '../model/node/NodeInfo'; @@ -27,7 +27,6 @@ import { ServerInfo } from '../model/node/ServerInfo'; * @since 1.0 */ export interface NodeRepository { - /** * Supplies additional information about the application running on a node. * @summary Get the node information @@ -64,5 +63,4 @@ export interface NodeRepository { * @returns Observable */ getServerInfo(): Observable; - } diff --git a/src/infrastructure/QueryParams.ts b/src/infrastructure/QueryParams.ts index ffd9620ec4..64b175840d 100644 --- a/src/infrastructure/QueryParams.ts +++ b/src/infrastructure/QueryParams.ts @@ -14,11 +14,9 @@ * limitations under the License. */ -import { TransactionType } from '../model/transaction/TransactionType'; - - /** - * @since 0.11.3 - */ +/** + * @since 0.11.3 + */ export enum Order { ASC = 'id', DESC = '-id', @@ -55,15 +53,17 @@ export class QueryParams { * id?: string; * }} configuration arguments */ - constructor(args?: { - pageSize?: number, - order?: Order, - id?: string; - }) { + constructor(args?: { pageSize?: number; order?: Order; id?: string }) { if (args) { - if (args.pageSize) { this.setPageSize(args.pageSize); } - if (args.order) { this.order = args.order; } - if (args.id) { this.id = args.id; } + if (args.pageSize) { + this.setPageSize(args.pageSize); + } + if (args.order) { + this.order = args.order; + } + if (args.id) { + this.id = args.id; + } } } diff --git a/src/infrastructure/ReceiptHttp.ts b/src/infrastructure/ReceiptHttp.ts index bfd20782d7..837850ed8b 100644 --- a/src/infrastructure/ReceiptHttp.ts +++ b/src/infrastructure/ReceiptHttp.ts @@ -67,13 +67,9 @@ export class ReceiptHttp extends Http implements ReceiptRepository { * @return Observable */ public getMerkleReceipts(height: UInt64, hash: string): Observable { - return observableFrom( - this.receiptRoutesApi.getMerkleReceipts(height.toString(), hash)).pipe( - map(({body}) => new MerkleProofInfo( - body.merklePath!.map( - (payload) => new MerklePathItem(payload.position, payload.hash)), - )), - catchError((error) => throwError(this.errorHandling(error))), + return observableFrom(this.receiptRoutesApi.getMerkleReceipts(height.toString(), hash)).pipe( + map(({ body }) => new MerkleProofInfo(body.merklePath!.map((payload) => new MerklePathItem(payload.position, payload.hash)))), + catchError((error) => throwError(this.errorHandling(error))), ); } @@ -85,10 +81,10 @@ export class ReceiptHttp extends Http implements ReceiptRepository { */ public getBlockReceipts(height: UInt64): Observable { return this.networkTypeObservable.pipe( - mergeMap((networkType) => observableFrom( - this.receiptRoutesApi.getBlockReceipts(height.toString())).pipe( - map(({body}) => CreateStatementFromDTO(body, networkType)), - catchError((error) => throwError(this.errorHandling(error))), + mergeMap((networkType) => + observableFrom(this.receiptRoutesApi.getBlockReceipts(height.toString())).pipe( + map(({ body }) => CreateStatementFromDTO(body, networkType)), + catchError((error) => throwError(this.errorHandling(error))), ), ), ); diff --git a/src/infrastructure/ReceiptRepository.ts b/src/infrastructure/ReceiptRepository.ts index 4c0660a63f..0267086b5f 100644 --- a/src/infrastructure/ReceiptRepository.ts +++ b/src/infrastructure/ReceiptRepository.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; +import { Observable } from 'rxjs'; import { MerkleProofInfo } from '../model/blockchain/MerkleProofInfo'; import { Statement } from '../model/receipt/Statement'; import { UInt64 } from '../model/UInt64'; @@ -25,7 +25,6 @@ import { UInt64 } from '../model/UInt64'; * @since 1.0 */ export interface ReceiptRepository { - /** * Get receipts from a block * Returns the receipts linked to a block. diff --git a/src/infrastructure/RepositoryFactory.ts b/src/infrastructure/RepositoryFactory.ts index 877b5265d6..1fabab7dfc 100644 --- a/src/infrastructure/RepositoryFactory.ts +++ b/src/infrastructure/RepositoryFactory.ts @@ -37,7 +37,6 @@ import { TransactionRepository } from './TransactionRepository'; * */ export interface RepositoryFactory { - /** * @returns the network type of the network. This method is cached, the server is only called the * first time. @@ -119,5 +118,4 @@ export interface RepositoryFactory { * @returns a newly create {@link IListener} */ createListener(): IListener; - } diff --git a/src/infrastructure/RepositoryFactoryHttp.ts b/src/infrastructure/RepositoryFactoryHttp.ts index 4d691e5ff0..fa79610e77 100644 --- a/src/infrastructure/RepositoryFactoryHttp.ts +++ b/src/infrastructure/RepositoryFactoryHttp.ts @@ -15,7 +15,7 @@ */ import { Observable, of as observableOf } from 'rxjs'; -import { map, share, shareReplay } from 'rxjs/operators'; +import { map, shareReplay } from 'rxjs/operators'; import { NetworkType } from '../model/network/NetworkType'; import { UInt64 } from '../model/UInt64'; import { AccountHttp } from './AccountHttp'; @@ -53,7 +53,6 @@ import { TransactionRepository } from './TransactionRepository'; * */ export class RepositoryFactoryHttp implements RepositoryFactory { - private readonly url: string; private readonly networkType: Observable; private readonly generationHash: Observable; @@ -67,8 +66,12 @@ export class RepositoryFactoryHttp implements RepositoryFactory { constructor(url: string, networkType?: NetworkType, generationHash?: string) { this.url = url; this.networkType = networkType ? observableOf(networkType) : this.createNetworkRepository().getNetworkType().pipe(shareReplay(1)); - this.generationHash = generationHash ? observableOf(generationHash) : - this.createBlockRepository().getBlockByHeight(UInt64.fromUint(1)).pipe(map((b) => b.generationHash)).pipe(shareReplay(1)); + this.generationHash = generationHash + ? observableOf(generationHash) + : this.createBlockRepository() + .getBlockByHeight(UInt64.fromUint(1)) + .pipe(map((b) => b.generationHash)) + .pipe(shareReplay(1)); } createAccountRepository(): AccountRepository { diff --git a/src/infrastructure/RestrictionAccountHttp.ts b/src/infrastructure/RestrictionAccountHttp.ts index f5918d3e1a..34c22fbf46 100644 --- a/src/infrastructure/RestrictionAccountHttp.ts +++ b/src/infrastructure/RestrictionAccountHttp.ts @@ -50,9 +50,9 @@ export class RestrictionAccountHttp extends Http implements RestrictionAccountRe * @returns Observable */ public getAccountRestrictions(address: Address): Observable { - return observableFrom(this.restrictionAccountRoutesApi.getAccountRestrictions(address.plain())) - .pipe(map(({body}) => DtoMapping.extractAccountRestrictionFromDto(body).accountRestrictions.restrictions), - catchError((error) => throwError(this.errorHandling(error))), + return observableFrom(this.restrictionAccountRoutesApi.getAccountRestrictions(address.plain())).pipe( + map(({ body }) => DtoMapping.extractAccountRestrictionFromDto(body).accountRestrictions.restrictions), + catchError((error) => throwError(this.errorHandling(error))), ); } @@ -65,12 +65,13 @@ export class RestrictionAccountHttp extends Http implements RestrictionAccountRe const accountIds = { addresses: addresses.map((address) => address.plain()), }; - return observableFrom( - this.restrictionAccountRoutesApi.getAccountRestrictionsFromAccounts(accountIds)) - .pipe(map(({body}) => body.map((restriction) => { - return DtoMapping.extractAccountRestrictionFromDto(restriction).accountRestrictions; - })), - catchError((error) => throwError(this.errorHandling(error))), + return observableFrom(this.restrictionAccountRoutesApi.getAccountRestrictionsFromAccounts(accountIds)).pipe( + map(({ body }) => + body.map((restriction) => { + return DtoMapping.extractAccountRestrictionFromDto(restriction).accountRestrictions; + }), + ), + catchError((error) => throwError(this.errorHandling(error))), ); } } diff --git a/src/infrastructure/RestrictionMosaicHttp.ts b/src/infrastructure/RestrictionMosaicHttp.ts index 1758f0dfb2..adfe66bae1 100644 --- a/src/infrastructure/RestrictionMosaicHttp.ts +++ b/src/infrastructure/RestrictionMosaicHttp.ts @@ -16,11 +16,7 @@ import { from as observableFrom, Observable, throwError } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; -import { - MosaicAddressRestrictionDTO, - MosaicGlobalRestrictionDTO, - RestrictionMosaicRoutesApi, -} from 'symbol-openapi-typescript-node-client'; +import { MosaicAddressRestrictionDTO, MosaicGlobalRestrictionDTO, RestrictionMosaicRoutesApi } from 'symbol-openapi-typescript-node-client'; import { Address } from '../model/account/Address'; import { MosaicId } from '../model/mosaic/MosaicId'; import { MosaicAddressRestriction } from '../model/restriction/MosaicAddressRestriction'; @@ -49,7 +45,6 @@ export class RestrictionMosaicHttp extends Http implements RestrictionMosaicRepo super(url); this.restrictionMosaicRoutesApi = new RestrictionMosaicRoutesApi(url); this.restrictionMosaicRoutesApi.useQuerystring = true; - } /** @@ -60,10 +55,9 @@ export class RestrictionMosaicHttp extends Http implements RestrictionMosaicRepo * @returns Observable */ getMosaicAddressRestriction(mosaicId: MosaicId, address: Address): Observable { - return observableFrom( - this.restrictionMosaicRoutesApi.getMosaicAddressRestriction(mosaicId.toHex(), address.plain())).pipe( - map(({body}) => this.toMosaicAddressRestriction(body)), - catchError((error) => throwError(this.errorHandling(error))), + return observableFrom(this.restrictionMosaicRoutesApi.getMosaicAddressRestriction(mosaicId.toHex(), address.plain())).pipe( + map(({ body }) => this.toMosaicAddressRestriction(body)), + catchError((error) => throwError(this.errorHandling(error))), ); } @@ -78,10 +72,9 @@ export class RestrictionMosaicHttp extends Http implements RestrictionMosaicRepo const accountIds = { addresses: addresses.map((address) => address.plain()), }; - return observableFrom( - this.restrictionMosaicRoutesApi.getMosaicAddressRestrictions(mosaicId.toHex(), accountIds)).pipe( - map(({body}) => body.map(this.toMosaicAddressRestriction)), - catchError((error) => throwError(this.errorHandling(error))), + return observableFrom(this.restrictionMosaicRoutesApi.getMosaicAddressRestrictions(mosaicId.toHex(), accountIds)).pipe( + map(({ body }) => body.map(this.toMosaicAddressRestriction)), + catchError((error) => throwError(this.errorHandling(error))), ); } @@ -113,10 +106,9 @@ export class RestrictionMosaicHttp extends Http implements RestrictionMosaicRepo * @returns Observable */ getMosaicGlobalRestriction(mosaicId: MosaicId): Observable { - return observableFrom( - this.restrictionMosaicRoutesApi.getMosaicGlobalRestriction(mosaicId.toHex())).pipe( - map(({body}) => this.toMosaicGlobalRestriction(body)), - catchError((error) => throwError(this.errorHandling(error))), + return observableFrom(this.restrictionMosaicRoutesApi.getMosaicGlobalRestriction(mosaicId.toHex())).pipe( + map(({ body }) => this.toMosaicGlobalRestriction(body)), + catchError((error) => throwError(this.errorHandling(error))), ); } @@ -130,10 +122,9 @@ export class RestrictionMosaicHttp extends Http implements RestrictionMosaicRepo const mosaicIdsBody = { mosaicIds: mosaicIds.map((id) => id.toHex()), }; - return observableFrom( - this.restrictionMosaicRoutesApi.getMosaicGlobalRestrictions(mosaicIdsBody)).pipe( - map(({body}) => body.map(this.toMosaicGlobalRestriction)), - catchError((error) => throwError(this.errorHandling(error))), + return observableFrom(this.restrictionMosaicRoutesApi.getMosaicGlobalRestrictions(mosaicIdsBody)).pipe( + map(({ body }) => body.map(this.toMosaicGlobalRestriction)), + catchError((error) => throwError(this.errorHandling(error))), ); } @@ -147,12 +138,15 @@ export class RestrictionMosaicHttp extends Http implements RestrictionMosaicRepo private toMosaicGlobalRestriction(dto: MosaicGlobalRestrictionDTO): MosaicGlobalRestriction { const restirctionItems = new Map(); dto.mosaicRestrictionEntry.restrictions.forEach((restriction) => - restirctionItems.set(restriction.key, + restirctionItems.set( + restriction.key, new MosaicGlobalRestrictionItem( new MosaicId(restriction.restriction.referenceMosaicId), restriction.restriction.restrictionValue, restriction.restriction.restrictionType.valueOf(), - ))); + ), + ), + ); return new MosaicGlobalRestriction( dto.mosaicRestrictionEntry.compositeHash, dto.mosaicRestrictionEntry.entryType.valueOf(), diff --git a/src/infrastructure/TransactionFilter.ts b/src/infrastructure/TransactionFilter.ts index 8bd726e68d..a7f5206080 100644 --- a/src/infrastructure/TransactionFilter.ts +++ b/src/infrastructure/TransactionFilter.ts @@ -31,10 +31,10 @@ export class TransactionFilter { * type: TransactionType[], * }} [args] */ - constructor(args?: { - types?: TransactionType[], - }) { - if (args && args.types) { this.types = args.types; } + constructor(args?: { types?: TransactionType[] }) { + if (args && args.types) { + this.types = args.types; + } } /** diff --git a/src/infrastructure/TransactionHttp.ts b/src/infrastructure/TransactionHttp.ts index ac8ee7c0f6..846bd49f50 100644 --- a/src/infrastructure/TransactionHttp.ts +++ b/src/infrastructure/TransactionHttp.ts @@ -68,7 +68,7 @@ export class TransactionHttp extends Http implements TransactionRepository { */ public getTransaction(transactionId: string): Observable { return observableFrom(this.transactionRoutesApi.getTransaction(transactionId)).pipe( - map(({body}) => CreateTransactionFromDTO(body)), + map(({ body }) => CreateTransactionFromDTO(body)), catchError((error) => throwError(this.errorHandling(error))), ); } @@ -82,11 +82,12 @@ export class TransactionHttp extends Http implements TransactionRepository { const transactionIdsBody = { transactionIds, }; - return observableFrom( - this.transactionRoutesApi.getTransactions(transactionIdsBody)).pipe( - map(({body}) => body.map((transactionDTO) => { - return CreateTransactionFromDTO(transactionDTO); - })), + return observableFrom(this.transactionRoutesApi.getTransactions(transactionIdsBody)).pipe( + map(({ body }) => + body.map((transactionDTO) => { + return CreateTransactionFromDTO(transactionDTO); + }), + ), catchError((error) => throwError(this.errorHandling(error))), ); } @@ -98,7 +99,7 @@ export class TransactionHttp extends Http implements TransactionRepository { */ public getTransactionStatus(transactionHash: string): Observable { return observableFrom(this.transactionRoutesApi.getTransactionStatus(transactionHash)).pipe( - map(({body}) => this.toTransactionStatus(body)), + map(({ body }) => this.toTransactionStatus(body)), catchError((error) => throwError(this.errorHandling(error))), ); } @@ -112,9 +113,8 @@ export class TransactionHttp extends Http implements TransactionRepository { const transactionHashesBody = { hashes: transactionHashes, }; - return observableFrom( - this.transactionRoutesApi.getTransactionsStatuses(transactionHashesBody)).pipe( - map(({body}) => body.map(this.toTransactionStatus)), + return observableFrom(this.transactionRoutesApi.getTransactionsStatuses(transactionHashesBody)).pipe( + map(({ body }) => body.map(this.toTransactionStatus)), catchError((error) => throwError(this.errorHandling(error))), ); } @@ -132,7 +132,8 @@ export class TransactionHttp extends Http implements TransactionRepository { dto.hash, Deadline.createFromDTO(UInt64.fromNumericString(dto.deadline).toDTO()), dto.code, - dto.height ? UInt64.fromNumericString(dto.height) : undefined); + dto.height ? UInt64.fromNumericString(dto.height) : undefined, + ); } /** @@ -142,10 +143,10 @@ export class TransactionHttp extends Http implements TransactionRepository { */ public announce(signedTransaction: SignedTransaction): Observable { if (signedTransaction.type === TransactionType.AGGREGATE_BONDED) { - throw new Error('Announcing aggregate bonded transaction should use \'announceAggregateBonded\''); + throw new Error("Announcing aggregate bonded transaction should use 'announceAggregateBonded'"); } return observableFrom(this.transactionRoutesApi.announceTransaction(signedTransaction)).pipe( - map(({body}) => new TransactionAnnounceResponse(body.message)), + map(({ body }) => new TransactionAnnounceResponse(body.message)), catchError((error) => throwError(this.errorHandling(error))), ); } @@ -160,7 +161,7 @@ export class TransactionHttp extends Http implements TransactionRepository { throw new Error('Only Transaction Type 0x4241 is allowed for announce aggregate bonded'); } return observableFrom(this.transactionRoutesApi.announcePartialTransaction(signedTransaction)).pipe( - map(({body}) => new TransactionAnnounceResponse(body.message)), + map(({ body }) => new TransactionAnnounceResponse(body.message)), catchError((error) => throwError(this.errorHandling(error))), ); } @@ -171,9 +172,10 @@ export class TransactionHttp extends Http implements TransactionRepository { * @returns Observable */ public announceAggregateBondedCosignature( - cosignatureSignedTransaction: CosignatureSignedTransaction): Observable { + cosignatureSignedTransaction: CosignatureSignedTransaction, + ): Observable { return observableFrom(this.transactionRoutesApi.announceCosignatureTransaction(cosignatureSignedTransaction)).pipe( - map(({body}) => new TransactionAnnounceResponse(body.message)), + map(({ body }) => new TransactionAnnounceResponse(body.message)), catchError((error) => throwError(this.errorHandling(error))), ); } @@ -185,22 +187,25 @@ export class TransactionHttp extends Http implements TransactionRepository { */ public getTransactionEffectiveFee(transactionId: string): Observable { return observableFrom(this.transactionRoutesApi.getTransaction(transactionId)).pipe( - mergeMap(({body}) => { + mergeMap(({ body }) => { // parse transaction to take advantage of `size` getter overload const transaction = CreateTransactionFromDTO(body); const uintHeight = (transaction.transactionInfo as TransactionInfo).height; // now read block details return observableFrom(this.blockRoutesApi.getBlockByHeight(uintHeight.toString())).pipe( - map((blockResponse: { response: ClientResponse; body: BlockInfoDTO; }) => { + map((blockResponse: { response: ClientResponse; body: BlockInfoDTO }) => { const blockDTO = blockResponse.body; // @see https://nemtech.github.io/concepts/transaction.html#fees // effective_fee = feeMultiplier x transaction::size return blockDTO.block.feeMultiplier * transaction.size; }), - catchError((error) => throwError(this.errorHandling(error)))); - }), catchError((err) => { + catchError((error) => throwError(this.errorHandling(error))), + ); + }), + catchError((err) => { return throwError(err); - })); + }), + ); } } diff --git a/src/infrastructure/TransactionRepository.ts b/src/infrastructure/TransactionRepository.ts index 8effe51382..8659a5313b 100644 --- a/src/infrastructure/TransactionRepository.ts +++ b/src/infrastructure/TransactionRepository.ts @@ -14,12 +14,12 @@ * limitations under the License. */ -import {Observable} from 'rxjs'; -import {CosignatureSignedTransaction} from '../model/transaction/CosignatureSignedTransaction'; -import {SignedTransaction} from '../model/transaction/SignedTransaction'; -import {Transaction} from '../model/transaction/Transaction'; -import {TransactionAnnounceResponse} from '../model/transaction/TransactionAnnounceResponse'; -import {TransactionStatus} from '../model/transaction/TransactionStatus'; +import { Observable } from 'rxjs'; +import { CosignatureSignedTransaction } from '../model/transaction/CosignatureSignedTransaction'; +import { SignedTransaction } from '../model/transaction/SignedTransaction'; +import { Transaction } from '../model/transaction/Transaction'; +import { TransactionAnnounceResponse } from '../model/transaction/TransactionAnnounceResponse'; +import { TransactionStatus } from '../model/transaction/TransactionStatus'; /** * Transaction interface repository. @@ -27,7 +27,6 @@ import {TransactionStatus} from '../model/transaction/TransactionStatus'; * @since 1.0 */ export interface TransactionRepository { - /** * Gets a transaction for a transactionId * @param transactionId - Transaction id or hash. diff --git a/src/infrastructure/receipt/CreateReceiptFromDTO.ts b/src/infrastructure/receipt/CreateReceiptFromDTO.ts index 6c564bbbac..0129f6e026 100644 --- a/src/infrastructure/receipt/CreateReceiptFromDTO.ts +++ b/src/infrastructure/receipt/CreateReceiptFromDTO.ts @@ -16,8 +16,8 @@ import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; import { Address } from '../../model/account/Address'; -import {PublicAccount} from '../../model/account/PublicAccount'; -import {MosaicId} from '../../model/mosaic/MosaicId'; +import { PublicAccount } from '../../model/account/PublicAccount'; +import { MosaicId } from '../../model/mosaic/MosaicId'; import { NamespaceId } from '../../model/namespace/NamespaceId'; import { ArtifactExpiryReceipt } from '../../model/receipt/ArtifactExpiryReceipt'; import { BalanceChangeReceipt } from '../../model/receipt/BalanceChangeReceipt'; @@ -31,17 +31,18 @@ import { ResolutionStatement } from '../../model/receipt/ResolutionStatement'; import { ResolutionType } from '../../model/receipt/ResolutionType'; import { Statement } from '../../model/receipt/Statement'; import { TransactionStatement } from '../../model/receipt/TransactionStatement'; -import {UInt64} from '../../model/UInt64'; +import { UInt64 } from '../../model/UInt64'; /** * @interal * @param unresolvedAddress unresolved address * @returns {Address | NamespaceId} */ -const extractUnresolvedAddress = (unresolvedAddress: any): Address | NamespaceId => { +const extractUnresolvedAddress = (unresolvedAddress: any): Address | NamespaceId => { if (typeof unresolvedAddress === 'string') { return UnresolvedMapping.toUnresolvedAddress(unresolvedAddress); - } else if (typeof unresolvedAddress === 'object') { // Is JSON object + } else if (typeof unresolvedAddress === 'object') { + // Is JSON object if (unresolvedAddress.hasOwnProperty('address')) { return Address.createFromRawAddress(unresolvedAddress.address); } else if (unresolvedAddress.hasOwnProperty('id')) { @@ -66,8 +67,10 @@ const createResolutionStatement = (statementDTO, resolutionType): ResolutionStat UInt64.fromNumericString(statementDTO.height), extractUnresolvedAddress(statementDTO.unresolved), statementDTO.resolutionEntries.map((entry) => { - return new ResolutionEntry(Address.createFromEncoded(entry.resolved), - new ReceiptSource(entry.source.primaryId, entry.source.secondaryId)); + return new ResolutionEntry( + Address.createFromEncoded(entry.resolved), + new ReceiptSource(entry.source.primaryId, entry.source.secondaryId), + ); }), ); case ResolutionType.Mosaic: @@ -76,12 +79,14 @@ const createResolutionStatement = (statementDTO, resolutionType): ResolutionStat UInt64.fromNumericString(statementDTO.height), UnresolvedMapping.toUnresolvedMosaic(statementDTO.unresolved), statementDTO.resolutionEntries.map((entry) => { - return new ResolutionEntry(new MosaicId(entry.resolved), - new ReceiptSource(entry.source.primaryId, entry.source.secondaryId)); + return new ResolutionEntry( + new MosaicId(entry.resolved), + new ReceiptSource(entry.source.primaryId, entry.source.secondaryId), + ); }), ); default: - throw new Error ('Resolution type invalid'); + throw new Error('Resolution type invalid'); } }; @@ -145,11 +150,7 @@ const extractArtifactId = (receiptType: ReceiptType, id: string): MosaicId | Nam * @constructor */ const createArtifactExpiryReceipt = (receiptDTO): Receipt => { - return new ArtifactExpiryReceipt( - extractArtifactId(receiptDTO.type, receiptDTO.artifactId), - receiptDTO.version, - receiptDTO.type, - ); + return new ArtifactExpiryReceipt(extractArtifactId(receiptDTO.type, receiptDTO.artifactId), receiptDTO.version, receiptDTO.type); }; /** @@ -190,7 +191,7 @@ export const CreateReceiptFromDTO = (receiptDTO, networkType): Receipt => { case ReceiptType.Mosaic_Expired: case ReceiptType.Namespace_Expired: case ReceiptType.Namespace_Deleted: - return createArtifactExpiryReceipt(receiptDTO); + return createArtifactExpiryReceipt(receiptDTO); case ReceiptType.Inflation: return createInflationReceipt(receiptDTO); default: diff --git a/src/infrastructure/transaction/CreateTransactionFromDTO.ts b/src/infrastructure/transaction/CreateTransactionFromDTO.ts index 4bcf4ae50a..a7280f4ffc 100644 --- a/src/infrastructure/transaction/CreateTransactionFromDTO.ts +++ b/src/infrastructure/transaction/CreateTransactionFromDTO.ts @@ -55,64 +55,68 @@ import { TransactionType } from '../../model/transaction/TransactionType'; import { TransferTransaction } from '../../model/transaction/TransferTransaction'; import { UInt64 } from '../../model/UInt64'; -// tslint:disable: no-use-before-declare /** - * @internal - * @param transactionDTO - * @returns {Transaction} - * @constructor + * Extract recipientAddress value from encoded hexadecimal notation. + * + * If bit 0 of byte 0 is not set (e.g. 0x90), then it is a regular address. + * Else (e.g. 0x91) it represents a namespace id which starts at byte 1. + * + * @param recipientAddress {string} Encoded hexadecimal recipientAddress notation + * @return {Address | NamespaceId} */ -export const CreateTransactionFromDTO = (transactionDTO): Transaction => { - if (transactionDTO.transaction.type === TransactionType.AGGREGATE_COMPLETE || - transactionDTO.transaction.type === TransactionType.AGGREGATE_BONDED) { - const innerTransactions = transactionDTO.transaction.transactions.map((innerTransactionDTO) => { - const aggregateTransactionInfo = innerTransactionDTO.meta ? new AggregateTransactionInfo( - UInt64.fromNumericString(innerTransactionDTO.meta.height), - innerTransactionDTO.meta.index, - innerTransactionDTO.meta.id, - innerTransactionDTO.meta.aggregateHash, - innerTransactionDTO.meta.aggregateId, - ) : undefined; - innerTransactionDTO.transaction.maxFee = transactionDTO.transaction.maxFee; - innerTransactionDTO.transaction.deadline = transactionDTO.transaction.deadline; - innerTransactionDTO.transaction.signature = transactionDTO.transaction.signature; - return CreateStandaloneTransactionFromDTO(innerTransactionDTO.transaction, aggregateTransactionInfo); - }); - return new AggregateTransaction( - transactionDTO.transaction.network, - transactionDTO.transaction.type, - transactionDTO.transaction.version, - Deadline.createFromDTO(transactionDTO.transaction.deadline), - UInt64.fromNumericString(transactionDTO.transaction.maxFee || '0'), - innerTransactions, - transactionDTO.transaction.cosignatures ? transactionDTO.transaction.cosignatures - .map((aggregateCosignatureDTO) => { - return new AggregateTransactionCosignature( - aggregateCosignatureDTO.signature, - PublicAccount.createFromPublicKey(aggregateCosignatureDTO.signerPublicKey, - transactionDTO.transaction.network)); - }) : [], - transactionDTO.transaction.signature, - transactionDTO.transaction.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.transaction.signerPublicKey, - transactionDTO.transaction.network) : undefined, - transactionDTO.meta ? new TransactionInfo( - UInt64.fromNumericString(transactionDTO.meta.height), - transactionDTO.meta.index, - transactionDTO.meta.id, - transactionDTO.meta.hash, - transactionDTO.meta.merkleComponentHash, - ) : undefined, - ); - } else { - const transactionInfo = transactionDTO.meta ? new TransactionInfo( - UInt64.fromNumericString(transactionDTO.meta.height), - transactionDTO.meta.index, - transactionDTO.meta.id, - transactionDTO.meta.hash, - transactionDTO.meta.merkleComponentHash, - ) : undefined; - return CreateStandaloneTransactionFromDTO(transactionDTO.transaction, transactionInfo); +export const extractRecipient = (recipientAddress: any): Address | NamespaceId => { + if (typeof recipientAddress === 'string') { + return UnresolvedMapping.toUnresolvedAddress(recipientAddress); + } else if (typeof recipientAddress === 'object') { + // Is JSON object + if (recipientAddress.hasOwnProperty('address')) { + return Address.createFromRawAddress(recipientAddress.address); + } else if (recipientAddress.hasOwnProperty('id')) { + return NamespaceId.createFromEncoded(recipientAddress.id); + } + } + throw new Error(`Recipient: ${recipientAddress} type is not recognised`); +}; + +/** + * Extract mosaics from encoded UInt64 notation. + * + * If most significant bit of byte 0 is set, then it is a namespaceId. + * If most significant bit of byte 0 is not set, then it is a mosaicId. + * + * @param mosaics {Array | undefined} The DTO array of mosaics (with UInt64 Id notation) + * @return {Mosaic[]} + */ +export const extractMosaics = (mosaics: any): Mosaic[] => { + if (mosaics === undefined) { + return []; + } + return mosaics.map((mosaicDTO) => { + const id = UnresolvedMapping.toUnresolvedMosaic(mosaicDTO.id); + return new Mosaic(id, UInt64.fromNumericString(mosaicDTO.amount)); + }); +}; + +/** + * Extract message from either JSON payload (unencoded) or DTO (encoded) + * + * @param message - message payload + * @return {PlainMessage} + */ +const extractMessage = (message: any): PlainMessage | EncryptedMessage => { + let msgObj = EmptyMessage; + if (message) { + if (message.type === MessageType.PlainMessage) { + msgObj = convert.isHexString(message.payload) + ? PlainMessage.createFromPayload(message.payload) + : PlainMessage.create(message.payload); + } else if (message.type === MessageType.EncryptedMessage) { + msgObj = EncryptedMessage.createFromPayload(message.payload); + } else if (message.type === MessageType.PersistentHarvestingDelegationMessage) { + msgObj = PersistentHarvestingDelegationMessage.createFromPayload(message.payload); + } } + return msgObj; }; /** @@ -123,7 +127,6 @@ export const CreateTransactionFromDTO = (transactionDTO): Transaction => { * @constructor */ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Transaction => { - if (transactionDTO.type === TransactionType.TRANSFER) { return new TransferTransaction( transactionDTO.network, @@ -134,8 +137,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr extractMosaics(transactionDTO.mosaics), extractMessage(transactionDTO.message !== undefined ? transactionDTO.message : undefined), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.NAMESPACE_REGISTRATION) { @@ -150,8 +154,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.registrationType === 0 ? UInt64.fromNumericString(transactionDTO.duration) : undefined, transactionDTO.registrationType === 1 ? NamespaceId.createFromEncoded(transactionDTO.parentId) : undefined, transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.MOSAIC_DEFINITION) { @@ -166,8 +171,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.divisibility, UInt64.fromNumericString(transactionDTO.duration), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.MOSAIC_SUPPLY_CHANGE) { @@ -180,8 +186,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.action, UInt64.fromNumericString(transactionDTO.delta), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.MULTISIG_ACCOUNT_MODIFICATION) { @@ -192,13 +199,16 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr UInt64.fromNumericString(transactionDTO.maxFee || '0'), transactionDTO.minApprovalDelta, transactionDTO.minRemovalDelta, - transactionDTO.publicKeyAdditions ? transactionDTO.publicKeyAdditions.map((addition) => - PublicAccount.createFromPublicKey(addition, transactionDTO.network)) : [], - transactionDTO.publicKeyDeletions ? transactionDTO.publicKeyDeletions.map((deletion) => - PublicAccount.createFromPublicKey(deletion, transactionDTO.network)) : [], + transactionDTO.publicKeyAdditions + ? transactionDTO.publicKeyAdditions.map((addition) => PublicAccount.createFromPublicKey(addition, transactionDTO.network)) + : [], + transactionDTO.publicKeyDeletions + ? transactionDTO.publicKeyDeletions.map((deletion) => PublicAccount.createFromPublicKey(deletion, transactionDTO.network)) + : [], transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.HASH_LOCK) { @@ -229,8 +239,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.secret, extractRecipient(recipientAddress), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.SECRET_PROOF) { @@ -245,8 +256,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr extractRecipient(recipientAddress), transactionDTO.proof, transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.MOSAIC_ALIAS) { @@ -259,8 +271,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr NamespaceId.createFromEncoded(transactionDTO.namespaceId), new MosaicId(transactionDTO.mosaicId), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.ADDRESS_ALIAS) { @@ -273,8 +286,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr NamespaceId.createFromEncoded(transactionDTO.namespaceId), extractRecipient(transactionDTO.address) as Address, transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.ACCOUNT_ADDRESS_RESTRICTION) { @@ -284,13 +298,12 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr Deadline.createFromDTO(transactionDTO.deadline), UInt64.fromNumericString(transactionDTO.maxFee || '0'), transactionDTO.restrictionFlags, - transactionDTO.restrictionAdditions ? transactionDTO.restrictionAdditions.map((addition) => - extractRecipient(addition)) : [], - transactionDTO.restrictionDeletions ? transactionDTO.restrictionDeletions.map((deletion) => - extractRecipient(deletion)) : [], + transactionDTO.restrictionAdditions ? transactionDTO.restrictionAdditions.map((addition) => extractRecipient(addition)) : [], + transactionDTO.restrictionDeletions ? transactionDTO.restrictionDeletions.map((deletion) => extractRecipient(deletion)) : [], transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.ACCOUNT_OPERATION_RESTRICTION) { @@ -303,8 +316,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.restrictionAdditions ? transactionDTO.restrictionAdditions : [], transactionDTO.restrictionDeletions ? transactionDTO.restrictionDeletions : [], transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.ACCOUNT_MOSAIC_RESTRICTION) { @@ -314,13 +328,16 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr Deadline.createFromDTO(transactionDTO.deadline), UInt64.fromNumericString(transactionDTO.maxFee || '0'), transactionDTO.restrictionFlags, - transactionDTO.restrictionAdditions ? transactionDTO.restrictionAdditions.map((addition) => - UnresolvedMapping.toUnresolvedMosaic(addition)) : [], - transactionDTO.restrictionDeletions ? transactionDTO.restrictionDeletions.map((deletion) => - UnresolvedMapping.toUnresolvedMosaic(deletion)) : [], + transactionDTO.restrictionAdditions + ? transactionDTO.restrictionAdditions.map((addition) => UnresolvedMapping.toUnresolvedMosaic(addition)) + : [], + transactionDTO.restrictionDeletions + ? transactionDTO.restrictionDeletions.map((deletion) => UnresolvedMapping.toUnresolvedMosaic(deletion)) + : [], transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.ACCOUNT_LINK) { @@ -332,8 +349,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.remotePublicKey, transactionDTO.linkAction, transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.MOSAIC_GLOBAL_RESTRICTION) { @@ -350,8 +368,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr UInt64.fromNumericString(transactionDTO.newRestrictionValue), transactionDTO.newRestrictionType, transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.MOSAIC_ADDRESS_RESTRICTION) { @@ -366,8 +385,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr UInt64.fromNumericString(transactionDTO.previousRestrictionValue), UInt64.fromNumericString(transactionDTO.newRestrictionValue), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.ACCOUNT_METADATA) { @@ -381,8 +401,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.valueSizeDelta, convert.decodeHex(transactionDTO.value), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.MOSAIC_METADATA) { @@ -397,8 +418,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.valueSizeDelta, convert.decodeHex(transactionDTO.value), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } else if (transactionDTO.type === TransactionType.NAMESPACE_METADATA) { @@ -413,8 +435,9 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr transactionDTO.valueSizeDelta, convert.decodeHex(transactionDTO.value), transactionDTO.signature, - transactionDTO.signerPublicKey ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, - transactionDTO.network) : undefined, + transactionDTO.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.signerPublicKey, transactionDTO.network) + : undefined, transactionInfo, ); } @@ -422,63 +445,70 @@ const CreateStandaloneTransactionFromDTO = (transactionDTO, transactionInfo): Tr }; /** - * Extract recipientAddress value from encoded hexadecimal notation. - * - * If bit 0 of byte 0 is not set (e.g. 0x90), then it is a regular address. - * Else (e.g. 0x91) it represents a namespace id which starts at byte 1. - * - * @param recipientAddress {string} Encoded hexadecimal recipientAddress notation - * @return {Address | NamespaceId} - */ -export const extractRecipient = (recipientAddress: any): Address | NamespaceId => { - if (typeof recipientAddress === 'string') { - return UnresolvedMapping.toUnresolvedAddress(recipientAddress); - } else if (typeof recipientAddress === 'object') { // Is JSON object - if (recipientAddress.hasOwnProperty('address')) { - return Address.createFromRawAddress(recipientAddress.address); - } else if (recipientAddress.hasOwnProperty('id')) { - return NamespaceId.createFromEncoded(recipientAddress.id); - } - } - throw new Error(`Recipient: ${recipientAddress} type is not recognised`); -}; - -/** - * Extract mosaics from encoded UInt64 notation. - * - * If most significant bit of byte 0 is set, then it is a namespaceId. - * If most significant bit of byte 0 is not set, then it is a mosaicId. - * - * @param mosaics {Array | undefined} The DTO array of mosaics (with UInt64 Id notation) - * @return {Mosaic[]} - */ -export const extractMosaics = (mosaics: any): Mosaic[] => { - if (mosaics === undefined) { - return []; - } - return mosaics.map((mosaicDTO) => { - const id = UnresolvedMapping.toUnresolvedMosaic(mosaicDTO.id); - return new Mosaic(id, UInt64.fromNumericString(mosaicDTO.amount)); - }); -}; - -/** - * Extract message from either JSON payload (unencoded) or DTO (encoded) - * - * @param message - message payload - * @return {PlainMessage} + * @internal + * @param transactionDTO + * @returns {Transaction} + * @constructor */ -const extractMessage = (message: any): PlainMessage | EncryptedMessage => { - let msgObj = EmptyMessage; - if (message) { - if (message.type === MessageType.PlainMessage) { - msgObj = convert.isHexString(message.payload) ? PlainMessage.createFromPayload(message.payload) : - PlainMessage.create(message.payload); - } else if (message.type === MessageType.EncryptedMessage) { - msgObj = EncryptedMessage.createFromPayload(message.payload); - } else if (message.type === MessageType.PersistentHarvestingDelegationMessage) { - msgObj = PersistentHarvestingDelegationMessage.createFromPayload(message.payload); - } +export const CreateTransactionFromDTO = (transactionDTO): Transaction => { + if ( + transactionDTO.transaction.type === TransactionType.AGGREGATE_COMPLETE || + transactionDTO.transaction.type === TransactionType.AGGREGATE_BONDED + ) { + const innerTransactions = transactionDTO.transaction.transactions.map((innerTransactionDTO) => { + const aggregateTransactionInfo = innerTransactionDTO.meta + ? new AggregateTransactionInfo( + UInt64.fromNumericString(innerTransactionDTO.meta.height), + innerTransactionDTO.meta.index, + innerTransactionDTO.meta.id, + innerTransactionDTO.meta.aggregateHash, + innerTransactionDTO.meta.aggregateId, + ) + : undefined; + innerTransactionDTO.transaction.maxFee = transactionDTO.transaction.maxFee; + innerTransactionDTO.transaction.deadline = transactionDTO.transaction.deadline; + innerTransactionDTO.transaction.signature = transactionDTO.transaction.signature; + return CreateStandaloneTransactionFromDTO(innerTransactionDTO.transaction, aggregateTransactionInfo); + }); + return new AggregateTransaction( + transactionDTO.transaction.network, + transactionDTO.transaction.type, + transactionDTO.transaction.version, + Deadline.createFromDTO(transactionDTO.transaction.deadline), + UInt64.fromNumericString(transactionDTO.transaction.maxFee || '0'), + innerTransactions, + transactionDTO.transaction.cosignatures + ? transactionDTO.transaction.cosignatures.map((aggregateCosignatureDTO) => { + return new AggregateTransactionCosignature( + aggregateCosignatureDTO.signature, + PublicAccount.createFromPublicKey(aggregateCosignatureDTO.signerPublicKey, transactionDTO.transaction.network), + ); + }) + : [], + transactionDTO.transaction.signature, + transactionDTO.transaction.signerPublicKey + ? PublicAccount.createFromPublicKey(transactionDTO.transaction.signerPublicKey, transactionDTO.transaction.network) + : undefined, + transactionDTO.meta + ? new TransactionInfo( + UInt64.fromNumericString(transactionDTO.meta.height), + transactionDTO.meta.index, + transactionDTO.meta.id, + transactionDTO.meta.hash, + transactionDTO.meta.merkleComponentHash, + ) + : undefined, + ); + } else { + const transactionInfo = transactionDTO.meta + ? new TransactionInfo( + UInt64.fromNumericString(transactionDTO.meta.height), + transactionDTO.meta.index, + transactionDTO.meta.id, + transactionDTO.meta.hash, + transactionDTO.meta.merkleComponentHash, + ) + : undefined; + return CreateStandaloneTransactionFromDTO(transactionDTO.transaction, transactionInfo); } - return msgObj; }; diff --git a/src/infrastructure/transaction/CreateTransactionFromPayload.ts b/src/infrastructure/transaction/CreateTransactionFromPayload.ts index 6efcba07f2..99c6f2aac2 100644 --- a/src/infrastructure/transaction/CreateTransactionFromPayload.ts +++ b/src/infrastructure/transaction/CreateTransactionFromPayload.ts @@ -47,24 +47,18 @@ import { TransferTransaction } from '../../model/transaction/TransferTransaction * @returns {Transaction | InnerTransaction} * @constructor */ -export const CreateTransactionFromPayload = (payload: string, - isEmbedded = false): Transaction | InnerTransaction => { - const transactionBuilder = isEmbedded ? EmbeddedTransactionBuilder.loadFromBinary(convert.hexToUint8(payload)) : - TransactionBuilder.loadFromBinary(convert.hexToUint8(payload)); +export const CreateTransactionFromPayload = (payload: string, isEmbedded = false): Transaction | InnerTransaction => { + const transactionBuilder = isEmbedded + ? EmbeddedTransactionBuilder.loadFromBinary(convert.hexToUint8(payload)) + : TransactionBuilder.loadFromBinary(convert.hexToUint8(payload)); const type = transactionBuilder.getType().valueOf(); switch (type) { case TransactionType.ACCOUNT_ADDRESS_RESTRICTION: - case TransactionType.ACCOUNT_OPERATION_RESTRICTION: + return AccountAddressRestrictionTransaction.createFromPayload(payload, isEmbedded); case TransactionType.ACCOUNT_MOSAIC_RESTRICTION: - switch (type) { - case TransactionType.ACCOUNT_ADDRESS_RESTRICTION: - return AccountAddressRestrictionTransaction.createFromPayload(payload, isEmbedded); - case TransactionType.ACCOUNT_MOSAIC_RESTRICTION: - return AccountMosaicRestrictionTransaction.createFromPayload(payload, isEmbedded); - case TransactionType.ACCOUNT_OPERATION_RESTRICTION: - return AccountOperationRestrictionTransaction.createFromPayload(payload, isEmbedded); - } - throw new Error ('Account restriction transaction type not recognised.'); + return AccountMosaicRestrictionTransaction.createFromPayload(payload, isEmbedded); + case TransactionType.ACCOUNT_OPERATION_RESTRICTION: + return AccountOperationRestrictionTransaction.createFromPayload(payload, isEmbedded); case TransactionType.ACCOUNT_LINK: return AccountLinkTransaction.createFromPayload(payload, isEmbedded); case TransactionType.ADDRESS_ALIAS: @@ -101,6 +95,6 @@ export const CreateTransactionFromPayload = (payload: string, case TransactionType.AGGREGATE_BONDED: return AggregateTransaction.createFromPayload(payload); default: - throw new Error ('Transaction type not implemented yet.'); - } + throw new Error('Transaction type not implemented yet.'); + } }; diff --git a/src/infrastructure/transaction/NamespaceMosaicIdGenerator.ts b/src/infrastructure/transaction/NamespaceMosaicIdGenerator.ts index 930ec1b14d..c70bc0fc7f 100644 --- a/src/infrastructure/transaction/NamespaceMosaicIdGenerator.ts +++ b/src/infrastructure/transaction/NamespaceMosaicIdGenerator.ts @@ -14,52 +14,51 @@ * limitations under the License. */ -import {Crypto} from '../../core/crypto'; +import { Crypto } from '../../core/crypto'; import { IdGenerator } from '../../core/format'; export class NamespaceMosaicIdGenerator { /** * @param {Uint8Array} nonce Mosaic nonce * @param {Uint8Array} ownerPublicId Public key - * @returns mosaic Id + * @returns {number[]} mosaic Id */ - public static mosaicId = (nonce: Uint8Array, ownerPublicId: Uint8Array) => { + public static mosaicId = (nonce: Uint8Array, ownerPublicId: Uint8Array): number[] => { return IdGenerator.generateMosaicId(nonce, ownerPublicId); - } + }; /** * @returns random mosaic nonce */ - public static generateRandomMosaicNonce = () => { + public static generateRandomMosaicNonce = (): any => { return Crypto.randomBytes(4); - } + }; /** * @param {string} namespaceName - The namespace name * @returns sub namespace id */ - public static namespaceId = (namespaceName: string) => { + public static namespaceId = (namespaceName: string): any => { const path = IdGenerator.generateNamespacePath(namespaceName); return path.length ? IdGenerator.generateNamespacePath(namespaceName)[path.length - 1] : []; - } + }; /** * @param {string} parentNamespaceName - The parent namespace name * @param {string} namespaceName - The namespace name * @returns sub namespace parent id */ - public static subnamespaceParentId = (parentNamespaceName: string, namespaceName: string) => { + public static subnamespaceParentId = (parentNamespaceName: string, namespaceName: string): any => { const path = IdGenerator.generateNamespacePath(`${parentNamespaceName}.${namespaceName}`); return IdGenerator.generateNamespacePath(parentNamespaceName)[path.length - 2]; - } + }; /** * @param {string} parentNamespaceName - The parent namespace name * @param {string} namespaceName - The namespace name * @returns sub namespace id */ - public static subnamespaceNamespaceId = (parentNamespaceName: string, namespaceName: string) => { + public static subnamespaceNamespaceId = (parentNamespaceName: string, namespaceName: string): any => { const path = IdGenerator.generateNamespacePath(`${parentNamespaceName}.${namespaceName}`); return path[path.length - 1]; - } - + }; } diff --git a/src/infrastructure/transaction/SerializeTransactionToJSON.ts b/src/infrastructure/transaction/SerializeTransactionToJSON.ts index 3e8d736902..ab8a799244 100644 --- a/src/infrastructure/transaction/SerializeTransactionToJSON.ts +++ b/src/infrastructure/transaction/SerializeTransactionToJSON.ts @@ -111,8 +111,8 @@ export const SerializeTransactionToJSON = (transaction: Transaction): any => { restrictionAdditionsCount: accountMosaicRestrictionTx.restrictionAdditions.length, restrictionDeletionsCount: accountMosaicRestrictionTx.restrictionDeletions.length, restrictionAdditions: accountMosaicRestrictionTx.restrictionAdditions.map((addition) => { - return addition.toHex(); - }), + return addition.toHex(); + }), restrictionDeletions: accountMosaicRestrictionTx.restrictionDeletions.map((deletion) => { return deletion.toHex(); }), @@ -123,8 +123,8 @@ export const SerializeTransactionToJSON = (transaction: Transaction): any => { minApprovalDelta: multisigTx.minApprovalDelta, minRemovalDelta: multisigTx.minRemovalDelta, publicKeyAdditions: multisigTx.publicKeyAdditions.map((addition) => { - return addition.publicKey; - }), + return addition.publicKey; + }), publicKeyDeletions: multisigTx.publicKeyDeletions.map((deletion) => { return deletion.publicKey; }), @@ -164,10 +164,14 @@ export const SerializeTransactionToJSON = (transaction: Transaction): any => { }; if (registerNamespaceDuration) { - Object.assign(jsonObject, {duration: registerNamespaceDuration.toString()}); + Object.assign(jsonObject, { + duration: registerNamespaceDuration.toString(), + }); } if (registerNamespaceParentId) { - Object.assign(jsonObject, {parentId: registerNamespaceParentId.toHex()}); + Object.assign(jsonObject, { + parentId: registerNamespaceParentId.toHex(), + }); } return jsonObject; case TransactionType.SECRET_LOCK: @@ -176,14 +180,14 @@ export const SerializeTransactionToJSON = (transaction: Transaction): any => { mosaicId: secretLockTx.mosaic.id.id.toHex(), amount: secretLockTx.mosaic.amount.toString(), duration: secretLockTx.duration.toString(), - hashAlgorithm: secretLockTx.hashType, + hashAlgorithm: secretLockTx.hashAlgorithm, secret: secretLockTx.secret, recipientAddress: secretLockTx.recipientAddress.toDTO(), }; case TransactionType.SECRET_PROOF: const secretProofTx = transaction as SecretProofTransaction; return { - hashAlgorithm: secretProofTx.hashType, + hashAlgorithm: secretProofTx.hashAlgorithm, secret: secretProofTx.secret, recipientAddress: secretProofTx.recipientAddress.toDTO(), proof: secretProofTx.proof, @@ -216,7 +220,6 @@ export const SerializeTransactionToJSON = (transaction: Transaction): any => { targetAddress: mosaicAddressRestrictionTx.targetAddress.toDTO(), previousRestrictionValue: mosaicAddressRestrictionTx.previousRestrictionValue.toString(), newRestrictionValue: mosaicAddressRestrictionTx.newRestrictionValue.toString(), - }; case TransactionType.ACCOUNT_METADATA: const accountMetadataTx = transaction as AccountMetadataTransaction; @@ -226,7 +229,6 @@ export const SerializeTransactionToJSON = (transaction: Transaction): any => { valueSizeDelta: accountMetadataTx.valueSizeDelta, valueSize: accountMetadataTx.value.length, value: Convert.utf8ToHex(accountMetadataTx.value), - }; case TransactionType.MOSAIC_METADATA: const mosaicMetadataTx = transaction as MosaicMetadataTransaction; @@ -237,7 +239,6 @@ export const SerializeTransactionToJSON = (transaction: Transaction): any => { targetMosaicId: mosaicMetadataTx.targetMosaicId.id.toHex(), valueSize: mosaicMetadataTx.value.length, value: Convert.utf8ToHex(mosaicMetadataTx.value), - }; case TransactionType.NAMESPACE_METADATA: const namespaceMetaTx = transaction as NamespaceMetadataTransaction; @@ -248,10 +249,8 @@ export const SerializeTransactionToJSON = (transaction: Transaction): any => { targetNamespaceId: namespaceMetaTx.targetNamespaceId.id.toHex(), valueSize: namespaceMetaTx.value.length, value: Convert.utf8ToHex(namespaceMetaTx.value), - }; default: - throw new Error ('Transaction type not implemented yet.'); + throw new Error('Transaction type not implemented yet.'); } - }; diff --git a/src/model/Id.ts b/src/model/Id.ts index c7dff7defa..67b3f55ad8 100644 --- a/src/model/Id.ts +++ b/src/model/Id.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {UInt64} from './UInt64'; +import { UInt64 } from './UInt64'; /** * This class is used to define mosaicIds and namespaceIds @@ -44,7 +44,6 @@ export class Id extends UInt64 { * @returns {string} */ private pad(str, maxVal): string { - return (str.length < maxVal ? this.pad(`0${str}`, maxVal) : str); + return str.length < maxVal ? this.pad(`0${str}`, maxVal) : str; } - } diff --git a/src/model/UInt64.ts b/src/model/UInt64.ts index 88586fcd4a..22daa127c7 100644 --- a/src/model/UInt64.ts +++ b/src/model/UInt64.ts @@ -21,7 +21,6 @@ import { RawUInt64 as uint64 } from '../core/format'; * UInt64 data model */ export class UInt64 { - /** * uint64 lower part */ @@ -74,7 +73,7 @@ export class UInt64 { */ public static isLongNumericString(input: string): boolean { const input_long = Long.fromString(input, true); - if (! /^\d+$/.test(input) || (input.substr(0, 1) === '0' && input.length > 1) || !Long.isLong(input_long)) { + if (!/^\d+$/.test(input) || (input.substr(0, 1) === '0' && input.length > 1) || !Long.isLong(input_long)) { return false; } return true; @@ -125,7 +124,11 @@ export class UInt64 { * @returns {number} */ public compact(): number { - return uint64.compact(this.toDTO()); + const result = uint64.compact(this.toDTO()); + if (Array.isArray(result)) { + throw new Error('Compacted value is greater than Number.Max_Value.'); + } + return result; } /** diff --git a/src/model/account/Account.ts b/src/model/account/Account.ts index b72eb53915..af631ee12e 100644 --- a/src/model/account/Account.ts +++ b/src/model/account/Account.ts @@ -14,19 +14,18 @@ * limitations under the License. */ -import {Crypto, KeyPair} from '../../core/crypto'; -import {SHA3Hasher} from '../../core/crypto/SHA3Hasher'; -import {Convert, RawAddress} from '../../core/format'; -import {EncryptedMessage} from '../message/EncryptedMessage'; -import {PlainMessage} from '../message/PlainMessage'; -import {NetworkType} from '../network/NetworkType'; -import {AggregateTransaction} from '../transaction/AggregateTransaction'; -import {CosignatureSignedTransaction} from '../transaction/CosignatureSignedTransaction'; -import {CosignatureTransaction} from '../transaction/CosignatureTransaction'; -import {SignedTransaction} from '../transaction/SignedTransaction'; -import {Transaction} from '../transaction/Transaction'; -import {Address} from './Address'; -import {PublicAccount} from './PublicAccount'; +import { Crypto, KeyPair } from '../../core/crypto'; +import { Convert, RawAddress } from '../../core/format'; +import { EncryptedMessage } from '../message/EncryptedMessage'; +import { PlainMessage } from '../message/PlainMessage'; +import { NetworkType } from '../network/NetworkType'; +import { AggregateTransaction } from '../transaction/AggregateTransaction'; +import { CosignatureSignedTransaction } from '../transaction/CosignatureSignedTransaction'; +import { CosignatureTransaction } from '../transaction/CosignatureTransaction'; +import { SignedTransaction } from '../transaction/SignedTransaction'; +import { Transaction } from '../transaction/Transaction'; +import { Address } from './Address'; +import { PublicAccount } from './PublicAccount'; interface IKeyPair { privateKey: Uint8Array; @@ -37,22 +36,21 @@ interface IKeyPair { * The account structure describes an account private key, public key, address and allows signing transactions. */ export class Account { - /** * @internal * @param address * @param keyPair */ private constructor( - /** - * The account address. - */ - public readonly address: Address, - /** - * The account keyPair, public and private key. - */ - private readonly keyPair: IKeyPair) { - } + /** + * The account address. + */ + public readonly address: Address, + /** + * The account keyPair, public and private key. + */ + private readonly keyPair: IKeyPair, + ) {} /** * Create an Account from a given private key @@ -60,15 +58,10 @@ export class Account { * @param networkType - Network type * @return {Account} */ - public static createFromPrivateKey(privateKey: string, - networkType: NetworkType): Account { + public static createFromPrivateKey(privateKey: string, networkType: NetworkType): Account { const keyPair: IKeyPair = KeyPair.createKeyPairFromPrivateKeyString(privateKey); - const address = RawAddress.addressToString( - RawAddress.publicKeyToAddress(keyPair.publicKey, networkType)); - return new Account( - Address.createFromRawAddress(address), - keyPair, - ); + const address = RawAddress.addressToString(RawAddress.publicKeyToAddress(keyPair.publicKey, networkType)); + return new Account(Address.createFromRawAddress(address), keyPair); } /** @@ -95,9 +88,7 @@ export class Account { * @param networkType - Network type * @returns {EncryptedMessage} */ - public encryptMessage(message: string, - recipientPublicAccount: PublicAccount, - networkType: NetworkType): EncryptedMessage { + public encryptMessage(message: string, recipientPublicAccount: PublicAccount): EncryptedMessage { return EncryptedMessage.create(message, recipientPublicAccount, this.privateKey); } @@ -108,9 +99,7 @@ export class Account { * @param networkType - Network type * @returns {PlainMessage} */ - public decryptMessage(encryptedMessage: EncryptedMessage, - publicAccount: PublicAccount, - networkType: NetworkType): PlainMessage { + public decryptMessage(encryptedMessage: EncryptedMessage, publicAccount: PublicAccount): PlainMessage { return EncryptedMessage.decrypt(encryptedMessage, this.privateKey, publicAccount); } /** @@ -162,10 +151,12 @@ export class Account { * @param generationHash - Network generation hash hex * @return {SignedTransaction} */ - public signTransactionWithCosignatories(transaction: AggregateTransaction, - cosignatories: Account[], - generationHash: string): SignedTransaction { - return transaction.signTransactionWithCosignatories(this, cosignatories, generationHash); + public signTransactionWithCosignatories( + transaction: AggregateTransaction, + cosignatories: Account[], + generationHash: string, + ): SignedTransaction { + return transaction.signTransactionWithCosignatories(this, cosignatories, generationHash); } /** @@ -176,10 +167,12 @@ export class Account { * @param generationHash - Network generation hash hex * @return {SignedTransaction} */ - public signTransactionGivenSignatures(transaction: AggregateTransaction, - cosignatureSignedTransactions: CosignatureSignedTransaction[], - generationHash: string): SignedTransaction { - return transaction.signTransactionGivenSignatures(this, cosignatureSignedTransactions, generationHash); + public signTransactionGivenSignatures( + transaction: AggregateTransaction, + cosignatureSignedTransactions: CosignatureSignedTransaction[], + generationHash: string, + ): SignedTransaction { + return transaction.signTransactionGivenSignatures(this, cosignatureSignedTransactions, generationHash); } /** * Sign aggregate signature transaction diff --git a/src/model/account/AccountInfo.ts b/src/model/account/AccountInfo.ts index 6b1b155b7e..771de820ef 100644 --- a/src/model/account/AccountInfo.ts +++ b/src/model/account/AccountInfo.ts @@ -14,18 +14,17 @@ * limitations under the License. */ -import {Mosaic} from '../mosaic/Mosaic'; -import {UInt64} from '../UInt64'; +import { Mosaic } from '../mosaic/Mosaic'; +import { UInt64 } from '../UInt64'; import { AccountType } from './AccountType'; import { ActivityBucket } from './ActivityBucket'; -import {Address} from './Address'; -import {PublicAccount} from './PublicAccount'; +import { Address } from './Address'; +import { PublicAccount } from './PublicAccount'; /** * The account info structure describes basic information for an account. */ export class AccountInfo { - /** * */ @@ -69,9 +68,8 @@ export class AccountInfo { /** * Importance height of the account. */ - public readonly importanceHeight: UInt64) { - - } + public readonly importanceHeight: UInt64, + ) {} /** * Returns account public account. diff --git a/src/model/account/AccountInfoResolvedMosaic.ts b/src/model/account/AccountInfoResolvedMosaic.ts new file mode 100644 index 0000000000..10dc58c5e1 --- /dev/null +++ b/src/model/account/AccountInfoResolvedMosaic.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AccountInfo } from './AccountInfo'; +import { ResolvedMosaic } from '../mosaic/ResolvedMosaic'; + +/** + * Account info with resolved mosaic + */ +export type AccountInfoResolvedMosaic = AccountInfo & { resolvedMosaics?: ResolvedMosaic[] }; diff --git a/src/model/account/AccountNames.ts b/src/model/account/AccountNames.ts index 3ef1f3fbb0..013784b8dc 100644 --- a/src/model/account/AccountNames.ts +++ b/src/model/account/AccountNames.ts @@ -15,13 +15,12 @@ */ import { NamespaceName } from '../namespace/NamespaceName'; -import {Address} from './Address'; +import { Address } from './Address'; /** * Account with linked names */ export class AccountNames { - /** * */ @@ -33,7 +32,6 @@ export class AccountNames { /** * Address linked namespace Ids */ - public readonly names: NamespaceName[]) { - - } + public readonly names: NamespaceName[], + ) {} } diff --git a/src/model/account/AccountType.ts b/src/model/account/AccountType.ts index f0f1f08126..bc2e076e86 100644 --- a/src/model/account/AccountType.ts +++ b/src/model/account/AccountType.ts @@ -21,7 +21,7 @@ * 3 - Remote harvester eligible account that is unlinked. */ - export enum AccountType { +export enum AccountType { Unlinked = 0, Main = 1, Remote = 2, diff --git a/src/model/account/ActivityBucket.ts b/src/model/account/ActivityBucket.ts index 296a49a145..cffd27d065 100644 --- a/src/model/account/ActivityBucket.ts +++ b/src/model/account/ActivityBucket.ts @@ -18,29 +18,27 @@ * Account activity bucket. */ export class ActivityBucket { - /** * Constructor * @param meta * @param accountRestrictions */ constructor( - /** - * Start height - */ - public readonly startHeight: string, - /** - * Total fees paid. - */ - public readonly totalFeesPaid: number, - /** - * Beneficiary count. - */ - public readonly beneficiaryCount: number, - /** - * Raw score. - */ - public readonly rawScore: number) { - - } + /** + * Start height + */ + public readonly startHeight: string, + /** + * Total fees paid. + */ + public readonly totalFeesPaid: number, + /** + * Beneficiary count. + */ + public readonly beneficiaryCount: number, + /** + * Raw score. + */ + public readonly rawScore: number, + ) {} } diff --git a/src/model/account/Address.ts b/src/model/account/Address.ts index fb2b161991..654eb51df8 100644 --- a/src/model/account/Address.ts +++ b/src/model/account/Address.ts @@ -26,11 +26,9 @@ export class Address { * @param networkType - The NEM network type. * @returns {Address} */ - public static createFromPublicKey(publicKey: string, - networkType: NetworkType): Address { + public static createFromPublicKey(publicKey: string, networkType: NetworkType): Address { const publicKeyUint8 = Convert.hexToUint8(publicKey); - const address = RawAddress - .addressToString(RawAddress.publicKeyToAddress(publicKeyUint8, networkType)); + const address = RawAddress.addressToString(RawAddress.publicKeyToAddress(publicKeyUint8, networkType)); return new Address(address, networkType); } @@ -42,10 +40,7 @@ export class Address { */ public static createFromRawAddress(rawAddress: string): Address { let networkType: NetworkType; - const addressTrimAndUpperCase: string = rawAddress - .trim() - .toUpperCase() - .replace(/-/g, ''); + const addressTrimAndUpperCase: string = rawAddress.trim().toUpperCase().replace(/-/g, ''); if (addressTrimAndUpperCase.length !== 40) { throw new Error('Address ' + addressTrimAndUpperCase + ' has to be 40 characters long'); } @@ -69,52 +64,50 @@ export class Address { * @return {Address} */ public static createFromEncoded(encoded: string): Address { - return Address.createFromRawAddress(RawAddress - .addressToString(Convert.hexToUint8(encoded))); + return Address.createFromRawAddress(RawAddress.addressToString(Convert.hexToUint8(encoded))); } /** * Determines the validity of an raw address string. * @param {string} rawAddress The raw address string. Expected format SCHCZBZ6QVJAHGJTKYVPW5FBSO2IXXJQBPV5XE6P - * @param {NetworkType} networkType The network identifier. * @returns {boolean} true if the raw address string is valid, false otherwise. */ - public static isValidRawAddress = (rawAddress: string, networkType: NetworkType): boolean => { + public static isValidRawAddress = (rawAddress: string): boolean => { try { - return RawAddress.isValidAddress(RawAddress.stringToAddress(rawAddress), networkType); + return RawAddress.isValidAddress(RawAddress.stringToAddress(rawAddress)); } catch (err) { return false; } - } + }; /** * Determines the validity of an encoded address string. * @param {string} encoded The encoded address string. Expected format: 9085215E4620D383C2DF70235B9EF7607F6A28EF6D16FD7B9C - * @param {NetworkType} networkType The network identifier. * @returns {boolean} true if the encoded address string is valid, false otherwise. */ - public static isValidEncodedAddress = (encoded: string, networkType: NetworkType): boolean => { + public static isValidEncodedAddress = (encoded: string): boolean => { try { - return RawAddress.isValidAddress(Convert.hexToUint8(encoded), networkType); + return RawAddress.isValidAddress(Convert.hexToUint8(encoded)); } catch (err) { return false; } - } + }; /** * @internal * @param address * @param networkType */ - private constructor(/** - * The address value. - */ - private readonly address: string, - /** - * The NEM network type. - */ - public readonly networkType: NetworkType) { - } + private constructor( + /** + * The address value. + */ + private readonly address: string, + /** + * The NEM network type. + */ + public readonly networkType: NetworkType, + ) {} /** * Get address in plain format ex: SB3KUBHATFCPV7UZQLWAQ2EUR6SIHBSBEOEDDDF3. @@ -152,7 +145,7 @@ export class Address { /** * Create DTO object */ - public toDTO() { + public toDTO(): any { return { address: this.address, networkType: this.networkType, diff --git a/src/model/account/MultisigAccountGraphInfo.ts b/src/model/account/MultisigAccountGraphInfo.ts index 548eab9cd6..89b596bdf7 100644 --- a/src/model/account/MultisigAccountGraphInfo.ts +++ b/src/model/account/MultisigAccountGraphInfo.ts @@ -14,19 +14,19 @@ * limitations under the License. */ -import {MultisigAccountInfo} from './MultisigAccountInfo'; +import { MultisigAccountInfo } from './MultisigAccountInfo'; /** * Multisig account graph info model */ export class MultisigAccountGraphInfo { - /** * @param multisigAccounts */ - constructor(/** - * The multisig accounts. - */ - public readonly multisigAccounts: Map) { - } + constructor( + /** + * The multisig accounts. + */ + public readonly multisigAccounts: Map, + ) {} } diff --git a/src/model/account/MultisigAccountInfo.ts b/src/model/account/MultisigAccountInfo.ts index 6aaf1e28dc..9847fbc822 100644 --- a/src/model/account/MultisigAccountInfo.ts +++ b/src/model/account/MultisigAccountInfo.ts @@ -14,13 +14,12 @@ * limitations under the License. */ -import {PublicAccount} from './PublicAccount'; +import { PublicAccount } from './PublicAccount'; /** * The multisig account graph info structure describes the information of all the mutlisig levels an account is involved in. */ export class MultisigAccountInfo { - /** * @param account * @param minApproval @@ -28,28 +27,28 @@ export class MultisigAccountInfo { * @param cosignatories * @param multisigAccounts */ - constructor(/** - * The account multisig public account. - */ - public readonly account: PublicAccount, - /** - * The number of signatures needed to approve a transaction. - */ - public readonly minApproval: number, - /** - * The number of signatures needed to remove a cosignatory. - */ - public readonly minRemoval: number, - /** - * The multisig account cosignatories. - */ - public readonly cosignatories: PublicAccount[], - /** - * The multisig accounts this account is cosigner of. - */ - public readonly multisigAccounts: PublicAccount[]) { - - } + constructor( + /** + * The account multisig public account. + */ + public readonly account: PublicAccount, + /** + * The number of signatures needed to approve a transaction. + */ + public readonly minApproval: number, + /** + * The number of signatures needed to remove a cosignatory. + */ + public readonly minRemoval: number, + /** + * The multisig account cosignatories. + */ + public readonly cosignatories: PublicAccount[], + /** + * The multisig accounts this account is cosigner of. + */ + public readonly multisigAccounts: PublicAccount[], + ) {} /** * Checks if the account is a multisig account. diff --git a/src/model/account/PublicAccount.ts b/src/model/account/PublicAccount.ts index 1117a95a23..227a9b804c 100644 --- a/src/model/account/PublicAccount.ts +++ b/src/model/account/PublicAccount.ts @@ -25,23 +25,21 @@ const Hash512 = 64; * The public account structure contains account's address and public key. */ export class PublicAccount { - /** * @internal * @param publicKey * @param address */ constructor( - /** - * The account public private. - */ - public readonly publicKey: string, - /** - * The account address. - */ - public readonly address: Address) { - - } + /** + * The account public private. + */ + public readonly publicKey: string, + /** + * The account address. + */ + public readonly address: Address, + ) {} /** * Create a PublicAccount from a public key and network type. @@ -68,20 +66,16 @@ export class PublicAccount { if (!signature) { throw new Error('Missing argument'); } - if (signature.length / 2 !== Hash512) { throw new Error('Signature length is incorrect'); } - if (!Convert.isHexString(signature)) { throw new Error('Signature must be hexadecimal only'); } // Convert signature key to Uint8Array const convertedSignature = Convert.hexToUint8(signature); - // Convert to Uint8Array - - const convertedData = Convert.hexToUint8(Convert.isHexString(data) ? data : Convert.utf8ToHex(data)); + const convertedData = Convert.hexToUint8(Convert.utf8ToHex(data)); return KeyPair.verify(Convert.hexToUint8(this.publicKey), convertedData, convertedSignature); } @@ -97,7 +91,7 @@ export class PublicAccount { /** * Create DTO object */ - toDTO() { + toDTO(): any { return { publicKey: this.publicKey, address: this.address.toDTO(), diff --git a/src/model/blockchain/BlockInfo.ts b/src/model/blockchain/BlockInfo.ts index c9a4b1d91a..98ee5a8199 100644 --- a/src/model/blockchain/BlockInfo.ts +++ b/src/model/blockchain/BlockInfo.ts @@ -14,15 +14,14 @@ * limitations under the License. */ -import {PublicAccount} from '../account/PublicAccount'; -import {NetworkType} from '../network/NetworkType'; -import {UInt64} from '../UInt64'; +import { PublicAccount } from '../account/PublicAccount'; +import { NetworkType } from '../network/NetworkType'; +import { UInt64 } from '../UInt64'; /** * The block info structure describes basic information of a block. */ export class BlockInfo { - /** * @param hash * @param generationHash @@ -44,85 +43,85 @@ export class BlockInfo { * @param beneficiaryPublicKey * @param numStatements */ - constructor(/** - * The block hash. - */ - public readonly hash: string, - /** - * The generation hash - */ - public readonly generationHash: string, - /** - * The sum of all transaction fees included in the block. - */ - public readonly totalFee: UInt64, - /** - * The number of transactions included. - */ - public readonly numTransactions: number, - /** - * The block signature. - * The signature was generated by the signer and can be used to validate that the blockchain - * data was not modified by a node. - */ - public readonly signature: string, - /** - * The public account of block harvester. - */ - public readonly signer: PublicAccount, - /** - * The network type. - */ - public readonly networkType: NetworkType, - /** - * The transaction version. - */ - public readonly version: number, - /** - * The block type. - */ - public readonly type: number, - /** - * The height of which the block was confirmed. - * Each block has a unique height. Subsequent blocks differ in height by 1. - */ - public readonly height: UInt64, - /** - * The number of milliseconds elapsed since the creation of the nemesis blockchain. - */ - public readonly timestamp: UInt64, - /** - * The POI difficulty to harvest a block. - */ - public readonly difficulty: UInt64, - /** - * The feeMultiplier defined by the harvester. - */ - public readonly feeMultiplier: number, - /** - * The last block hash. - */ - public readonly previousBlockHash: string, - /** - * The block transaction hash. - */ - public readonly blockTransactionsHash: string, - /** - * The block receipt hash. - */ - public readonly blockReceiptsHash: string, - /** - * The state hash. - */ - public readonly stateHash: string, - /** - * The beneficiary public key. - */ - public readonly beneficiaryPublicKey?: PublicAccount | undefined, - /** - * The number of statements included. - */ - public readonly numStatements?: number) { - - } + constructor( + /** + * The block hash. + */ + public readonly hash: string, + /** + * The generation hash + */ + public readonly generationHash: string, + /** + * The sum of all transaction fees included in the block. + */ + public readonly totalFee: UInt64, + /** + * The number of transactions included. + */ + public readonly numTransactions: number, + /** + * The block signature. + * The signature was generated by the signer and can be used to validate that the blockchain + * data was not modified by a node. + */ + public readonly signature: string, + /** + * The public account of block harvester. + */ + public readonly signer: PublicAccount, + /** + * The network type. + */ + public readonly networkType: NetworkType, + /** + * The transaction version. + */ + public readonly version: number, + /** + * The block type. + */ + public readonly type: number, + /** + * The height of which the block was confirmed. + * Each block has a unique height. Subsequent blocks differ in height by 1. + */ + public readonly height: UInt64, + /** + * The number of milliseconds elapsed since the creation of the nemesis blockchain. + */ + public readonly timestamp: UInt64, + /** + * The POI difficulty to harvest a block. + */ + public readonly difficulty: UInt64, + /** + * The feeMultiplier defined by the harvester. + */ + public readonly feeMultiplier: number, + /** + * The last block hash. + */ + public readonly previousBlockHash: string, + /** + * The block transaction hash. + */ + public readonly blockTransactionsHash: string, + /** + * The block receipt hash. + */ + public readonly blockReceiptsHash: string, + /** + * The state hash. + */ + public readonly stateHash: string, + /** + * The beneficiary public key. + */ + public readonly beneficiaryPublicKey?: PublicAccount | undefined, + /** + * The number of statements included. + */ + public readonly numStatements?: number, + ) {} } diff --git a/src/model/blockchain/BlockchainScore.ts b/src/model/blockchain/BlockchainScore.ts index 12d8e98173..dd5d08830f 100644 --- a/src/model/blockchain/BlockchainScore.ts +++ b/src/model/blockchain/BlockchainScore.ts @@ -14,25 +14,24 @@ * limitations under the License. */ -import {UInt64} from '../UInt64'; +import { UInt64 } from '../UInt64'; /** * The blockchain score structure describes blockchain difficulty. */ export class BlockchainScore { - /** * @param scoreLow * @param scoreHigh */ - constructor(/** - * Low part of the blockchain score. - */ - public readonly scoreLow: UInt64, - /** - * High part of the blockchain score. - */ - public readonly scoreHigh: UInt64) { - - } + constructor( + /** + * Low part of the blockchain score. + */ + public readonly scoreLow: UInt64, + /** + * High part of the blockchain score. + */ + public readonly scoreHigh: UInt64, + ) {} } diff --git a/src/model/blockchain/MerklePathItem.ts b/src/model/blockchain/MerklePathItem.ts index 9547d8f7e0..97380293a7 100644 --- a/src/model/blockchain/MerklePathItem.ts +++ b/src/model/blockchain/MerklePathItem.ts @@ -20,19 +20,18 @@ import { PositionEnum } from 'symbol-openapi-typescript-node-client/dist/model/p * The block merkle path item */ export class MerklePathItem { - /** * @param position * @param hash */ - constructor(/** - * The position - */ - public readonly position?: PositionEnum, - /** - * The hash - */ - public readonly hash?: string) { - - } + constructor( + /** + * The position + */ + public readonly position?: PositionEnum, + /** + * The hash + */ + public readonly hash?: string, + ) {} } diff --git a/src/model/blockchain/MerkleProofInfo.ts b/src/model/blockchain/MerkleProofInfo.ts index 86df7da991..5bc88b3b98 100644 --- a/src/model/blockchain/MerkleProofInfo.ts +++ b/src/model/blockchain/MerkleProofInfo.ts @@ -20,14 +20,13 @@ import { MerklePathItem } from './MerklePathItem'; * The block merkle proof info */ export class MerkleProofInfo { - /** * @param merklePath - Array of merkle path items */ - constructor(/** - * The merkle path - */ - public readonly merklePath?: MerklePathItem[]) { - - } + constructor( + /** + * The merkle path + */ + public readonly merklePath?: MerklePathItem[], + ) {} } diff --git a/src/model/blockchain/StorageInfo.ts b/src/model/blockchain/StorageInfo.ts index b71c8aaf2f..712db87531 100644 --- a/src/model/blockchain/StorageInfo.ts +++ b/src/model/blockchain/StorageInfo.ts @@ -18,23 +18,23 @@ * The blockchain storage info structure describes stored data. */ export class StorageInfo { - /** * @param numBlocks * @param numTransactions * @param numAccounts */ - constructor(/** - * The number of confirmed blocks. - */ - public readonly numBlocks: number, - /** - * The number of confirmed transactions. - */ - public readonly numTransactions: number, - /** - * The number accounts published in the blockchain. - */ - public readonly numAccounts: number) { - } + constructor( + /** + * The number of confirmed blocks. + */ + public readonly numBlocks: number, + /** + * The number of confirmed transactions. + */ + public readonly numTransactions: number, + /** + * The number accounts published in the blockchain. + */ + public readonly numAccounts: number, + ) {} } diff --git a/src/model/message/EncryptedMessage.ts b/src/model/message/EncryptedMessage.ts index 8133f87f5e..12ac76f67f 100644 --- a/src/model/message/EncryptedMessage.ts +++ b/src/model/message/EncryptedMessage.ts @@ -14,22 +14,19 @@ * limitations under the License. */ -import {Crypto, SHA3Hasher} from '../../core/crypto'; -import {PublicAccount} from '../account/PublicAccount'; -import { NetworkType } from '../network/NetworkType'; -import {Message} from './Message'; -import {MessageType} from './MessageType'; -import {PlainMessage} from './PlainMessage'; +import { Crypto } from '../../core/crypto'; +import { PublicAccount } from '../account/PublicAccount'; +import { Message } from './Message'; +import { MessageType } from './MessageType'; +import { PlainMessage } from './PlainMessage'; /** * Encrypted Message model */ export class EncryptedMessage extends Message { - public readonly recipientPublicAccount?: PublicAccount; - constructor(payload: string, - recipientPublicAccount?: PublicAccount) { + constructor(payload: string, recipientPublicAccount?: PublicAccount) { super(MessageType.EncryptedMessage, payload); this.recipientPublicAccount = recipientPublicAccount; } @@ -41,14 +38,11 @@ export class EncryptedMessage extends Message { * @param privateKey - Sender private key * @return {EncryptedMessage} */ - public static create(message: string, - recipientPublicAccount: PublicAccount, - privateKey: string): EncryptedMessage { + public static create(message: string, recipientPublicAccount: PublicAccount, privateKey: string): EncryptedMessage { return new EncryptedMessage( - Crypto.encode(privateKey, - recipientPublicAccount.publicKey, - message).toUpperCase(), - recipientPublicAccount); + Crypto.encode(privateKey, recipientPublicAccount.publicKey, message).toUpperCase(), + recipientPublicAccount, + ); } /** @@ -66,12 +60,7 @@ export class EncryptedMessage extends Message { * @param recipientPublicAccount - Sender public account * @return {PlainMessage} */ - public static decrypt(encryptMessage: EncryptedMessage, - privateKey, - recipientPublicAccount: PublicAccount): PlainMessage { - return new PlainMessage(this.decodeHex( - Crypto.decode(privateKey, - recipientPublicAccount.publicKey, - encryptMessage.payload))); + public static decrypt(encryptMessage: EncryptedMessage, privateKey, recipientPublicAccount: PublicAccount): PlainMessage { + return new PlainMessage(this.decodeHex(Crypto.decode(privateKey, recipientPublicAccount.publicKey, encryptMessage.payload))); } } diff --git a/src/model/message/Message.ts b/src/model/message/Message.ts index 532b6ba0c4..df26f43f88 100644 --- a/src/model/message/Message.ts +++ b/src/model/message/Message.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {decode} from 'utf8'; +import { decode } from 'utf8'; /** * An abstract message class that serves as the base class of all message types. @@ -42,20 +42,21 @@ export abstract class Message { * @param type * @param payload */ - constructor(/** - * Message type - */ - public readonly type: number, - /** - * Message payload - */ - public readonly payload: string) { - } + constructor( + /** + * Message type + */ + public readonly type: number, + /** + * Message payload + */ + public readonly payload: string, + ) {} /** * Create DTO object */ - toDTO() { + toDTO(): any { return { type: this.type, payload: this.payload, diff --git a/src/model/message/MessageType.ts b/src/model/message/MessageType.ts index 2174a91d8c..8c211908f3 100644 --- a/src/model/message/MessageType.ts +++ b/src/model/message/MessageType.ts @@ -23,5 +23,5 @@ export enum MessageType { PlainMessage = 0x00, EncryptedMessage = 0x01, - PersistentHarvestingDelegationMessage = 0xFE, + PersistentHarvestingDelegationMessage = 0xfe, } diff --git a/src/model/message/PersistentHarvestingDelegationMessage.ts b/src/model/message/PersistentHarvestingDelegationMessage.ts index c51d897f8f..7542c99cee 100644 --- a/src/model/message/PersistentHarvestingDelegationMessage.ts +++ b/src/model/message/PersistentHarvestingDelegationMessage.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {Crypto, SHA3Hasher} from '../../core/crypto'; +import { Crypto } from '../../core/crypto'; import { Convert } from '../../core/format/Convert'; import { Account } from '../account/Account'; import { NetworkType } from '../network/NetworkType'; @@ -37,11 +37,15 @@ export class PersistentHarvestingDelegationMessage extends Message { * @param {NetworkType} networkType - Catapult network type * @return {PersistentHarvestingDelegationMessage} */ - public static create(delegatedPrivateKey: string, - recipientPublicKey: string, - networkType: NetworkType): PersistentHarvestingDelegationMessage { + public static create( + delegatedPrivateKey: string, + recipientPublicKey: string, + networkType: NetworkType, + ): PersistentHarvestingDelegationMessage { const ephemeralKeypair = Account.generateNewAccount(networkType); - const encrypted = MessageMarker.PersistentDelegationUnlock + ephemeralKeypair.publicKey + + const encrypted = + MessageMarker.PersistentDelegationUnlock + + ephemeralKeypair.publicKey + Crypto.encode(ephemeralKeypair.privateKey, recipientPublicKey, delegatedPrivateKey, true).toUpperCase(); return new PersistentHarvestingDelegationMessage(encrypted); } @@ -61,8 +65,7 @@ export class PersistentHarvestingDelegationMessage extends Message { * @param privateKey - Recipient private key * @return {string} */ - public static decrypt(encryptMessage: PersistentHarvestingDelegationMessage, - privateKey: string): string { + public static decrypt(encryptMessage: PersistentHarvestingDelegationMessage, privateKey: string): string { const markerLength = MessageMarker.PersistentDelegationUnlock.length; const ephemeralPublicKey = encryptMessage.payload.substring(markerLength, markerLength + 64); const payload = encryptMessage.payload.substring(markerLength + ephemeralPublicKey.length); diff --git a/src/model/message/PlainMessage.ts b/src/model/message/PlainMessage.ts index 809017e1fe..37d5634903 100644 --- a/src/model/message/PlainMessage.ts +++ b/src/model/message/PlainMessage.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {Message} from './Message'; -import {MessageType} from './MessageType'; +import { Message } from './Message'; +import { MessageType } from './MessageType'; /** * The plain message model defines a plain string. When sending it to the network we transform the payload to hex-string. @@ -43,7 +43,6 @@ export class PlainMessage extends Message { constructor(payload: string) { super(MessageType.PlainMessage, payload); } - } /** diff --git a/src/model/metadata/Metadata.ts b/src/model/metadata/Metadata.ts index c2d0dd4a40..7afe4cb730 100644 --- a/src/model/metadata/Metadata.ts +++ b/src/model/metadata/Metadata.ts @@ -21,21 +21,19 @@ import { MetadataEntry } from './MetadataEntry'; * Mosaics can be transferred by means of a transfer transaction. */ export class Metadata { - /** * Constructor * @param id - The metadata id * @param metadataEntry - The metadata entry */ constructor( - /** - * The metadata id - */ - public readonly id: string, - /** - * The metadata entry - */ - public readonly metadataEntry: MetadataEntry) { - - } + /** + * The metadata id + */ + public readonly id: string, + /** + * The metadata entry + */ + public readonly metadataEntry: MetadataEntry, + ) {} } diff --git a/src/model/metadata/MetadataEntry.ts b/src/model/metadata/MetadataEntry.ts index e740b301b2..eccdcb2187 100644 --- a/src/model/metadata/MetadataEntry.ts +++ b/src/model/metadata/MetadataEntry.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {MosaicId} from '../mosaic/MosaicId'; -import {NamespaceId} from '../namespace/NamespaceId'; +import { MosaicId } from '../mosaic/MosaicId'; +import { NamespaceId } from '../namespace/NamespaceId'; import { UInt64 } from '../UInt64'; import { MetadataType } from './MetadataType'; @@ -24,7 +24,6 @@ import { MetadataType } from './MetadataType'; * Mosaics can be transferred by means of a transfer transaction. */ export class MetadataEntry { - /** * Constructor * @param {string} compositeHash - The composite hash @@ -36,34 +35,33 @@ export class MetadataEntry { * @param {MosaicId | NamespaceId | undefined} targetId - The target mosaic or namespace identifier */ constructor( - /** - * The composite hash - */ - public readonly compositeHash: string, - /** - * The metadata sender's public key - */ - public readonly senderPublicKey: string, - /** - * The metadata target public key - */ - public readonly targetPublicKey: string, - /** - * The key scoped to source, target and type - */ - public readonly scopedMetadataKey: UInt64, - /** - * The metadata type - */ - public readonly metadataType: MetadataType, - /** - * The metadata value - */ - public readonly value: string, - /** - * The target mosaic or namespace identifier - */ - public readonly targetId?: MosaicId | NamespaceId) { - - } + /** + * The composite hash + */ + public readonly compositeHash: string, + /** + * The metadata sender's public key + */ + public readonly senderPublicKey: string, + /** + * The metadata target public key + */ + public readonly targetPublicKey: string, + /** + * The key scoped to source, target and type + */ + public readonly scopedMetadataKey: UInt64, + /** + * The metadata type + */ + public readonly metadataType: MetadataType, + /** + * The metadata value + */ + public readonly value: string, + /** + * The target mosaic or namespace identifier + */ + public readonly targetId?: MosaicId | NamespaceId, + ) {} } diff --git a/src/model/model.ts b/src/model/model.ts index 75d93ee10f..ac5e4f7a9b 100644 --- a/src/model/model.ts +++ b/src/model/model.ts @@ -1,5 +1,5 @@ /* - * Copyright 2018 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ export * from './account/MultisigAccountGraphInfo'; export * from './account/MultisigAccountInfo'; export * from './account/PublicAccount'; export * from './account/AccountNames'; +export * from './account/AccountInfoResolvedMosaic'; // Blockchain export * from './blockchain/BlockchainScore'; @@ -51,6 +52,7 @@ export * from './mosaic/NetworkCurrencyLocal'; export * from './mosaic/NetworkCurrencyPublic'; export * from './mosaic/NetworkHarvestLocal'; export * from './mosaic/MosaicNames'; +export * from './mosaic/ResolvedMosaic'; // Mosaic export * from './metadata/Metadata'; @@ -69,6 +71,7 @@ export * from './namespace/NamespaceName'; export * from './namespace/NamespaceRegistrationType'; export * from './namespace/AliasAction'; export * from './namespace/EmptyAlias'; +export * from './namespace/NamespaceInfoWithName'; // Network @@ -150,7 +153,7 @@ export * from './transaction/CosignatureTransaction'; export * from './transaction/Deadline'; export * from './transaction/PersistentDelegationRequestTransaction'; export * from './transaction/HashLockTransaction'; -export * from './transaction/HashType'; +export * from './transaction/LockHashAlgorithm'; export * from './transaction/InnerTransaction'; export * from './transaction/LinkAction'; export * from './transaction/LockFundsTransaction'; @@ -179,9 +182,7 @@ export * from './transaction/MosaicGlobalRestrictionTransaction'; export * from './transaction/MosaicAddressRestrictionTransaction'; // Wallet -export * from './wallet/EncryptedPrivateKey'; export * from './wallet/ISimpleWalletDTO'; export * from './wallet/Password'; export * from './wallet/SimpleWallet'; export * from './wallet/Wallet'; -export * from './wallet/WalletAlgorithm'; diff --git a/src/model/mosaic/Mosaic.ts b/src/model/mosaic/Mosaic.ts index 2b392b9e3d..a94145ec2f 100644 --- a/src/model/mosaic/Mosaic.ts +++ b/src/model/mosaic/Mosaic.ts @@ -14,43 +14,40 @@ * limitations under the License. */ -import {NamespaceId} from '../namespace/NamespaceId'; -import {UInt64} from '../UInt64'; -import {MosaicId} from './MosaicId'; +import { NamespaceId } from '../namespace/NamespaceId'; +import { UInt64 } from '../UInt64'; +import { MosaicId } from './MosaicId'; /** * A mosaic describes an instance of a mosaic definition. * Mosaics can be transferred by means of a transfer transaction. */ export class Mosaic { - /** * Constructor * @param id * @param amount */ constructor( - /** - * The mosaic id - */ - public readonly id: MosaicId|NamespaceId, - /** - * The mosaic amount. The quantity is always given in smallest units for the mosaic - * i.e. if it has a divisibility of 3 the quantity is given in millis. - */ - public readonly amount: UInt64) { - - } + /** + * The mosaic id + */ + public readonly id: MosaicId | NamespaceId, + /** + * The mosaic amount. The quantity is always given in smallest units for the mosaic + * i.e. if it has a divisibility of 3 the quantity is given in millis. + */ + public readonly amount: UInt64, + ) {} /** * @internal * @returns {{amount: number[], id: number[]}} */ - public toDTO() { + public toDTO(): any { return { amount: this.amount.toString(), id: this.id.id.toHex(), }; } - } diff --git a/src/model/mosaic/MosaicFlags.ts b/src/model/mosaic/MosaicFlags.ts index 21ff8017ac..26c526be59 100644 --- a/src/model/mosaic/MosaicFlags.ts +++ b/src/model/mosaic/MosaicFlags.ts @@ -18,7 +18,6 @@ * Mosaic flags model */ export class MosaicFlags { - /** * The creator can choose between a definition that allows a mosaic supply change at a later point or an immutable supply. * Allowed values for the property are "true" and "false". The default value is "false". @@ -60,10 +59,7 @@ export class MosaicFlags { * @param transferable * @param restrictable */ - public static create( - supplyMutable: boolean, - transferable: boolean, - restrictable: boolean = false ): MosaicFlags { + public static create(supplyMutable: boolean, transferable: boolean, restrictable = false): MosaicFlags { const flags = (supplyMutable ? 1 : 0) + (transferable ? 2 : 0) + (restrictable ? 4 : 0); return new MosaicFlags(flags); } @@ -79,7 +75,7 @@ export class MosaicFlags { /** * Create DTO object */ - toDTO() { + toDTO(): any { return { flags: this.getValue(), }; diff --git a/src/model/mosaic/MosaicId.ts b/src/model/mosaic/MosaicId.ts index 5804ca9c48..4cf900e263 100644 --- a/src/model/mosaic/MosaicId.ts +++ b/src/model/mosaic/MosaicId.ts @@ -25,7 +25,6 @@ import { MosaicNonce } from '../mosaic/MosaicNonce'; * @since 1.0 */ export class MosaicId { - /** * Mosaic id */ @@ -56,7 +55,7 @@ export class MosaicId { if (id instanceof Array) { this.id = new Id(id); } else if (typeof id === 'string') { - if (! /^[0-9A-Fa-f]{16}$/i.test(id)) { + if (!/^[0-9A-Fa-f]{16}$/i.test(id)) { throw new Error('Invalid size for MosaicId hexadecimal notation'); } @@ -88,7 +87,7 @@ export class MosaicId { /** * Create DTO object. */ - toDTO() { + toDTO(): any { return this.id.toDTO(); } } diff --git a/src/model/mosaic/MosaicInfo.ts b/src/model/mosaic/MosaicInfo.ts index a61bcd7b07..c6499194f1 100644 --- a/src/model/mosaic/MosaicInfo.ts +++ b/src/model/mosaic/MosaicInfo.ts @@ -23,7 +23,6 @@ import { MosaicId } from './MosaicId'; * The mosaic info structure describes a mosaic. */ export class MosaicInfo { - /** * @param id * @param supply @@ -35,40 +34,39 @@ export class MosaicInfo { * @param duration */ constructor( - /** - * The mosaic id. - */ - public readonly id: MosaicId, - /** - * The mosaic supply. - */ - public readonly supply: UInt64, - /** - * The block height were mosaic was created. - */ - public readonly height: UInt64, - /** - * The public key of the mosaic creator. - */ - public readonly owner: PublicAccount, - /** - * The mosaic revision - */ - public readonly revision: number, - /** - * The mosaic flags. - */ - public readonly flags: MosaicFlags, - /** - * Mosaic divisibility - */ - public readonly divisibility: number, - /** - * Mosaic duration - */ - public readonly duration: UInt64, - ) { - } + /** + * The mosaic id. + */ + public readonly id: MosaicId, + /** + * The mosaic supply. + */ + public readonly supply: UInt64, + /** + * The block height were mosaic was created. + */ + public readonly height: UInt64, + /** + * The public key of the mosaic creator. + */ + public readonly owner: PublicAccount, + /** + * The mosaic revision + */ + public readonly revision: number, + /** + * The mosaic flags. + */ + public readonly flags: MosaicFlags, + /** + * Mosaic divisibility + */ + public readonly divisibility: number, + /** + * Mosaic duration + */ + public readonly duration: UInt64, + ) {} /** * Is mosaic supply mutable diff --git a/src/model/mosaic/MosaicNames.ts b/src/model/mosaic/MosaicNames.ts index bdbba55f79..3d540c619e 100644 --- a/src/model/mosaic/MosaicNames.ts +++ b/src/model/mosaic/MosaicNames.ts @@ -21,7 +21,6 @@ import { MosaicId } from './MosaicId'; * Mosaic with linked names */ export class MosaicNames { - /** * */ @@ -33,7 +32,6 @@ export class MosaicNames { /** * Address linked namespace names */ - public readonly names: NamespaceName[]) { - - } + public readonly names: NamespaceName[], + ) {} } diff --git a/src/model/mosaic/MosaicNonce.ts b/src/model/mosaic/MosaicNonce.ts index d120a92b11..7471b5863b 100644 --- a/src/model/mosaic/MosaicNonce.ts +++ b/src/model/mosaic/MosaicNonce.ts @@ -22,7 +22,6 @@ import { Convert as convert } from '../../core/format'; * @since 1.0 */ export class MosaicNonce { - /** * Create MosaicNonce from int * diff --git a/src/model/mosaic/NetworkCurrencyLocal.ts b/src/model/mosaic/NetworkCurrencyLocal.ts index c1a6e34dc9..cb8b3a887f 100644 --- a/src/model/mosaic/NetworkCurrencyLocal.ts +++ b/src/model/mosaic/NetworkCurrencyLocal.ts @@ -14,10 +14,9 @@ * limitations under the License. */ -import {NamespaceId} from '../namespace/NamespaceId'; -import {UInt64} from '../UInt64'; -import {Mosaic} from './Mosaic'; -import {MosaicId} from './MosaicId'; +import { NamespaceId } from '../namespace/NamespaceId'; +import { UInt64 } from '../UInt64'; +import { Mosaic } from './Mosaic'; /** * NetworkCurrencyLocal mosaic for local test network (local bootstrap server) @@ -28,7 +27,6 @@ import {MosaicId} from './MosaicId'; * @since 0.10.2 */ export class NetworkCurrencyLocal extends Mosaic { - /** * namespaceId of `currency` namespace. * @@ -75,7 +73,7 @@ export class NetworkCurrencyLocal extends Mosaic { * @param amount * @returns {NetworkCurrencyLocal} */ - public static createRelative(amount: UInt64 | number) { + public static createRelative(amount: UInt64 | number): NetworkCurrencyLocal { if (typeof amount === 'number') { return new NetworkCurrencyLocal(UInt64.fromUint(amount * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY))); } @@ -89,7 +87,7 @@ export class NetworkCurrencyLocal extends Mosaic { * @param amount * @returns {NetworkCurrencyLocal} */ - public static createAbsolute(amount: UInt64 | number) { + public static createAbsolute(amount: UInt64 | number): NetworkCurrencyLocal { if (typeof amount === 'number') { return new NetworkCurrencyLocal(UInt64.fromUint(amount)); } diff --git a/src/model/mosaic/NetworkCurrencyPublic.ts b/src/model/mosaic/NetworkCurrencyPublic.ts index bb9b39bf04..236553cbf7 100644 --- a/src/model/mosaic/NetworkCurrencyPublic.ts +++ b/src/model/mosaic/NetworkCurrencyPublic.ts @@ -14,10 +14,9 @@ * limitations under the License. */ -import {NamespaceId} from '../namespace/NamespaceId'; -import {UInt64} from '../UInt64'; -import {Mosaic} from './Mosaic'; -import {MosaicId} from './MosaicId'; +import { NamespaceId } from '../namespace/NamespaceId'; +import { UInt64 } from '../UInt64'; +import { Mosaic } from './Mosaic'; /** * NetworkCurrencyPublic mosaic for public / Public_test network @@ -28,7 +27,6 @@ import {MosaicId} from './MosaicId'; * @since 0.10.2 */ export class NetworkCurrencyPublic extends Mosaic { - /** * namespaceId of `currency` namespace. * @@ -75,7 +73,7 @@ export class NetworkCurrencyPublic extends Mosaic { * @param amount * @returns {NetworkCurrencyPublic} */ - public static createRelative(amount: UInt64 | number) { + public static createRelative(amount: UInt64 | number): NetworkCurrencyPublic { if (typeof amount === 'number') { return new NetworkCurrencyPublic(UInt64.fromUint(amount * Math.pow(10, NetworkCurrencyPublic.DIVISIBILITY))); } @@ -89,7 +87,7 @@ export class NetworkCurrencyPublic extends Mosaic { * @param amount * @returns {NetworkCurrencyPublic} */ - public static createAbsolute(amount: UInt64 | number) { + public static createAbsolute(amount: UInt64 | number): NetworkCurrencyPublic { if (typeof amount === 'number') { return new NetworkCurrencyPublic(UInt64.fromUint(amount)); } diff --git a/src/model/mosaic/NetworkHarvestLocal.ts b/src/model/mosaic/NetworkHarvestLocal.ts index c600988cf1..955a221c05 100644 --- a/src/model/mosaic/NetworkHarvestLocal.ts +++ b/src/model/mosaic/NetworkHarvestLocal.ts @@ -13,10 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {NamespaceId} from '../namespace/NamespaceId'; -import {UInt64} from '../UInt64'; -import {Mosaic} from './Mosaic'; -import {MosaicId} from './MosaicId'; +import { NamespaceId } from '../namespace/NamespaceId'; +import { UInt64 } from '../UInt64'; +import { Mosaic } from './Mosaic'; /** * NetworkHarvestLocal mosaic @@ -27,7 +26,6 @@ import {MosaicId} from './MosaicId'; * @since 0.10.2 */ export class NetworkHarvestLocal extends Mosaic { - /** * namespaceId of `currency` namespace. * @@ -74,7 +72,7 @@ export class NetworkHarvestLocal extends Mosaic { * @param amount * @returns {NetworkHarvestLocal} */ - public static createRelative(amount: UInt64 | number) { + public static createRelative(amount: UInt64 | number): NetworkHarvestLocal { if (typeof amount === 'number') { return new NetworkHarvestLocal(UInt64.fromUint(amount * Math.pow(10, NetworkHarvestLocal.DIVISIBILITY))); } @@ -88,7 +86,7 @@ export class NetworkHarvestLocal extends Mosaic { * @param amount * @returns {NetworkHarvestLocal} */ - public static createAbsolute(amount: UInt64 | number) { + public static createAbsolute(amount: UInt64 | number): NetworkHarvestLocal { if (typeof amount === 'number') { return new NetworkHarvestLocal(UInt64.fromUint(amount)); } diff --git a/src/model/mosaic/ResolvedMosaic.ts b/src/model/mosaic/ResolvedMosaic.ts new file mode 100644 index 0000000000..50f078ea15 --- /dev/null +++ b/src/model/mosaic/ResolvedMosaic.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NamespaceName } from '../namespace/NamespaceName'; +import { Mosaic } from './Mosaic'; + +/** + * Resolved mosaic model with namespace name + */ +export type ResolvedMosaic = Mosaic & { namespaceName?: NamespaceName }; diff --git a/src/model/namespace/AddressAlias.ts b/src/model/namespace/AddressAlias.ts index cc8eb1ca60..6d49c42630 100644 --- a/src/model/namespace/AddressAlias.ts +++ b/src/model/namespace/AddressAlias.ts @@ -14,8 +14,8 @@ * limitations under the License. */ import { RawAddress } from '../../core/format/RawAddress'; -import {Address} from '../account/Address'; -import {Alias} from './Alias'; +import { Address } from '../account/Address'; +import { Alias } from './Alias'; import { AliasType } from './AliasType'; /** @@ -24,15 +24,16 @@ import { AliasType } from './AliasType'; * @since 0.10.2 */ export class AddressAlias extends Alias { - /** * Create AddressAlias object * @param content */ - constructor(/** - * The alias address - */ - public readonly address: Address) { + constructor( + /** + * The alias address + */ + public readonly address: Address, + ) { super(AliasType.Address, address, undefined); } diff --git a/src/model/namespace/Alias.ts b/src/model/namespace/Alias.ts index fd4266450c..49f70f891c 100644 --- a/src/model/namespace/Alias.ts +++ b/src/model/namespace/Alias.ts @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {Address} from '../account/Address'; -import {MosaicId} from '../mosaic/MosaicId'; +import { Address } from '../account/Address'; +import { MosaicId } from '../mosaic/MosaicId'; /** * Abtract class for Aliases @@ -46,8 +46,8 @@ export abstract class Alias { /** * The alias mosaicId */ - public readonly mosaicId?: MosaicId) { - } + public readonly mosaicId?: MosaicId, + ) {} /** * @internal diff --git a/src/model/namespace/EmptyAlias.ts b/src/model/namespace/EmptyAlias.ts index c03829fb45..0f9e1cf634 100644 --- a/src/model/namespace/EmptyAlias.ts +++ b/src/model/namespace/EmptyAlias.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {Alias} from './Alias'; +import { Alias } from './Alias'; import { AliasType } from './AliasType'; /** diff --git a/src/model/namespace/MosaicAlias.ts b/src/model/namespace/MosaicAlias.ts index 3af0f6a893..60448f7a3f 100644 --- a/src/model/namespace/MosaicAlias.ts +++ b/src/model/namespace/MosaicAlias.ts @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {MosaicId} from '../mosaic/MosaicId'; -import {Alias} from './Alias'; +import { MosaicId } from '../mosaic/MosaicId'; +import { Alias } from './Alias'; import { AliasType } from './AliasType'; /** @@ -23,15 +23,16 @@ import { AliasType } from './AliasType'; * @since 0.10.2 */ export class MosaicAlias extends Alias { - /** * Create AddressAlias object * @param mosaicId */ - constructor(/** - * The alias address - */ - public readonly mosaicId: MosaicId) { + constructor( + /** + * The alias address + */ + public readonly mosaicId: MosaicId, + ) { super(AliasType.Mosaic, undefined, mosaicId); } diff --git a/src/model/namespace/NamespaceId.ts b/src/model/namespace/NamespaceId.ts index 7f4e019077..3d12529cd6 100644 --- a/src/model/namespace/NamespaceId.ts +++ b/src/model/namespace/NamespaceId.ts @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {Convert as convert} from '../../core/format'; -import {NamespaceMosaicIdGenerator} from '../../infrastructure/transaction/NamespaceMosaicIdGenerator'; -import {Id} from '../Id'; +import { Convert as convert } from '../../core/format'; +import { NamespaceMosaicIdGenerator } from '../../infrastructure/transaction/NamespaceMosaicIdGenerator'; +import { Id } from '../Id'; /** * The namespace id structure describes namespace id @@ -23,7 +23,6 @@ import {Id} from '../Id'; * @since 1.0 */ export class NamespaceId { - /** * Namespace id */ @@ -56,7 +55,7 @@ export class NamespaceId { */ public static createFromEncoded(encoded: string): NamespaceId { const uint = convert.hexToUint8(encoded); - const hex = convert.uint8ToHex(uint); + const hex = convert.uint8ToHex(uint); const namespace = new NamespaceId(Id.fromHex(hex).toDTO()); return namespace; } @@ -84,7 +83,7 @@ export class NamespaceId { /** * Create DTO object */ - public toDTO() { + public toDTO(): any { return { id: this.id.toHex(), fullName: this.fullName ? this.fullName : '', diff --git a/src/model/namespace/NamespaceInfo.ts b/src/model/namespace/NamespaceInfo.ts index cd06cb0498..6d6a96b416 100644 --- a/src/model/namespace/NamespaceInfo.ts +++ b/src/model/namespace/NamespaceInfo.ts @@ -14,16 +14,15 @@ * limitations under the License. */ -import {PublicAccount} from '../account/PublicAccount'; -import {UInt64} from '../UInt64'; -import {Alias} from './Alias'; -import {NamespaceId} from './NamespaceId'; +import { PublicAccount } from '../account/PublicAccount'; +import { UInt64 } from '../UInt64'; +import { Alias } from './Alias'; +import { NamespaceId } from './NamespaceId'; /** * Object containing information of a namespace. */ export class NamespaceInfo { - /** * @param active * @param index @@ -36,52 +35,52 @@ export class NamespaceInfo { * @param startHeight * @param endHeight */ - constructor(/** - * Namespace is active. - */ - public readonly active: boolean, - /** - * The namespace index. - */ - public readonly index: number, - /** - * The meta data id. - */ - public readonly metaId: string, - /** - * The namespace registration type, namespace and sub namespace. - */ - private readonly registrationType: number, - /** - * The level of namespace. - */ - public readonly depth: number, - /** - * The namespace id levels. - */ - public readonly levels: NamespaceId[], - /** - * The namespace parent id. - */ - private readonly parentId: NamespaceId, - /** - * The owner of the namespace. - */ - public readonly owner: PublicAccount, - /** - * The height at which the ownership begins. - */ - public readonly startHeight: UInt64, - /** - * The height at which the ownership ends. - */ - public readonly endHeight: UInt64, - /** - * The alias linked to a namespace. - */ - public readonly alias: Alias) { - - } + constructor( + /** + * Namespace is active. + */ + public readonly active: boolean, + /** + * The namespace index. + */ + public readonly index: number, + /** + * The meta data id. + */ + public readonly metaId: string, + /** + * The namespace registration type, namespace and sub namespace. + */ + private readonly registrationType: number, + /** + * The level of namespace. + */ + public readonly depth: number, + /** + * The namespace id levels. + */ + public readonly levels: NamespaceId[], + /** + * The namespace parent id. + */ + private readonly parentId: NamespaceId, + /** + * The owner of the namespace. + */ + public readonly owner: PublicAccount, + /** + * The height at which the ownership begins. + */ + public readonly startHeight: UInt64, + /** + * The height at which the ownership ends. + */ + public readonly endHeight: UInt64, + /** + * The alias linked to a namespace. + */ + public readonly alias: Alias, + ) {} /** * Namespace id diff --git a/src/model/namespace/NamespaceInfoWithName.ts b/src/model/namespace/NamespaceInfoWithName.ts new file mode 100644 index 0000000000..181b7e5277 --- /dev/null +++ b/src/model/namespace/NamespaceInfoWithName.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NamespaceInfo } from './NamespaceInfo'; + +/** + * Resolved mosaic model with namespace name + */ +export type NamespaceInfoWithName = NamespaceInfo & { namespaceName?: string }; diff --git a/src/model/namespace/NamespaceName.ts b/src/model/namespace/NamespaceName.ts index ba7c5e24ba..50ce13c3c6 100644 --- a/src/model/namespace/NamespaceName.ts +++ b/src/model/namespace/NamespaceName.ts @@ -14,28 +14,28 @@ * limitations under the License. */ -import {NamespaceId} from './NamespaceId'; +import { NamespaceId } from './NamespaceId'; /** * The namespace name info structure describes basic information of a namespace and name. */ export class NamespaceName { - /** * @param namespaceId * @param name */ - constructor(/** - * The namespace id. - */ - public readonly namespaceId: NamespaceId, - /** - * The namespace name. - */ - public readonly name: string, - /** - * The parent id. - */ - public readonly parentId?: NamespaceId) { - } + constructor( + /** + * The namespace id. + */ + public readonly namespaceId: NamespaceId, + /** + * The namespace name. + */ + public readonly name: string, + /** + * The parent id. + */ + public readonly parentId?: NamespaceId, + ) {} } diff --git a/src/model/network/AccountLinkNetworkProperties.ts b/src/model/network/AccountLinkNetworkProperties.ts index f7616dc256..686fab47d2 100644 --- a/src/model/network/AccountLinkNetworkProperties.ts +++ b/src/model/network/AccountLinkNetworkProperties.ts @@ -15,10 +15,8 @@ */ export class AccountLinkNetworkProperties { - /** * @param dummy - to trigger plugin load. */ - constructor(public readonly dummy?: string) { - } + constructor(public readonly dummy?: string) {} } diff --git a/src/model/network/AccountRestrictionNetworkProperties.ts b/src/model/network/AccountRestrictionNetworkProperties.ts index d6a29dcbbc..cdde73d0cb 100644 --- a/src/model/network/AccountRestrictionNetworkProperties.ts +++ b/src/model/network/AccountRestrictionNetworkProperties.ts @@ -15,10 +15,8 @@ */ export class AccountRestrictionNetworkProperties { - /** * @param maxAccountRestrictionValues - Maximum number of account restriction values. */ - constructor(public readonly maxAccountRestrictionValues?: string) { - } + constructor(public readonly maxAccountRestrictionValues?: string) {} } diff --git a/src/model/network/AggregateNetworkProperties.ts b/src/model/network/AggregateNetworkProperties.ts index ae3f8f1dcb..648f10dc5b 100644 --- a/src/model/network/AggregateNetworkProperties.ts +++ b/src/model/network/AggregateNetworkProperties.ts @@ -14,7 +14,6 @@ * limitations under the License. */ - // tslint:disable: max-line-length export class AggregateNetworkProperties { /** * @param maxTransactionsPerAggregate - Maximum number of transactions per aggregate. @@ -23,10 +22,11 @@ export class AggregateNetworkProperties { * @param enableBondedAggregateSupport - Set to true if bonded aggregates should be allowed. Set to false if bonded aggregates should be rejected. * @param maxBondedTransactionLifetime - Maximum lifetime a bonded transaction can have before it expires. */ - constructor(public readonly maxTransactionsPerAggregate?: string, - public readonly maxCosignaturesPerAggregate?: string, - public readonly enableStrictCosignatureCheck?: boolean, - public readonly enableBondedAggregateSupport?: boolean, - public readonly maxBondedTransactionLifetime?: string) { - } + constructor( + public readonly maxTransactionsPerAggregate?: string, + public readonly maxCosignaturesPerAggregate?: string, + public readonly enableStrictCosignatureCheck?: boolean, + public readonly enableBondedAggregateSupport?: boolean, + public readonly maxBondedTransactionLifetime?: string, + ) {} } diff --git a/src/model/network/ChainProperties.ts b/src/model/network/ChainProperties.ts index 6de1d92b5b..3f6616550e 100644 --- a/src/model/network/ChainProperties.ts +++ b/src/model/network/ChainProperties.ts @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// tslint:disable: max-line-length /** * Chain related configuration properties. */ @@ -41,26 +40,27 @@ export class ChainProperties { * @param blockPruneInterval - Number of blocks between cache pruning. * @param maxTransactionsPerBlock - Maximum number of transactions per block. */ - constructor(public readonly enableVerifiableState?: boolean, - public readonly enableVerifiableReceipts?: boolean, - public readonly currencyMosaicId?: string, - public readonly harvestingMosaicId?: string, - public readonly blockGenerationTargetTime?: string, - public readonly blockTimeSmoothingFactor?: string, - public readonly importanceGrouping?: string, - public readonly importanceActivityPercentage?: string, - public readonly maxRollbackBlocks?: string, - public readonly maxDifficultyBlocks?: string, - public readonly defaultDynamicFeeMultiplier?: string, - public readonly maxTransactionLifetime?: string, - public readonly maxBlockFutureTime?: string, - public readonly initialCurrencyAtomicUnits?: string, - public readonly maxMosaicAtomicUnits?: string, - public readonly totalChainImportance?: string, - public readonly minHarvesterBalance?: string, - public readonly maxHarvesterBalance?: string, - public readonly harvestBeneficiaryPercentage?: string, - public readonly blockPruneInterval?: string, - public readonly maxTransactionsPerBlock?: string) { - } + constructor( + public readonly enableVerifiableState?: boolean, + public readonly enableVerifiableReceipts?: boolean, + public readonly currencyMosaicId?: string, + public readonly harvestingMosaicId?: string, + public readonly blockGenerationTargetTime?: string, + public readonly blockTimeSmoothingFactor?: string, + public readonly importanceGrouping?: string, + public readonly importanceActivityPercentage?: string, + public readonly maxRollbackBlocks?: string, + public readonly maxDifficultyBlocks?: string, + public readonly defaultDynamicFeeMultiplier?: string, + public readonly maxTransactionLifetime?: string, + public readonly maxBlockFutureTime?: string, + public readonly initialCurrencyAtomicUnits?: string, + public readonly maxMosaicAtomicUnits?: string, + public readonly totalChainImportance?: string, + public readonly minHarvesterBalance?: string, + public readonly maxHarvesterBalance?: string, + public readonly harvestBeneficiaryPercentage?: string, + public readonly blockPruneInterval?: string, + public readonly maxTransactionsPerBlock?: string, + ) {} } diff --git a/src/model/network/HashLockNetworkProperties.ts b/src/model/network/HashLockNetworkProperties.ts index 006354741c..30ff2a6b08 100644 --- a/src/model/network/HashLockNetworkProperties.ts +++ b/src/model/network/HashLockNetworkProperties.ts @@ -15,12 +15,9 @@ */ export class HashLockNetworkProperties { - /** * @param lockedFundsPerAggregate - Amount that has to be locked per aggregate in partial cache. * @param maxHashLockDuration - Maximum number of blocks for which a hash lock can exist. */ - constructor(public readonly lockedFundsPerAggregate?: string, - public readonly maxHashLockDuration?: string) { - } + constructor(public readonly lockedFundsPerAggregate?: string, public readonly maxHashLockDuration?: string) {} } diff --git a/src/model/network/MetadataNetworkProperties.ts b/src/model/network/MetadataNetworkProperties.ts index 6cb37e0291..0589326711 100644 --- a/src/model/network/MetadataNetworkProperties.ts +++ b/src/model/network/MetadataNetworkProperties.ts @@ -15,10 +15,8 @@ */ export class MetadataNetworkProperties { - /** * @param maxValueSize - Maximum metadata value size. */ - constructor(public readonly maxValueSize?: string) { - } + constructor(public readonly maxValueSize?: string) {} } diff --git a/src/model/network/MosaicNetworkProperties.ts b/src/model/network/MosaicNetworkProperties.ts index 0e2dc7d15c..c0e1675fc0 100644 --- a/src/model/network/MosaicNetworkProperties.ts +++ b/src/model/network/MosaicNetworkProperties.ts @@ -14,7 +14,7 @@ * limitations under the License. */ - export class MosaicNetworkProperties { +export class MosaicNetworkProperties { /** * @param maxMosaicsPerAccount - Maximum number of mosaics that an account can own. * @param maxMosaicDuration - Maximum mosaic duration. @@ -22,10 +22,11 @@ * @param mosaicRentalFeeSinkPublicKey - Public key of the mosaic rental fee sink account. * @param mosaicRentalFee - Mosaic rental fee. */ - constructor(public readonly maxMosaicsPerAccount?: string, - public readonly maxMosaicDuration?: string, - public readonly maxMosaicDivisibility?: string, - public readonly mosaicRentalFeeSinkPublicKey?: string, - public readonly mosaicRentalFee?: string) { - } + constructor( + public readonly maxMosaicsPerAccount?: string, + public readonly maxMosaicDuration?: string, + public readonly maxMosaicDivisibility?: string, + public readonly mosaicRentalFeeSinkPublicKey?: string, + public readonly mosaicRentalFee?: string, + ) {} } diff --git a/src/model/network/MosaicRestrictionNetworkProperties.ts b/src/model/network/MosaicRestrictionNetworkProperties.ts index c1565a59f1..90a441e816 100644 --- a/src/model/network/MosaicRestrictionNetworkProperties.ts +++ b/src/model/network/MosaicRestrictionNetworkProperties.ts @@ -15,10 +15,8 @@ */ export class MosaicRestrictionNetworkProperties { - /** * @param maxMosaicRestrictionValues - Maximum number of mosaic restriction values. */ - constructor(public readonly maxMosaicRestrictionValues?: string) { - } + constructor(public readonly maxMosaicRestrictionValues?: string) {} } diff --git a/src/model/network/MultisigNetworkProperties.ts b/src/model/network/MultisigNetworkProperties.ts index 9cc4342983..1e8167f283 100644 --- a/src/model/network/MultisigNetworkProperties.ts +++ b/src/model/network/MultisigNetworkProperties.ts @@ -15,14 +15,14 @@ */ export class MultisigNetworkProperties { - /** * @param maxMultisigDepth - Maximum number of multisig levels. * @param maxCosignatoriesPerAccount - Maximum number of cosignatories per account. * @param maxCosignedAccountsPerAccount - Maximum number of accounts a single account can cosign. */ - constructor(public readonly maxMultisigDepth?: string, - public readonly maxCosignatoriesPerAccount?: string, - public readonly maxCosignedAccountsPerAccount?: string) { - } + constructor( + public readonly maxMultisigDepth?: string, + public readonly maxCosignatoriesPerAccount?: string, + public readonly maxCosignedAccountsPerAccount?: string, + ) {} } diff --git a/src/model/network/NamespaceNetworkProperties.ts b/src/model/network/NamespaceNetworkProperties.ts index 74c1e1f776..b1e981e40d 100644 --- a/src/model/network/NamespaceNetworkProperties.ts +++ b/src/model/network/NamespaceNetworkProperties.ts @@ -15,7 +15,6 @@ */ export class NamespaceNetworkProperties { - /** * @param maxNameSize - Maximum namespace name size. * @param maxChildNamespaces - Maximum number of children for a root namespace. @@ -28,15 +27,16 @@ export class NamespaceNetworkProperties { * @param rootNamespaceRentalFeePerBlock - Root namespace rental fee per block. * @param childNamespaceRentalFee - Child namespace rental fee. */ - constructor(public readonly maxNameSize?: string, - public readonly maxChildNamespaces?: string, - public readonly maxNamespaceDepth?: string, - public readonly minNamespaceDuration?: string, - public readonly maxNamespaceDuration?: string, - public readonly namespaceGracePeriodDuration?: string, - public readonly reservedRootNamespaceNames?: string, - public readonly namespaceRentalFeeSinkPublicKey?: string, - public readonly rootNamespaceRentalFeePerBlock?: string, - public readonly childNamespaceRentalFee?: string) { - } + constructor( + public readonly maxNameSize?: string, + public readonly maxChildNamespaces?: string, + public readonly maxNamespaceDepth?: string, + public readonly minNamespaceDuration?: string, + public readonly maxNamespaceDuration?: string, + public readonly namespaceGracePeriodDuration?: string, + public readonly reservedRootNamespaceNames?: string, + public readonly namespaceRentalFeeSinkPublicKey?: string, + public readonly rootNamespaceRentalFeePerBlock?: string, + public readonly childNamespaceRentalFee?: string, + ) {} } diff --git a/src/model/network/NetworkConfiguration.ts b/src/model/network/NetworkConfiguration.ts index 56c9cec4ab..5413153835 100644 --- a/src/model/network/NetworkConfiguration.ts +++ b/src/model/network/NetworkConfiguration.ts @@ -22,14 +22,14 @@ import { PluginProperties } from './PluginProperties'; * Network Configuration */ export class NetworkConfiguration { - /** * @param network - Network related configuration properties. * @param chain - Chain related configuration properties. * @param plugins - Plugin related configuration properties. */ - constructor(public readonly network: NetworkProperties, - public readonly chain: ChainProperties, - public readonly plugins: PluginProperties) { - } + constructor( + public readonly network: NetworkProperties, + public readonly chain: ChainProperties, + public readonly plugins: PluginProperties, + ) {} } diff --git a/src/model/network/NetworkName.ts b/src/model/network/NetworkName.ts index 93ad34a06f..db4e1c37e2 100644 --- a/src/model/network/NetworkName.ts +++ b/src/model/network/NetworkName.ts @@ -18,11 +18,9 @@ * Network Name */ export class NetworkName { - /** * @param name - Network name * @param description - Network description */ - constructor(public readonly name: string, public readonly description: string) { - } + constructor(public readonly name: string, public readonly description: string) {} } diff --git a/src/model/network/NetworkProperties.ts b/src/model/network/NetworkProperties.ts index c32e2e94b6..8ac7a165c4 100644 --- a/src/model/network/NetworkProperties.ts +++ b/src/model/network/NetworkProperties.ts @@ -20,7 +20,6 @@ import { NodeIdentityEqualityStrategy } from 'symbol-openapi-typescript-node-cli * Network related configuration properties. */ export class NetworkProperties { - /** * @param identifier - Network identifier. * @param nodeEqualityStrategy - Node equality strategy. Defines if the identifier for the node must be its public key or host. @@ -28,10 +27,11 @@ export class NetworkProperties { * @param generationHash - Nemesis generation hash. * @param epochAdjustment - Nemesis epoch time adjustment. */ - constructor(public readonly identifier?: string, - public readonly nodeEqualityStrategy?: NodeIdentityEqualityStrategy, - public readonly publicKey?: string, - public readonly generationHash?: string, - public readonly epochAdjustment?: string) { - } + constructor( + public readonly identifier?: string, + public readonly nodeEqualityStrategy?: NodeIdentityEqualityStrategy, + public readonly publicKey?: string, + public readonly generationHash?: string, + public readonly epochAdjustment?: string, + ) {} } diff --git a/src/model/network/PluginProperties.ts b/src/model/network/PluginProperties.ts index 3fd8d90b7d..5c44b60cf1 100644 --- a/src/model/network/PluginProperties.ts +++ b/src/model/network/PluginProperties.ts @@ -31,7 +31,6 @@ import { TransferNetworkProperties } from './TransferNetworkProperties'; * Network related configuration properties. */ export class PluginProperties { - /** * @param accountlink - Network identifier. * @param aggregate - Nemesis public key. @@ -45,16 +44,17 @@ export class PluginProperties { * @param restrictionmosaic - * @param transfer - */ - constructor(public readonly accountlink?: AccountLinkNetworkProperties, - public readonly aggregate?: AggregateNetworkProperties, - public readonly lockhash?: HashLockNetworkProperties, - public readonly locksecret?: SecretLockNetworkProperties, - public readonly metadata?: MetadataNetworkProperties, - public readonly mosaic?: MosaicNetworkProperties, - public readonly multisig?: MultisigNetworkProperties, - public readonly namespace?: NamespaceNetworkProperties, - public readonly restrictionaccount?: AccountRestrictionNetworkProperties, - public readonly restrictionmosaic?: MosaicRestrictionNetworkProperties, - public readonly transfer?: TransferNetworkProperties) { - } + constructor( + public readonly accountlink?: AccountLinkNetworkProperties, + public readonly aggregate?: AggregateNetworkProperties, + public readonly lockhash?: HashLockNetworkProperties, + public readonly locksecret?: SecretLockNetworkProperties, + public readonly metadata?: MetadataNetworkProperties, + public readonly mosaic?: MosaicNetworkProperties, + public readonly multisig?: MultisigNetworkProperties, + public readonly namespace?: NamespaceNetworkProperties, + public readonly restrictionaccount?: AccountRestrictionNetworkProperties, + public readonly restrictionmosaic?: MosaicRestrictionNetworkProperties, + public readonly transfer?: TransferNetworkProperties, + ) {} } diff --git a/src/model/network/RentalFees.ts b/src/model/network/RentalFees.ts index 601dcce0c8..1f1784726a 100644 --- a/src/model/network/RentalFees.ts +++ b/src/model/network/RentalFees.ts @@ -14,20 +14,20 @@ * limitations under the License. */ - import { UInt64 } from '../UInt64'; +import { UInt64 } from '../UInt64'; /** * Rental Fees */ export class RentalFees { - // tslint:disable: max-line-length /** * @param effectiveRootNamespaceRentalFeePerBlock - Absolute amount. An amount of 123456789 (absolute) for a mosaic with divisibility 6 means 123.456789 (relative). * @param effectiveChildNamespaceRentalFee - Absolute amount. An amount of 123456789 (absolute) for a mosaic with divisibility 6 means 123.456789 (relative). * @param effectiveMosaicRentalFee - bsolute amount. An amount of 123456789 (absolute) for a mosaic with divisibility 6 means 123.456789 (relative). */ - constructor(public readonly effectiveRootNamespaceRentalFeePerBlock: UInt64, - public readonly effectiveChildNamespaceRentalFee: UInt64, - public readonly effectiveMosaicRentalFee: UInt64) { - } + constructor( + public readonly effectiveRootNamespaceRentalFeePerBlock: UInt64, + public readonly effectiveChildNamespaceRentalFee: UInt64, + public readonly effectiveMosaicRentalFee: UInt64, + ) {} } diff --git a/src/model/network/SecretLockNetworkProperties.ts b/src/model/network/SecretLockNetworkProperties.ts index 002cb9e214..a029668ecc 100644 --- a/src/model/network/SecretLockNetworkProperties.ts +++ b/src/model/network/SecretLockNetworkProperties.ts @@ -15,14 +15,14 @@ */ export class SecretLockNetworkProperties { - /** * @param maxSecretLockDuration - Maximum number of blocks for which a secret lock can exist. * @param minProofSize - Minimum size of a proof in bytes. * @param maxProofSize - Maximum size of a proof in bytes. */ - constructor(public readonly maxSecretLockDuration?: string, - public readonly minProofSize?: string, - public readonly maxProofSize?: string) { - } + constructor( + public readonly maxSecretLockDuration?: string, + public readonly minProofSize?: string, + public readonly maxProofSize?: string, + ) {} } diff --git a/src/model/network/TransactionFees.ts b/src/model/network/TransactionFees.ts index 25c3b75ba3..ee087c2b4c 100644 --- a/src/model/network/TransactionFees.ts +++ b/src/model/network/TransactionFees.ts @@ -18,16 +18,16 @@ * Transacation Fees */ export class TransactionFees { - /** * @param averageFeeMultiplier - Average fee multiplier over the last \"numBlocksTransactionFeeStats\". * @param medianFeeMultiplier - Median fee multiplier over the last \"numBlocksTransactionFeeStats\". * @param highestFeeMultiplier - Highest fee multiplier over the last "numBlocksTransactionFeeStats". * @param lowestFeeMultiplier - Lowest fee multiplier over the last "numBlocksTransactionFeeStats". */ - constructor(public readonly averageFeeMultiplier: number, - public readonly medianFeeMultiplier: number, - public readonly highestFeeMultiplier: number, - public readonly lowestFeeMultiplier: number) { - } + constructor( + public readonly averageFeeMultiplier: number, + public readonly medianFeeMultiplier: number, + public readonly highestFeeMultiplier: number, + public readonly lowestFeeMultiplier: number, + ) {} } diff --git a/src/model/network/TransferNetworkProperties.ts b/src/model/network/TransferNetworkProperties.ts index bac679f0d6..9ecc46de1a 100644 --- a/src/model/network/TransferNetworkProperties.ts +++ b/src/model/network/TransferNetworkProperties.ts @@ -15,10 +15,8 @@ */ export class TransferNetworkProperties { - /** * @param maxMessageSize - Maximum transaction message size. */ - constructor(public readonly maxMessageSize?: string) { - } + constructor(public readonly maxMessageSize?: string) {} } diff --git a/src/model/node/NodeHealth.ts b/src/model/node/NodeHealth.ts index 85a2dff18e..1a4c721ac5 100644 --- a/src/model/node/NodeHealth.ts +++ b/src/model/node/NodeHealth.ts @@ -20,17 +20,18 @@ import { NodeStatusEnum } from 'symbol-openapi-typescript-node-client'; * The node info structure describes basic information of a node health. */ export class NodeHealth { - /** * @param apiNode * @param db */ - constructor(/** - * The api node status - */ - public readonly apiNode: NodeStatusEnum, - /** - * The database status - */ - public readonly db: NodeStatusEnum ) {} + constructor( + /** + * The api node status + */ + public readonly apiNode: NodeStatusEnum, + /** + * The database status + */ + public readonly db: NodeStatusEnum, + ) {} } diff --git a/src/model/node/NodeInfo.ts b/src/model/node/NodeInfo.ts index e4f8198b02..5e1f0f9568 100644 --- a/src/model/node/NodeInfo.ts +++ b/src/model/node/NodeInfo.ts @@ -19,7 +19,6 @@ import { RoleType } from './RoleType'; * The node info structure describes basic information of a node. */ export class NodeInfo { - /** * @param publicKey * @param networkGenerationHash @@ -30,36 +29,38 @@ export class NodeInfo { * @param host * @param friendlyName */ - constructor(/** - * The public key used to identify the node. - */ - public readonly publicKey: string, - /** - * The network generation hash - */ - public readonly networkGenerationHash: string, - /** - * The port used for the communication. - */ - public readonly port: number, - /** - * The network identifier. - */ - public readonly networkIdentifier: NetworkType, - /** - * The version of the application. - */ - public readonly version: number, - /** - * The roles of the application. - */ - public readonly roles: RoleType, - /** - * The IP address of the endpoint. - */ - public readonly host: string, - /** - * The name of the node. - */ - public readonly friendlyName: string ) {} + constructor( + /** + * The public key used to identify the node. + */ + public readonly publicKey: string, + /** + * The network generation hash + */ + public readonly networkGenerationHash: string, + /** + * The port used for the communication. + */ + public readonly port: number, + /** + * The network identifier. + */ + public readonly networkIdentifier: NetworkType, + /** + * The version of the application. + */ + public readonly version: number, + /** + * The roles of the application. + */ + public readonly roles: RoleType, + /** + * The IP address of the endpoint. + */ + public readonly host: string, + /** + * The name of the node. + */ + public readonly friendlyName: string, + ) {} } diff --git a/src/model/node/NodeTime.ts b/src/model/node/NodeTime.ts index 6e8a26e5e7..8aa602c044 100644 --- a/src/model/node/NodeTime.ts +++ b/src/model/node/NodeTime.ts @@ -18,17 +18,18 @@ import { UInt64 } from '../UInt64'; * The node info structure describes basic information of a node. */ export class NodeTime { - /** * @param sendTimeStamp * @param receiveTimeStamp */ - constructor(/** - * The request send timestamp - */ - public readonly sendTimeStamp?: UInt64, - /** - * The request received timestamp - */ - public readonly receiveTimeStamp?: UInt64 ) {} + constructor( + /** + * The request send timestamp + */ + public readonly sendTimeStamp?: UInt64, + /** + * The request received timestamp + */ + public readonly receiveTimeStamp?: UInt64, + ) {} } diff --git a/src/model/node/ServerInfo.ts b/src/model/node/ServerInfo.ts index 754555391e..338b36d76b 100644 --- a/src/model/node/ServerInfo.ts +++ b/src/model/node/ServerInfo.ts @@ -18,19 +18,18 @@ * The server information. */ export class ServerInfo { - /** * @param restVersion - The catapult-rest component version * @param sdkVersion - the catapult-sdk component version */ - constructor(/** - * The catapult-rest component version - */ - public readonly restVersion: string, - /** - * the catapult-sdk component version - */ - public readonly sdkVersion: string) { - - } + constructor( + /** + * The catapult-rest component version + */ + public readonly restVersion: string, + /** + * the catapult-sdk component version + */ + public readonly sdkVersion: string, + ) {} } diff --git a/src/model/receipt/ArtifactExpiryReceipt.ts b/src/model/receipt/ArtifactExpiryReceipt.ts index 41fff14395..a83c752a81 100644 --- a/src/model/receipt/ArtifactExpiryReceipt.ts +++ b/src/model/receipt/ArtifactExpiryReceipt.ts @@ -25,7 +25,6 @@ import { ReceiptVersion } from './ReceiptVersion'; * Artifact Expiry: An artifact (e.g. namespace, mosaic) expired. */ export class ArtifactExpiryReceipt extends Receipt { - /** * Artifact expiry receipt * @param artifactId -The id of the artifact (eg. namespace, mosaic). @@ -33,10 +32,7 @@ export class ArtifactExpiryReceipt extends Receipt { * @param type - The receipt type * @param size - the receipt size */ - constructor(public readonly artifactId: MosaicId | NamespaceId, - version: ReceiptVersion, - type: ReceiptType, - size?: number) { + constructor(public readonly artifactId: MosaicId | NamespaceId, version: ReceiptVersion, type: ReceiptType, size?: number) { super(version, type, size); } @@ -47,10 +43,16 @@ export class ArtifactExpiryReceipt extends Receipt { */ public serialize(): Uint8Array { if (this.artifactId instanceof MosaicId) { - return new MosaicExpiryReceiptBuilder(ReceiptVersion.ARTIFACT_EXPIRY, this.type.valueOf(), - new MosaicIdDto(this.artifactId.toDTO())).serialize(); + return new MosaicExpiryReceiptBuilder( + ReceiptVersion.ARTIFACT_EXPIRY, + this.type.valueOf(), + new MosaicIdDto(this.artifactId.toDTO()), + ).serialize(); } - return new NamespaceExpiryReceiptBuilder(ReceiptVersion.ARTIFACT_EXPIRY, this.type.valueOf(), - new NamespaceIdDto(this.artifactId.id.toDTO())).serialize(); + return new NamespaceExpiryReceiptBuilder( + ReceiptVersion.ARTIFACT_EXPIRY, + this.type.valueOf(), + new NamespaceIdDto(this.artifactId.id.toDTO()), + ).serialize(); } } diff --git a/src/model/receipt/BalanceChangeReceipt.ts b/src/model/receipt/BalanceChangeReceipt.ts index 8d4ab88998..3a5587a7b6 100644 --- a/src/model/receipt/BalanceChangeReceipt.ts +++ b/src/model/receipt/BalanceChangeReceipt.ts @@ -27,7 +27,6 @@ import { ReceiptVersion } from './ReceiptVersion'; * Balance Change: A mosaic credit or debit was triggered. */ export class BalanceChangeReceipt extends Receipt { - /** * Balance change expiry receipt * @param targetPublicAccount - The target account public account. @@ -38,21 +37,22 @@ export class BalanceChangeReceipt extends Receipt { * @param size - the receipt size */ constructor( - /** - * The target targetPublicKey public account. - */ - public readonly targetPublicAccount: PublicAccount, - /** - * The mosaic id. - */ - public readonly mosaicId: MosaicId, - /** - * The amount of mosaic. - */ - public readonly amount: UInt64, - version: ReceiptVersion, - type: ReceiptType, - size?: number) { + /** + * The target targetPublicKey public account. + */ + public readonly targetPublicAccount: PublicAccount, + /** + * The mosaic id. + */ + public readonly mosaicId: MosaicId, + /** + * The amount of mosaic. + */ + public readonly amount: UInt64, + version: ReceiptVersion, + type: ReceiptType, + size?: number, + ) { super(version, type, size); } @@ -62,7 +62,9 @@ export class BalanceChangeReceipt extends Receipt { * @return {Uint8Array} */ public serialize(): Uint8Array { - return new BalanceChangeReceiptBuilder(ReceiptVersion.BALANCE_CHANGE, this.type.valueOf(), + return new BalanceChangeReceiptBuilder( + ReceiptVersion.BALANCE_CHANGE, + this.type.valueOf(), new MosaicBuilder(new MosaicIdDto(this.mosaicId.toDTO()), new AmountDto(this.amount.toDTO())), new KeyDto(Convert.hexToUint8(this.targetPublicAccount.publicKey)), ).serialize(); diff --git a/src/model/receipt/BalanceTransferReceipt.ts b/src/model/receipt/BalanceTransferReceipt.ts index 93b88da304..9082a50511 100644 --- a/src/model/receipt/BalanceTransferReceipt.ts +++ b/src/model/receipt/BalanceTransferReceipt.ts @@ -30,7 +30,6 @@ import { ReceiptVersion } from './ReceiptVersion'; * Balance Transfer: A mosaic transfer was triggered. */ export class BalanceTransferReceipt extends Receipt { - /** * Balance transfer expiry receipt * @param sender - The public account of the sender. @@ -42,25 +41,26 @@ export class BalanceTransferReceipt extends Receipt { * @param size - the receipt size */ constructor( - /** - * The public account of the sender. - */ - public readonly sender: PublicAccount, - /** - * The mosaic recipient address. - */ - public readonly recipientAddress: Address | NamespaceId, - /** - * The mosaic id. - */ - public readonly mosaicId: MosaicId, - /** - * The amount of mosaic. - */ - public readonly amount: UInt64, - version: ReceiptVersion, - type: ReceiptType, - size?: number) { + /** + * The public account of the sender. + */ + public readonly sender: PublicAccount, + /** + * The mosaic recipient address. + */ + public readonly recipientAddress: Address | NamespaceId, + /** + * The mosaic id. + */ + public readonly mosaicId: MosaicId, + /** + * The amount of mosaic. + */ + public readonly amount: UInt64, + version: ReceiptVersion, + type: ReceiptType, + size?: number, + ) { super(version, type, size); } @@ -70,7 +70,9 @@ export class BalanceTransferReceipt extends Receipt { * @return {Uint8Array} */ public serialize(): Uint8Array { - return new BalanceTransferReceiptBuilder(ReceiptVersion.BALANCE_TRANSFER, this.type.valueOf(), + return new BalanceTransferReceiptBuilder( + ReceiptVersion.BALANCE_TRANSFER, + this.type.valueOf(), new MosaicBuilder(new MosaicIdDto(this.mosaicId.toDTO()), new AmountDto(this.amount.toDTO())), new KeyDto(Convert.hexToUint8(this.sender.publicKey)), new AddressDto(this.getRecipientBytes()), diff --git a/src/model/receipt/InflationReceipt.ts b/src/model/receipt/InflationReceipt.ts index f24b64ab40..ae95972595 100644 --- a/src/model/receipt/InflationReceipt.ts +++ b/src/model/receipt/InflationReceipt.ts @@ -25,7 +25,6 @@ import { ReceiptVersion } from './ReceiptVersion'; * Balance Transfer: A mosaic transfer was triggered. */ export class InflationReceipt extends Receipt { - /** * Balance transfer expiry receipt * @param mosaicId - The mosaic id. @@ -35,17 +34,18 @@ export class InflationReceipt extends Receipt { * @param size - the receipt size */ constructor( - /** - * The mosaic id. - */ - public readonly mosaicId: MosaicId, - /** - * The amount of mosaic. - */ - public readonly amount: UInt64, - version: ReceiptVersion, - type: ReceiptType, - size?: number) { + /** + * The mosaic id. + */ + public readonly mosaicId: MosaicId, + /** + * The amount of mosaic. + */ + public readonly amount: UInt64, + version: ReceiptVersion, + type: ReceiptType, + size?: number, + ) { super(version, type, size); } @@ -55,8 +55,9 @@ export class InflationReceipt extends Receipt { * @return {Uint8Array} */ public serialize(): Uint8Array { - return new InflationReceiptBuilder( - ReceiptVersion.INFLATION_RECEIPT, this.type.valueOf(), + return new InflationReceiptBuilder( + ReceiptVersion.INFLATION_RECEIPT, + this.type.valueOf(), new MosaicBuilder(new MosaicIdDto(this.mosaicId.toDTO()), new AmountDto(this.amount.toDTO())), ).serialize(); } diff --git a/src/model/receipt/Receipt.ts b/src/model/receipt/Receipt.ts index c020191cdf..0f0ad51457 100644 --- a/src/model/receipt/Receipt.ts +++ b/src/model/receipt/Receipt.ts @@ -21,7 +21,6 @@ import { ReceiptVersion } from './ReceiptVersion'; * An abstract transaction class that serves as the base class of all receipts. */ export abstract class Receipt { - /** * @constructor * @param size @@ -29,19 +28,19 @@ export abstract class Receipt { * @param type */ constructor( - /** - * The receipt version. - */ - public readonly version: ReceiptVersion, - /** - * The receipt type. - */ - public readonly type: ReceiptType, - /** - * The receipt size. - */ - public readonly size?: number) { - } + /** + * The receipt version. + */ + public readonly version: ReceiptVersion, + /** + * The receipt type. + */ + public readonly type: ReceiptType, + /** + * The receipt size. + */ + public readonly size?: number, + ) {} /** * @internal diff --git a/src/model/receipt/ReceiptSource.ts b/src/model/receipt/ReceiptSource.ts index 3a293cbb62..f46346a9ad 100644 --- a/src/model/receipt/ReceiptSource.ts +++ b/src/model/receipt/ReceiptSource.ts @@ -20,22 +20,21 @@ import { GeneratorUtils } from 'catbuffer-typescript'; * The receipt source object. */ export class ReceiptSource { - /** * @constructor * @param primaryId - The transaction primary source (e.g. index within block). * @param secondaryId - The transaction secondary source (e.g. index within aggregate). */ constructor( - /** - * The transaction primary source (e.g. index within block). - */ - public readonly primaryId: number, - /** - * The transaction secondary source (e.g. index within aggregate). - */ - public readonly secondaryId: number) { - } + /** + * The transaction primary source (e.g. index within block). + */ + public readonly primaryId: number, + /** + * The transaction secondary source (e.g. index within aggregate). + */ + public readonly secondaryId: number, + ) {} /** * @internal @@ -44,6 +43,8 @@ export class ReceiptSource { */ public serialize(): Uint8Array { return GeneratorUtils.concatTypedArrays( - GeneratorUtils.uintToBuffer(this.primaryId, 4), GeneratorUtils.uintToBuffer(this.secondaryId, 4)); + GeneratorUtils.uintToBuffer(this.primaryId, 4), + GeneratorUtils.uintToBuffer(this.secondaryId, 4), + ); } } diff --git a/src/model/receipt/ReceiptType.ts b/src/model/receipt/ReceiptType.ts index 74a1314360..0652e0fc74 100644 --- a/src/model/receipt/ReceiptType.ts +++ b/src/model/receipt/ReceiptType.ts @@ -21,7 +21,6 @@ * @see https://github.com/nemtech/catapult-server/blob/master/src/catapult/model/ReceiptType.cpp */ export enum ReceiptType { - /** * The recipient, account and amount of fees received for harvesting a block. It is recorded when a block is harvested. */ @@ -29,41 +28,41 @@ export enum ReceiptType { /** * The unresolved and resolved alias. It is recorded when a transaction indicates a valid address alias instead of an address. */ - Address_Alias_Resolution = 0xF143, + Address_Alias_Resolution = 0xf143, /** * The unresolved and resolved alias. It is recorded when a transaction indicates a valid mosaic alias instead of a mosaicId. */ - Mosaic_Alias_Resolution = 0xF243, + Mosaic_Alias_Resolution = 0xf243, /** * A collection of state changes for a given source. It is recorded when a state change receipt is issued. */ - Transaction_Group = 0xE143, + Transaction_Group = 0xe143, /** * The mosaicId expiring in this block. It is recorded when a mosaic expires. */ - Mosaic_Expired = 0x414D, + Mosaic_Expired = 0x414d, /** * The sender and recipient of the levied mosaic, the mosaicId and amount. It is recorded when a transaction has a levied mosaic. */ - Mosaic_Levy = 0x124D, + Mosaic_Levy = 0x124d, /** * The sender and recipient of the mosaicId and amount representing the cost of registering the mosaic. * It is recorded when a mosaic is registered. */ - Mosaic_Rental_Fee = 0x124D, + Mosaic_Rental_Fee = 0x124d, /** * The identifier of the namespace expiring in this block. It is recorded when the namespace lifetime elapses. */ - Namespace_Expired = 0x414E, + Namespace_Expired = 0x414e, /** * The sender and recipient of the mosaicId and amount representing the cost of extending the namespace. * It is recorded when a namespace is registered or its duration is extended. */ - Namespace_Rental_Fee = 0x134E, + Namespace_Rental_Fee = 0x134e, /** * The identifier of the namespace deleted in this block. It is recorded when the namespace grace period elapses. */ - Namespace_Deleted = 0x424E, + Namespace_Deleted = 0x424e, /** * The lockhash sender, mosaicId and amount locked. It is recorded when a valid HashLockTransaction is announced. */ diff --git a/src/model/receipt/ReceiptVersion.ts b/src/model/receipt/ReceiptVersion.ts index 191a7b2828..2e746c8a10 100644 --- a/src/model/receipt/ReceiptVersion.ts +++ b/src/model/receipt/ReceiptVersion.ts @@ -21,7 +21,6 @@ * @see https://github.com/nemtech/catapult-server/blob/master/src/catapult/model/ReceiptType.cpp */ export class ReceiptVersion { - /** * Balance transfer receipt version. * @type {number} diff --git a/src/model/receipt/ResolutionEntry.ts b/src/model/receipt/ResolutionEntry.ts index 7866ff56a1..21bb59ac9b 100644 --- a/src/model/receipt/ResolutionEntry.ts +++ b/src/model/receipt/ResolutionEntry.ts @@ -25,22 +25,21 @@ import { ReceiptSource } from './ReceiptSource'; * The receipt source object. */ export class ResolutionEntry { - /** * @constructor * @param resolved - A resolved address or resolved mosaicId (alias). * @param source - The receipt source. */ constructor( - /** - * A resolved address or resolved mosaicId (alias). - */ - public readonly resolved: Address | MosaicId, - /** - * The receipt source. - */ - public readonly source: ReceiptSource) { - } + /** + * A resolved address or resolved mosaicId (alias). + */ + public readonly resolved: Address | MosaicId, + /** + * The receipt source. + */ + public readonly source: ReceiptSource, + ) {} /** * @internal @@ -48,13 +47,13 @@ export class ResolutionEntry { * @return {Uint8Array} */ public serialize(): Uint8Array { - let resolvedBytes: Uint8Array; - if (this.resolved instanceof Address) { - resolvedBytes = RawAddress.stringToAddress((this.resolved as Address).plain()); - } else { - resolvedBytes = GeneratorUtils.uint64ToBuffer(UInt64.fromHex((this.resolved as MosaicId).toHex()).toDTO()); - } - const sourceBytes = this.source.serialize(); - return GeneratorUtils.concatTypedArrays(resolvedBytes, sourceBytes); + let resolvedBytes: Uint8Array; + if (this.resolved instanceof Address) { + resolvedBytes = RawAddress.stringToAddress((this.resolved as Address).plain()); + } else { + resolvedBytes = GeneratorUtils.uint64ToBuffer(UInt64.fromHex((this.resolved as MosaicId).toHex()).toDTO()); + } + const sourceBytes = this.source.serialize(); + return GeneratorUtils.concatTypedArrays(resolvedBytes, sourceBytes); } } diff --git a/src/model/receipt/ResolutionStatement.ts b/src/model/receipt/ResolutionStatement.ts index ed2e536b8a..790bd3b2e0 100644 --- a/src/model/receipt/ResolutionStatement.ts +++ b/src/model/receipt/ResolutionStatement.ts @@ -14,14 +14,17 @@ * limitations under the License. */ -import { AddressDto, - AddressResolutionEntryBuilder, - AddressResolutionStatementBuilder, - MosaicIdDto, MosaicResolutionEntryBuilder, - MosaicResolutionStatementBuilder, - ReceiptSourceBuilder, - UnresolvedAddressDto, - UnresolvedMosaicIdDto } from 'catbuffer-typescript'; +import { + AddressDto, + AddressResolutionEntryBuilder, + AddressResolutionStatementBuilder, + MosaicIdDto, + MosaicResolutionEntryBuilder, + MosaicResolutionStatementBuilder, + ReceiptSourceBuilder, + UnresolvedAddressDto, + UnresolvedMosaicIdDto, +} from 'catbuffer-typescript'; import { sha3_256 } from 'js-sha3'; import { RawAddress } from '../../core/format/RawAddress'; import { UnresolvedMapping } from '../../core/utils/UnresolvedMapping'; @@ -41,7 +44,6 @@ import { ResolutionType } from './ResolutionType'; * - Mosaic Resolution: A mosaic alias was used in the block. */ export class ResolutionStatement { - /** * Receipt - resolution statement object * @param resolutionType - The resolution type @@ -50,23 +52,23 @@ export class ResolutionStatement { * @param resolutionEntries - The array of resolution entries. */ constructor( - /** - * Resolution type - */ - public readonly resolutionType: ResolutionType, - /** - * The block height. - */ - public readonly height: UInt64, - /** - * An unresolved address or unresolved mosaicId. - */ - public readonly unresolved: Address | MosaicId | NamespaceId, - /** - * The array of resolution entries. - */ - public readonly resolutionEntries: ResolutionEntry[]) { - } + /** + * Resolution type + */ + public readonly resolutionType: ResolutionType, + /** + * The block height. + */ + public readonly height: UInt64, + /** + * An unresolved address or unresolved mosaicId. + */ + public readonly unresolved: Address | MosaicId | NamespaceId, + /** + * The array of resolution entries. + */ + public readonly resolutionEntries: ResolutionEntry[], + ) {} /** * Generate receipt hash @@ -74,23 +76,36 @@ export class ResolutionStatement { * @return {string} receipt hash in hex */ public generateHash(networkType: NetworkType): string { - const type = this.resolutionType === ResolutionType.Address ? ReceiptType.Address_Alias_Resolution - : ReceiptType.Mosaic_Alias_Resolution; - const builder = this.resolutionType === ResolutionType.Address ? new AddressResolutionStatementBuilder( - ReceiptVersion.RESOLUTION_STATEMENT, type.valueOf(), - new UnresolvedAddressDto(UnresolvedMapping.toUnresolvedAddressBytes(this.unresolved as Address | NamespaceId, networkType)), - this.resolutionEntries.map((entry) => new AddressResolutionEntryBuilder( - new ReceiptSourceBuilder(entry.source.primaryId, entry.source.secondaryId), - new AddressDto(RawAddress.stringToAddress((entry.resolved as Address).plain())), - )), - ) : new MosaicResolutionStatementBuilder(ReceiptVersion.RESOLUTION_STATEMENT, - type.valueOf(), - new UnresolvedMosaicIdDto(UInt64.fromHex((this.unresolved as MosaicId | NamespaceId).toHex()).toDTO()), - this.resolutionEntries.map((entry) => new MosaicResolutionEntryBuilder( - new ReceiptSourceBuilder(entry.source.primaryId, entry.source.secondaryId), - new MosaicIdDto((entry.resolved as MosaicId).toDTO()), - )), - ); + const type = + this.resolutionType === ResolutionType.Address ? ReceiptType.Address_Alias_Resolution : ReceiptType.Mosaic_Alias_Resolution; + const builder = + this.resolutionType === ResolutionType.Address + ? new AddressResolutionStatementBuilder( + ReceiptVersion.RESOLUTION_STATEMENT, + type.valueOf(), + new UnresolvedAddressDto( + UnresolvedMapping.toUnresolvedAddressBytes(this.unresolved as Address | NamespaceId, networkType), + ), + this.resolutionEntries.map( + (entry) => + new AddressResolutionEntryBuilder( + new ReceiptSourceBuilder(entry.source.primaryId, entry.source.secondaryId), + new AddressDto(RawAddress.stringToAddress((entry.resolved as Address).plain())), + ), + ), + ) + : new MosaicResolutionStatementBuilder( + ReceiptVersion.RESOLUTION_STATEMENT, + type.valueOf(), + new UnresolvedMosaicIdDto(UInt64.fromHex((this.unresolved as MosaicId | NamespaceId).toHex()).toDTO()), + this.resolutionEntries.map( + (entry) => + new MosaicResolutionEntryBuilder( + new ReceiptSourceBuilder(entry.source.primaryId, entry.source.secondaryId), + new MosaicIdDto((entry.resolved as MosaicId).toDTO()), + ), + ), + ); const hasher = sha3_256.create(); hasher.update(builder.serialize()); return hasher.hex().toUpperCase(); @@ -139,9 +154,11 @@ export class ResolutionStatement { Transaction: [Inx:3(2+1), AggInx:0] It should return Entry: {P:2, S:0} */ - return this.resolutionEntries - .find((entry) => entry.source.primaryId === resolvedPrimaryId && - entry.source.secondaryId === this.getMaxSecondaryIdByPrimaryId(resolvedPrimaryId)); + return this.resolutionEntries.find( + (entry) => + entry.source.primaryId === resolvedPrimaryId && + entry.source.secondaryId === this.getMaxSecondaryIdByPrimaryId(resolvedPrimaryId), + ); } // When transaction index matches a primaryId, get the most recent secondaryId (resolvedPrimaryId can only <= primaryId) @@ -159,8 +176,11 @@ export class ResolutionStatement { */ if (resolvedSecondaryId === 0 && resolvedSecondaryId !== secondaryId) { const lastPrimaryId = this.getMaxAvailablePrimaryId(resolvedPrimaryId - 1); - return this.resolutionEntries.find((entry) => entry.source.primaryId === lastPrimaryId && - entry.source.secondaryId === this.getMaxSecondaryIdByPrimaryId(lastPrimaryId)); + return this.resolutionEntries.find( + (entry) => + entry.source.primaryId === lastPrimaryId && + entry.source.secondaryId === this.getMaxSecondaryIdByPrimaryId(lastPrimaryId), + ); } /* @@ -171,8 +191,9 @@ export class ResolutionStatement { Transaction: [Inx:5(4+1), AggInx:6(2+1)] It should return Entry: {P:5, S:6} */ - return this.resolutionEntries - .find((entry) => entry.source.primaryId === resolvedPrimaryId && entry.source.secondaryId === resolvedSecondaryId); + return this.resolutionEntries.find( + (entry) => entry.source.primaryId === resolvedPrimaryId && entry.source.secondaryId === resolvedSecondaryId, + ); } /** @@ -182,8 +203,11 @@ export class ResolutionStatement { * @returns {number} */ private getMaxSecondaryIdByPrimaryId(primaryId: number): number { - return Math.max(...this.resolutionEntries.filter((entry) => entry.source.primaryId === primaryId) - .map((filtered) => filtered.source.secondaryId)); + return Math.max( + ...this.resolutionEntries + .filter((entry) => entry.source.primaryId === primaryId) + .map((filtered) => filtered.source.secondaryId), + ); } /** @@ -193,8 +217,11 @@ export class ResolutionStatement { * @returns {number} */ private getMaxSecondaryIdByPrimaryIdAndSecondaryId(primaryId: number, secondaryId: number): number { - return Math.max(...this.resolutionEntries.filter((entry) => entry.source.primaryId === primaryId) - .map((filtered) => secondaryId >= filtered.source.secondaryId ? filtered.source.secondaryId : 0)); + return Math.max( + ...this.resolutionEntries + .filter((entry) => entry.source.primaryId === primaryId) + .map((filtered) => (secondaryId >= filtered.source.secondaryId ? filtered.source.secondaryId : 0)), + ); } /** @@ -204,7 +231,6 @@ export class ResolutionStatement { * @returns {number} */ private getMaxAvailablePrimaryId(primaryId: number): number { - return Math.max(...this.resolutionEntries - .map((entry) => primaryId >= entry.source.primaryId ? entry.source.primaryId : 0)); + return Math.max(...this.resolutionEntries.map((entry) => (primaryId >= entry.source.primaryId ? entry.source.primaryId : 0))); } } diff --git a/src/model/receipt/Statement.ts b/src/model/receipt/Statement.ts index 4753c63498..a681976906 100644 --- a/src/model/receipt/Statement.ts +++ b/src/model/receipt/Statement.ts @@ -23,7 +23,6 @@ import { ResolutionType } from './ResolutionType'; import { TransactionStatement } from './TransactionStatement'; export class Statement { - /** * Receipt - transaction statement object * @param transactionStatements - The transaction statements. @@ -31,19 +30,19 @@ export class Statement { * @param mosaicResolutionStatements - The mosaic resolution statements. */ constructor( - /** - * The transaction statements. - */ - public readonly transactionStatements: TransactionStatement[], - /** - * The address resolution statements. - */ - public readonly addressResolutionStatements: ResolutionStatement[], - /** - * The mosaic resolution statements. - */ - public readonly mosaicResolutionStatements: ResolutionStatement[]) { - } + /** + * The transaction statements. + */ + public readonly transactionStatements: TransactionStatement[], + /** + * The address resolution statements. + */ + public readonly addressResolutionStatements: ResolutionStatement[], + /** + * The mosaic resolution statements. + */ + public readonly mosaicResolutionStatements: ResolutionStatement[], + ) {} /** * Resolve unresolvedAddress from statement @@ -53,14 +52,21 @@ export class Statement { * @param aggregateTransactionIndex Aggregate transaction index * @returns {Address} */ - public resolveAddress(unresolvedAddress: Address | NamespaceId, - height: string, - transactionIndex: number, - aggregateTransactionIndex: number = 0): Address { - return unresolvedAddress instanceof NamespaceId ? - this.getResolvedFromReceipt(ResolutionType.Address, unresolvedAddress as NamespaceId, - transactionIndex, height, aggregateTransactionIndex) as Address : - unresolvedAddress; + public resolveAddress( + unresolvedAddress: Address | NamespaceId, + height: string, + transactionIndex: number, + aggregateTransactionIndex = 0, + ): Address { + return unresolvedAddress instanceof NamespaceId + ? (this.getResolvedFromReceipt( + ResolutionType.Address, + unresolvedAddress as NamespaceId, + transactionIndex, + height, + aggregateTransactionIndex, + ) as Address) + : unresolvedAddress; } /** @@ -71,14 +77,21 @@ export class Statement { * @param aggregateTransactionIndex Aggregate transaction index * @returns {MosaicId} */ - public resolveMosaicId(unresolvedMosaicId: MosaicId | NamespaceId, - height: string, - transactionIndex: number, - aggregateTransactionIndex: number = 0): MosaicId { - return unresolvedMosaicId instanceof NamespaceId ? - this.getResolvedFromReceipt(ResolutionType.Mosaic, unresolvedMosaicId as NamespaceId, - transactionIndex, height, aggregateTransactionIndex) as MosaicId : - unresolvedMosaicId; + public resolveMosaicId( + unresolvedMosaicId: MosaicId | NamespaceId, + height: string, + transactionIndex: number, + aggregateTransactionIndex = 0, + ): MosaicId { + return unresolvedMosaicId instanceof NamespaceId + ? (this.getResolvedFromReceipt( + ResolutionType.Mosaic, + unresolvedMosaicId as NamespaceId, + transactionIndex, + height, + aggregateTransactionIndex, + ) as MosaicId) + : unresolvedMosaicId; } /** @@ -89,14 +102,19 @@ export class Statement { * @param aggregateTransactionIndex Aggregate transaction index * @returns {Mosaic} */ - public resolveMosaic(unresolvedMosaic: Mosaic, - height: string, - transactionIndex: number, - aggregateTransactionIndex: number = 0): Mosaic { - return unresolvedMosaic.id instanceof NamespaceId ? - new Mosaic(this.getResolvedFromReceipt(ResolutionType.Mosaic, unresolvedMosaic.id as NamespaceId, - transactionIndex, height, aggregateTransactionIndex) as MosaicId, unresolvedMosaic.amount) : - unresolvedMosaic; + public resolveMosaic(unresolvedMosaic: Mosaic, height: string, transactionIndex: number, aggregateTransactionIndex = 0): Mosaic { + return unresolvedMosaic.id instanceof NamespaceId + ? new Mosaic( + this.getResolvedFromReceipt( + ResolutionType.Mosaic, + unresolvedMosaic.id as NamespaceId, + transactionIndex, + height, + aggregateTransactionIndex, + ) as MosaicId, + unresolvedMosaic.amount, + ) + : unresolvedMosaic; } /** @@ -109,15 +127,17 @@ export class Statement { * @param aggregateTransactionIndex Transaction index for aggregate * @returns {MosaicId | Address} */ - private getResolvedFromReceipt(resolutionType: ResolutionType, - unresolved: NamespaceId, - transactionIndex: number, - height: string, - aggregateTransactionIndex?: number): MosaicId | Address { - - const resolutionStatement = (resolutionType === ResolutionType.Address ? this.addressResolutionStatements : - this.mosaicResolutionStatements).find((resolution) => resolution.height.toString() === height && - (resolution.unresolved as NamespaceId).equals(unresolved)); + private getResolvedFromReceipt( + resolutionType: ResolutionType, + unresolved: NamespaceId, + transactionIndex: number, + height: string, + aggregateTransactionIndex?: number, + ): MosaicId | Address { + const resolutionStatement = (resolutionType === ResolutionType.Address + ? this.addressResolutionStatements + : this.mosaicResolutionStatements + ).find((resolution) => resolution.height.toString() === height && (resolution.unresolved as NamespaceId).equals(unresolved)); if (!resolutionStatement) { throw new Error(`No resolution statement found on block: ${height} for unresolved: ${unresolved.toHex()}`); diff --git a/src/model/receipt/TransactionStatement.ts b/src/model/receipt/TransactionStatement.ts index a7c1374c7f..5f04c7e76f 100644 --- a/src/model/receipt/TransactionStatement.ts +++ b/src/model/receipt/TransactionStatement.ts @@ -29,7 +29,6 @@ import { ReceiptVersion } from './ReceiptVersion'; * - Artifact Expiry: An artifact (e.g. namespace, mosaic) expired. */ export class TransactionStatement { - /** * Receipt - transaction statement object * @param height - The block height @@ -37,19 +36,19 @@ export class TransactionStatement { * @param receipts - The array of receipt headers. */ constructor( - /** - * The block height. - */ - public readonly height: UInt64, - /** - * The receipt source. - */ - public readonly source: ReceiptSource, - /** - * The array of receipt headers. - */ - public readonly receipts: Receipt[]) { - } + /** + * The block height. + */ + public readonly height: UInt64, + /** + * The receipt source. + */ + public readonly source: ReceiptSource, + /** + * The array of receipt headers. + */ + public readonly receipts: Receipt[], + ) {} /** * Generate receipt hash diff --git a/src/model/restriction/AccountRestriction.ts b/src/model/restriction/AccountRestriction.ts index 5c2fa8a9e1..41a318bc45 100644 --- a/src/model/restriction/AccountRestriction.ts +++ b/src/model/restriction/AccountRestriction.ts @@ -19,22 +19,19 @@ import { AccountRestrictionFlags } from './AccountRestrictionType'; * Account restriction structure describes restriction information. */ export class AccountRestriction { - /** * Constructor * @param restrictionFlags * @param values */ constructor( - /** - * Account restriction type - */ - public readonly restrictionFlags: AccountRestrictionFlags, - /** - * Restriction values. - */ - public readonly values: object[]) { - - } - + /** + * Account restriction type + */ + public readonly restrictionFlags: AccountRestrictionFlags, + /** + * Restriction values. + */ + public readonly values: object[], + ) {} } diff --git a/src/model/restriction/AccountRestrictionType.ts b/src/model/restriction/AccountRestrictionType.ts index 268c5194ef..70175b3bbb 100644 --- a/src/model/restriction/AccountRestrictionType.ts +++ b/src/model/restriction/AccountRestrictionType.ts @@ -24,7 +24,7 @@ * 0x80 Account restriction is interpreted as blocking operation. */ - // !!This enum will be deprecated once catbuffer-typescript code applied. +// !!This enum will be deprecated once catbuffer-typescript code applied. enum AccountRestrictionTypeEnum { Address = 0x0001, Mosaic = 0x0002, @@ -52,40 +52,36 @@ export enum AccountRestrictionFlags { /** * Allow only outgoing transactions to a given address. */ - AllowOutgoingAddress = (AccountRestrictionTypeEnum.Address + AccountRestrictionTypeEnum.Outgoing), + AllowOutgoingAddress = AccountRestrictionTypeEnum.Address + AccountRestrictionTypeEnum.Outgoing, /** * Allow only outgoing transactions with a given transaction type. */ - AllowOutgoingTransactionType = (AccountRestrictionTypeEnum.TransactionType + - AccountRestrictionTypeEnum.Outgoing), + AllowOutgoingTransactionType = AccountRestrictionTypeEnum.TransactionType + AccountRestrictionTypeEnum.Outgoing, /** * Block incoming transactions from a given address. */ - BlockIncomingAddress = (AccountRestrictionTypeEnum.Address + AccountRestrictionTypeEnum.Block), + BlockIncomingAddress = AccountRestrictionTypeEnum.Address + AccountRestrictionTypeEnum.Block, /** * Block incoming transactions containing a given mosaic identifier. */ - BlockMosaic = (AccountRestrictionTypeEnum.Mosaic + AccountRestrictionTypeEnum.Block), + BlockMosaic = AccountRestrictionTypeEnum.Mosaic + AccountRestrictionTypeEnum.Block, /** * Block incoming transactions with a given transaction type. */ - BlockIncomingTransactionType = (AccountRestrictionTypeEnum.TransactionType + - AccountRestrictionTypeEnum.Block), + BlockIncomingTransactionType = AccountRestrictionTypeEnum.TransactionType + AccountRestrictionTypeEnum.Block, /** * Block outgoing transactions from a given address. */ - BlockOutgoingAddress = (AccountRestrictionTypeEnum.Address + - AccountRestrictionTypeEnum.Block + - AccountRestrictionTypeEnum.Outgoing), + BlockOutgoingAddress = AccountRestrictionTypeEnum.Address + AccountRestrictionTypeEnum.Block + AccountRestrictionTypeEnum.Outgoing, /** * Block outgoing transactions with a given transaction type. */ - BlockOutgoingTransactionType = (AccountRestrictionTypeEnum.TransactionType + - AccountRestrictionTypeEnum.Block + - AccountRestrictionTypeEnum.Outgoing), + BlockOutgoingTransactionType = AccountRestrictionTypeEnum.TransactionType + + AccountRestrictionTypeEnum.Block + + AccountRestrictionTypeEnum.Outgoing, } diff --git a/src/model/restriction/AccountRestrictions.ts b/src/model/restriction/AccountRestrictions.ts index c5f183edf8..9e72deba97 100644 --- a/src/model/restriction/AccountRestrictions.ts +++ b/src/model/restriction/AccountRestrictions.ts @@ -19,21 +19,19 @@ import { AccountRestriction } from './AccountRestriction'; * Account restrictions structure describes restriction information for an account. */ export class AccountRestrictions { - /** * Constructor * @param address * @param restrictions */ constructor( - /** - * Account Address - */ - public readonly address: Address, - /** - * Restrictions. - */ - public readonly restrictions: AccountRestriction[]) { - - } + /** + * Account Address + */ + public readonly address: Address, + /** + * Restrictions. + */ + public readonly restrictions: AccountRestriction[], + ) {} } diff --git a/src/model/restriction/AccountRestrictionsInfo.ts b/src/model/restriction/AccountRestrictionsInfo.ts index 5e6de8a8ba..79f38bb5c3 100644 --- a/src/model/restriction/AccountRestrictionsInfo.ts +++ b/src/model/restriction/AccountRestrictionsInfo.ts @@ -18,21 +18,19 @@ import { AccountRestrictions } from './AccountRestrictions'; * Account restrictions structure describes restriction information for an account. */ export class AccountRestrictionsInfo { - /** * Constructor * @param meta * @param accountRestrictions */ constructor( - /** - * meta - */ - public readonly meta: any, - /** - * Restrictions. - */ - public readonly accountRestrictions: AccountRestrictions) { - - } + /** + * meta + */ + public readonly meta: any, + /** + * Restrictions. + */ + public readonly accountRestrictions: AccountRestrictions, + ) {} } diff --git a/src/model/restriction/MosaicAddressRestriction.ts b/src/model/restriction/MosaicAddressRestriction.ts index 59cb6229b0..10d9f373f1 100644 --- a/src/model/restriction/MosaicAddressRestriction.ts +++ b/src/model/restriction/MosaicAddressRestriction.ts @@ -21,7 +21,6 @@ import { MosaicRestrictionEntryType } from './MosaicRestrictionEntryType'; * Mosaic address restriction structure describes restriction information for an mosaic. */ export class MosaicAddressRestriction { - /** * Constructor * @param compositeHash @@ -31,26 +30,25 @@ export class MosaicAddressRestriction { * @param restrictions */ constructor( - /** - * composite hash - */ - public readonly compositeHash: string, - /** - * Mosaic restriction entry type. - */ - public readonly entryType: MosaicRestrictionEntryType, - /** - * Mosaic identifier. - */ - public readonly mosaicId: MosaicId, - /** - * Target address - */ - public readonly targetAddress: Address, - /** - * Mosaic restriction items - */ - public readonly restrictions: Map) { - - } + /** + * composite hash + */ + public readonly compositeHash: string, + /** + * Mosaic restriction entry type. + */ + public readonly entryType: MosaicRestrictionEntryType, + /** + * Mosaic identifier. + */ + public readonly mosaicId: MosaicId, + /** + * Target address + */ + public readonly targetAddress: Address, + /** + * Mosaic restriction items + */ + public readonly restrictions: Map, + ) {} } diff --git a/src/model/restriction/MosaicGlobalRestriction.ts b/src/model/restriction/MosaicGlobalRestriction.ts index 67f50b9938..c5d6734854 100644 --- a/src/model/restriction/MosaicGlobalRestriction.ts +++ b/src/model/restriction/MosaicGlobalRestriction.ts @@ -21,7 +21,6 @@ import { MosaicRestrictionEntryType } from './MosaicRestrictionEntryType'; * Mosaic global restriction structure describes restriction information for an mosaic. */ export class MosaicGlobalRestriction { - /** * Constructor * @param compositeHash @@ -31,22 +30,21 @@ export class MosaicGlobalRestriction { * @param restrictions */ constructor( - /** - * composite hash - */ - public readonly compositeHash: string, - /** - * Mosaic restriction entry type. - */ - public readonly entryType: MosaicRestrictionEntryType, - /** - * Mosaic identifier. - */ - public readonly mosaicId: MosaicId, - /** - * Mosaic restriction items - */ - public readonly restrictions: Map) { - - } + /** + * composite hash + */ + public readonly compositeHash: string, + /** + * Mosaic restriction entry type. + */ + public readonly entryType: MosaicRestrictionEntryType, + /** + * Mosaic identifier. + */ + public readonly mosaicId: MosaicId, + /** + * Mosaic restriction items + */ + public readonly restrictions: Map, + ) {} } diff --git a/src/model/restriction/MosaicGlobalRestrictionItem.ts b/src/model/restriction/MosaicGlobalRestrictionItem.ts index 9c4a0eaa0d..a346cdf3cd 100644 --- a/src/model/restriction/MosaicGlobalRestrictionItem.ts +++ b/src/model/restriction/MosaicGlobalRestrictionItem.ts @@ -14,14 +14,12 @@ * limitations under the License. */ -import { Address } from '../account/Address'; import { MosaicId } from '../mosaic/MosaicId'; import { MosaicRestrictionType } from './MosaicRestrictionType'; /** * Mosaic global restriction item structure . */ export class MosaicGlobalRestrictionItem { - /** * Constructor * @param referenceMosaicId @@ -29,18 +27,17 @@ export class MosaicGlobalRestrictionItem { * @param restrictionType */ constructor( - /** - * Reference mosaic identifier - */ - public readonly referenceMosaicId: MosaicId, - /** - * Mosaic restriction value. - */ - public readonly restrictionValue: string, - /** - * Mosaic restriction type. - */ - public readonly restrictionType: MosaicRestrictionType) { - - } + /** + * Reference mosaic identifier + */ + public readonly referenceMosaicId: MosaicId, + /** + * Mosaic restriction value. + */ + public readonly restrictionValue: string, + /** + * Mosaic restriction type. + */ + public readonly restrictionType: MosaicRestrictionType, + ) {} } diff --git a/src/model/transaction/AccountAddressRestrictionTransaction.ts b/src/model/transaction/AccountAddressRestrictionTransaction.ts index 000878411b..f6d567b260 100644 --- a/src/model/transaction/AccountAddressRestrictionTransaction.ts +++ b/src/model/transaction/AccountAddressRestrictionTransaction.ts @@ -42,7 +42,6 @@ import { TransactionType } from './TransactionType'; import { TransactionVersion } from './TransactionVersion'; export class AccountAddressRestrictionTransaction extends Transaction { - /** * Create a modify account address restriction transaction object * @param deadline - The deadline to include the transaction. @@ -53,19 +52,23 @@ export class AccountAddressRestrictionTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {AccountAddressRestrictionTransaction} */ - public static create(deadline: Deadline, - restrictionFlags: AccountRestrictionFlags, - restrictionAdditions: (Address | NamespaceId)[], - restrictionDeletions: (Address | NamespaceId)[], - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): AccountAddressRestrictionTransaction { - return new AccountAddressRestrictionTransaction(networkType, + public static create( + deadline: Deadline, + restrictionFlags: AccountRestrictionFlags, + restrictionAdditions: (Address | NamespaceId)[], + restrictionDeletions: (Address | NamespaceId)[], + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): AccountAddressRestrictionTransaction { + return new AccountAddressRestrictionTransaction( + networkType, TransactionVersion.ACCOUNT_ADDRESS_RESTRICTION, deadline, maxFee, restrictionFlags, restrictionAdditions, - restrictionDeletions); + restrictionDeletions, + ); } /** @@ -80,18 +83,19 @@ export class AccountAddressRestrictionTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - public readonly restrictionFlags: AccountRestrictionFlags, - public readonly restrictionAdditions: (Address | NamespaceId)[], - public readonly restrictionDeletions: (Address | NamespaceId)[], - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { - super(TransactionType.ACCOUNT_ADDRESS_RESTRICTION, - networkType, version, deadline, maxFee, signature, signer, transactionInfo); + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + public readonly restrictionFlags: AccountRestrictionFlags, + public readonly restrictionAdditions: (Address | NamespaceId)[], + public readonly restrictionDeletions: (Address | NamespaceId)[], + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { + super(TransactionType.ACCOUNT_ADDRESS_RESTRICTION, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } /** @@ -100,15 +104,16 @@ export class AccountAddressRestrictionTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedAccountAddressRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - AccountAddressRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedAccountAddressRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : AccountAddressRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = AccountAddressRestrictionTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as AccountAddressRestrictionTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as AccountAddressRestrictionTransactionBuilder).getDeadline().timestamp), builder.getRestrictionFlags().valueOf(), builder.getRestrictionAdditions().map((addition) => { return UnresolvedMapping.toUnresolvedAddress(Convert.uint8ToHex(addition.unresolvedAddress)); @@ -119,8 +124,7 @@ export class AccountAddressRestrictionTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as AccountAddressRestrictionTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -140,9 +144,15 @@ export class AccountAddressRestrictionTransaction extends Transaction { const byteRestrictionAdditions = 25 * this.restrictionAdditions.length; const byteRestrictionDeletions = 25 * this.restrictionDeletions.length; - return byteSize + byteRestrictionType + byteAdditionCount + byteDeletionCount + - byteRestrictionAdditions + byteRestrictionDeletions + - byteAccountRestrictionTransactionBody_Reserved1; + return ( + byteSize + + byteRestrictionType + + byteAdditionCount + + byteDeletionCount + + byteRestrictionAdditions + + byteRestrictionDeletions + + byteAccountRestrictionTransactionBody_Reserved1 + ); } /** @@ -198,15 +208,15 @@ export class AccountAddressRestrictionTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {AccountAddressRestrictionTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): AccountAddressRestrictionTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): AccountAddressRestrictionTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - restrictionAdditions: - this.restrictionAdditions.map((addition) => statement.resolveAddress(addition, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)), - restrictionDeletions: - this.restrictionDeletions.map((deletion) => statement.resolveAddress(deletion, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)), + restrictionAdditions: this.restrictionAdditions.map((addition) => + statement.resolveAddress(addition, transactionInfo.height.toString(), transactionInfo.index, aggregateTransactionIndex), + ), + restrictionDeletions: this.restrictionDeletions.map((deletion) => + statement.resolveAddress(deletion, transactionInfo.height.toString(), transactionInfo.index, aggregateTransactionIndex), + ), }); } } diff --git a/src/model/transaction/AccountLinkTransaction.ts b/src/model/transaction/AccountLinkTransaction.ts index 784b408b41..d642940c62 100644 --- a/src/model/transaction/AccountLinkTransaction.ts +++ b/src/model/transaction/AccountLinkTransaction.ts @@ -48,17 +48,14 @@ export class AccountLinkTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {AccountLinkTransaction} */ - public static create(deadline: Deadline, - remotePublicKey: string, - linkAction: LinkAction, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): AccountLinkTransaction { - return new AccountLinkTransaction(networkType, - TransactionVersion.ACCOUNT_LINK, - deadline, - maxFee, - remotePublicKey, - linkAction); + public static create( + deadline: Deadline, + remotePublicKey: string, + linkAction: LinkAction, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): AccountLinkTransaction { + return new AccountLinkTransaction(networkType, TransactionVersion.ACCOUNT_LINK, deadline, maxFee, remotePublicKey, linkAction); } /** @@ -72,21 +69,23 @@ export class AccountLinkTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The public key of the remote account. - */ - public readonly remotePublicKey: string, - /** - * The account link action. - */ - public readonly linkAction: LinkAction, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The public key of the remote account. + */ + public readonly remotePublicKey: string, + /** + * The account link action. + */ + public readonly linkAction: LinkAction, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.ACCOUNT_LINK, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -96,10 +95,10 @@ export class AccountLinkTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedAccountLinkTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - AccountLinkTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedAccountLinkTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : AccountLinkTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = AccountLinkTransaction.create( @@ -109,8 +108,7 @@ export class AccountLinkTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as AccountLinkTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** diff --git a/src/model/transaction/AccountMetadataTransaction.ts b/src/model/transaction/AccountMetadataTransaction.ts index 684aad60cf..bd94cfb443 100644 --- a/src/model/transaction/AccountMetadataTransaction.ts +++ b/src/model/transaction/AccountMetadataTransaction.ts @@ -51,21 +51,25 @@ export class AccountMetadataTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {AccountMetadataTransaction} */ - public static create(deadline: Deadline, - targetPublicKey: string, - scopedMetadataKey: UInt64, - valueSizeDelta: number, - value: string, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): AccountMetadataTransaction { - return new AccountMetadataTransaction(networkType, + public static create( + deadline: Deadline, + targetPublicKey: string, + scopedMetadataKey: UInt64, + valueSizeDelta: number, + value: string, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): AccountMetadataTransaction { + return new AccountMetadataTransaction( + networkType, TransactionVersion.ACCOUNT_METADATA, deadline, maxFee, targetPublicKey, scopedMetadataKey, valueSizeDelta, - value); + value, + ); } /** @@ -81,34 +85,33 @@ export class AccountMetadataTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * Public key of the target account. - */ - public readonly targetPublicKey: string, - /** - * Metadata key scoped to source, target and type. - */ - public readonly scopedMetadataKey: UInt64, - /** - * Change in value size in bytes. - */ - public readonly valueSizeDelta: number, - /** - * String value with UTF-8 encoding. - * Difference between the previous value and new value. - */ - public readonly value: string, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * Public key of the target account. + */ + public readonly targetPublicKey: string, + /** + * Metadata key scoped to source, target and type. + */ + public readonly scopedMetadataKey: UInt64, + /** + * Change in value size in bytes. + */ + public readonly valueSizeDelta: number, + /** + * String value with UTF-8 encoding. + * Difference between the previous value and new value. + */ + public readonly value: string, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.ACCOUNT_METADATA, networkType, version, deadline, maxFee, signature, signer, transactionInfo); - if (value.length > 1024) { - throw new Error('The maximum value size is 1024'); - } } /** @@ -117,10 +120,10 @@ export class AccountMetadataTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedAccountMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - AccountMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedAccountMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : AccountMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = AccountMetadataTransaction.create( @@ -132,8 +135,7 @@ export class AccountMetadataTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as AccountMetadataTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -151,8 +153,7 @@ export class AccountMetadataTransaction extends Transaction { const byteValueSizeDelta = 2; const valueSize = 2; - return byteSize + targetPublicKey + byteScopedMetadataKey + - byteValueSizeDelta + valueSize + this.value.length; + return byteSize + targetPublicKey + byteScopedMetadataKey + byteValueSizeDelta + valueSize + this.value.length; } /** diff --git a/src/model/transaction/AccountMosaicRestrictionTransaction.ts b/src/model/transaction/AccountMosaicRestrictionTransaction.ts index 5680e4d091..9077ee02fa 100644 --- a/src/model/transaction/AccountMosaicRestrictionTransaction.ts +++ b/src/model/transaction/AccountMosaicRestrictionTransaction.ts @@ -42,7 +42,6 @@ import { TransactionType } from './TransactionType'; import { TransactionVersion } from './TransactionVersion'; export class AccountMosaicRestrictionTransaction extends Transaction { - /** * Create a modify account mosaic restriction transaction object * @param deadline - The deadline to include the transaction. @@ -53,19 +52,23 @@ export class AccountMosaicRestrictionTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {AccountAddressRestrictionTransaction} */ - public static create(deadline: Deadline, - restrictionFlags: AccountRestrictionFlags, - restrictionAdditions: (MosaicId | NamespaceId)[], - restrictionDeletions: (MosaicId | NamespaceId)[], - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): AccountMosaicRestrictionTransaction { - return new AccountMosaicRestrictionTransaction(networkType, + public static create( + deadline: Deadline, + restrictionFlags: AccountRestrictionFlags, + restrictionAdditions: (MosaicId | NamespaceId)[], + restrictionDeletions: (MosaicId | NamespaceId)[], + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): AccountMosaicRestrictionTransaction { + return new AccountMosaicRestrictionTransaction( + networkType, TransactionVersion.ACCOUNT_MOSAIC_RESTRICTION, deadline, maxFee, restrictionFlags, restrictionAdditions, - restrictionDeletions); + restrictionDeletions, + ); } /** @@ -80,18 +83,19 @@ export class AccountMosaicRestrictionTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - public readonly restrictionFlags: AccountRestrictionFlags, - public readonly restrictionAdditions: (MosaicId | NamespaceId)[], - public readonly restrictionDeletions: (MosaicId | NamespaceId)[], - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { - super(TransactionType.ACCOUNT_MOSAIC_RESTRICTION, - networkType, version, deadline, maxFee, signature, signer, transactionInfo); + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + public readonly restrictionFlags: AccountRestrictionFlags, + public readonly restrictionAdditions: (MosaicId | NamespaceId)[], + public readonly restrictionDeletions: (MosaicId | NamespaceId)[], + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { + super(TransactionType.ACCOUNT_MOSAIC_RESTRICTION, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } /** @@ -100,15 +104,16 @@ export class AccountMosaicRestrictionTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedAccountMosaicRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - AccountMosaicRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedAccountMosaicRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : AccountMosaicRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = AccountMosaicRestrictionTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as AccountMosaicRestrictionTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as AccountMosaicRestrictionTransactionBuilder).getDeadline().timestamp), builder.getRestrictionFlags().valueOf(), builder.getRestrictionAdditions().map((addition) => { return UnresolvedMapping.toUnresolvedMosaic(new UInt64(addition.unresolvedMosaicId).toHex()); @@ -119,8 +124,7 @@ export class AccountMosaicRestrictionTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as AccountMosaicRestrictionTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -140,9 +144,15 @@ export class AccountMosaicRestrictionTransaction extends Transaction { const byteRestrictionAdditions = 8 * this.restrictionAdditions.length; const byteRestrictionDeletions = 8 * this.restrictionDeletions.length; - return byteSize + byteRestrictionType + byteAdditionCount + byteDeletionCount + - byteRestrictionAdditions + byteRestrictionDeletions + - byteAccountRestrictionTransactionBody_Reserved1; + return ( + byteSize + + byteRestrictionType + + byteAdditionCount + + byteDeletionCount + + byteRestrictionAdditions + + byteRestrictionDeletions + + byteAccountRestrictionTransactionBody_Reserved1 + ); } /** @@ -198,15 +208,15 @@ export class AccountMosaicRestrictionTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {AccountMosaicRestrictionTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): AccountMosaicRestrictionTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): AccountMosaicRestrictionTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - restrictionAdditions: - this.restrictionAdditions.map((addition) => statement.resolveMosaicId(addition, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)), - restrictionDeletions: - this.restrictionDeletions.map((deletion) => statement.resolveMosaicId(deletion, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)), + restrictionAdditions: this.restrictionAdditions.map((addition) => + statement.resolveMosaicId(addition, transactionInfo.height.toString(), transactionInfo.index, aggregateTransactionIndex), + ), + restrictionDeletions: this.restrictionDeletions.map((deletion) => + statement.resolveMosaicId(deletion, transactionInfo.height.toString(), transactionInfo.index, aggregateTransactionIndex), + ), }); } } diff --git a/src/model/transaction/AccountOperationRestrictionTransaction.ts b/src/model/transaction/AccountOperationRestrictionTransaction.ts index 7a3d334dc6..f8c3642c84 100644 --- a/src/model/transaction/AccountOperationRestrictionTransaction.ts +++ b/src/model/transaction/AccountOperationRestrictionTransaction.ts @@ -36,7 +36,6 @@ import { TransactionType } from './TransactionType'; import { TransactionVersion } from './TransactionVersion'; export class AccountOperationRestrictionTransaction extends Transaction { - /** * Create a modify account operation restriction type transaction object * @param deadline - The deadline to include the transaction. @@ -47,19 +46,23 @@ export class AccountOperationRestrictionTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {AccountOperationRestrictionTransaction} */ - public static create(deadline: Deadline, - restrictionFlags: AccountRestrictionFlags, - restrictionAdditions: TransactionType[], - restrictionDeletions: TransactionType[], - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): AccountOperationRestrictionTransaction { - return new AccountOperationRestrictionTransaction(networkType, + public static create( + deadline: Deadline, + restrictionFlags: AccountRestrictionFlags, + restrictionAdditions: TransactionType[], + restrictionDeletions: TransactionType[], + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): AccountOperationRestrictionTransaction { + return new AccountOperationRestrictionTransaction( + networkType, TransactionVersion.MODIFY_ACCOUNT_RESTRICTION_ENTITY_TYPE, deadline, maxFee, restrictionFlags, restrictionAdditions, - restrictionDeletions); + restrictionDeletions, + ); } /** @@ -74,18 +77,19 @@ export class AccountOperationRestrictionTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - public readonly restrictionFlags: AccountRestrictionFlags, - public readonly restrictionAdditions: TransactionType[], - public readonly restrictionDeletions: TransactionType[], - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { - super(TransactionType.ACCOUNT_OPERATION_RESTRICTION, - networkType, version, deadline, maxFee, signature, signer, transactionInfo); + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + public readonly restrictionFlags: AccountRestrictionFlags, + public readonly restrictionAdditions: TransactionType[], + public readonly restrictionDeletions: TransactionType[], + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { + super(TransactionType.ACCOUNT_OPERATION_RESTRICTION, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } /** @@ -94,15 +98,16 @@ export class AccountOperationRestrictionTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedAccountOperationRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - AccountOperationRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedAccountOperationRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : AccountOperationRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signer = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = AccountOperationRestrictionTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as AccountOperationRestrictionTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as AccountOperationRestrictionTransactionBuilder).getDeadline().timestamp), builder.getRestrictionFlags().valueOf(), builder.getRestrictionAdditions(), builder.getRestrictionDeletions(), @@ -129,9 +134,15 @@ export class AccountOperationRestrictionTransaction extends Transaction { const byteRestrictionAdditions = 2 * this.restrictionAdditions.length; const byteRestrictionDeletions = 2 * this.restrictionDeletions.length; - return byteSize + byteRestrictionType + byteAdditionCount + byteDeletionCount + - byteRestrictionAdditions + byteRestrictionDeletions + - byteAccountRestrictionTransactionBody_Reserved1; + return ( + byteSize + + byteRestrictionType + + byteAdditionCount + + byteDeletionCount + + byteRestrictionAdditions + + byteRestrictionDeletions + + byteAccountRestrictionTransactionBody_Reserved1 + ); } /** diff --git a/src/model/transaction/AccountRestrictionModification.ts b/src/model/transaction/AccountRestrictionModification.ts index 3e4fb20787..045e2815ab 100644 --- a/src/model/transaction/AccountRestrictionModification.ts +++ b/src/model/transaction/AccountRestrictionModification.ts @@ -20,23 +20,21 @@ import { AccountRestrictionModificationAction } from '../restriction/AccountRest import { TransactionType } from './TransactionType'; export class AccountRestrictionModification { - /** * Constructor * @param modificationAction * @param value */ constructor( - /** - * Modification type. - */ - public readonly modificationAction: AccountRestrictionModificationAction, - /** - * Modification value (Address, Mosaic or Transaction Type). - */ - public readonly value: T) { - - } + /** + * Modification type. + */ + public readonly modificationAction: AccountRestrictionModificationAction, + /** + * Modification value (Address, Mosaic or Transaction Type). + */ + public readonly value: T, + ) {} /** * Create an address filter for account restriction modification @@ -44,8 +42,10 @@ export class AccountRestrictionModification { * @param value - modification value (Address) * @returns {AccountRestrictionModification} */ - public static createForAddress(modificationAction: AccountRestrictionModificationAction, - value: Address): AccountRestrictionModification { + public static createForAddress( + modificationAction: AccountRestrictionModificationAction, + value: Address, + ): AccountRestrictionModification { return new AccountRestrictionModification(modificationAction, value.plain()); } /** @@ -54,9 +54,11 @@ export class AccountRestrictionModification { * @param value - modification value (Mosaic) * @returns {AccountRestrictionModification} */ - public static createForMosaic(modificationAction: AccountRestrictionModificationAction, - value: MosaicId): AccountRestrictionModification { - return new AccountRestrictionModification(modificationAction, value.id.toDTO()); + public static createForMosaic( + modificationAction: AccountRestrictionModificationAction, + value: MosaicId, + ): AccountRestrictionModification { + return new AccountRestrictionModification(modificationAction, value.id.toDTO()); } /** @@ -65,15 +67,17 @@ export class AccountRestrictionModification { * @param operation - modification value (Transaction Type) * @returns {AccountRestrictionModification} */ - public static createForOperation(modificationAction: AccountRestrictionModificationAction, - value: number): AccountRestrictionModification { - return new AccountRestrictionModification(modificationAction, value); + public static createForOperation( + modificationAction: AccountRestrictionModificationAction, + value: number, + ): AccountRestrictionModification { + return new AccountRestrictionModification(modificationAction, value); } /** * @internal */ - toDTO() { + toDTO(): any { return { value: this.value, modificationAction: this.modificationAction, diff --git a/src/model/transaction/AccountRestrictionTransaction.ts b/src/model/transaction/AccountRestrictionTransaction.ts index 5b198ae189..3df41ca934 100644 --- a/src/model/transaction/AccountRestrictionTransaction.ts +++ b/src/model/transaction/AccountRestrictionTransaction.ts @@ -23,7 +23,6 @@ import { UInt64 } from '../UInt64'; import { AccountAddressRestrictionTransaction } from './AccountAddressRestrictionTransaction'; import { AccountMosaicRestrictionTransaction } from './AccountMosaicRestrictionTransaction'; import { AccountOperationRestrictionTransaction } from './AccountOperationRestrictionTransaction'; -import { AccountRestrictionModification } from './AccountRestrictionModification'; import { Deadline } from './Deadline'; import { TransactionType } from './TransactionType'; @@ -46,11 +45,15 @@ export class AccountRestrictionTransaction { networkType: NetworkType, maxFee: UInt64 = new UInt64([0, 0]), ): AccountAddressRestrictionTransaction { - if (![AccountRestrictionFlags.AllowIncomingAddress, - AccountRestrictionFlags.AllowOutgoingAddress, - AccountRestrictionFlags.BlockOutgoingAddress, - AccountRestrictionFlags.BlockIncomingAddress].includes(restrictionFlags)) { - throw new Error ('Restriction type is not allowed.'); + if ( + ![ + AccountRestrictionFlags.AllowIncomingAddress, + AccountRestrictionFlags.AllowOutgoingAddress, + AccountRestrictionFlags.BlockOutgoingAddress, + AccountRestrictionFlags.BlockIncomingAddress, + ].includes(restrictionFlags) + ) { + throw new Error('Restriction type is not allowed.'); } return AccountAddressRestrictionTransaction.create( deadline, @@ -81,7 +84,7 @@ export class AccountRestrictionTransaction { maxFee: UInt64 = new UInt64([0, 0]), ): AccountMosaicRestrictionTransaction { if (![AccountRestrictionFlags.AllowMosaic, AccountRestrictionFlags.BlockMosaic].includes(restrictionFlags)) { - throw new Error ('Restriction type is not allowed.'); + throw new Error('Restriction type is not allowed.'); } return AccountMosaicRestrictionTransaction.create( deadline, @@ -111,11 +114,15 @@ export class AccountRestrictionTransaction { networkType: NetworkType, maxFee: UInt64 = new UInt64([0, 0]), ): AccountOperationRestrictionTransaction { - if (![AccountRestrictionFlags.AllowIncomingTransactionType, - AccountRestrictionFlags.AllowOutgoingTransactionType, - AccountRestrictionFlags.BlockIncomingTransactionType, - AccountRestrictionFlags.BlockOutgoingTransactionType].includes(restrictionFlags)) { - throw new Error ('Restriction type is not allowed.'); + if ( + ![ + AccountRestrictionFlags.AllowIncomingTransactionType, + AccountRestrictionFlags.AllowOutgoingTransactionType, + AccountRestrictionFlags.BlockIncomingTransactionType, + AccountRestrictionFlags.BlockOutgoingTransactionType, + ].includes(restrictionFlags) + ) { + throw new Error('Restriction type is not allowed.'); } return AccountOperationRestrictionTransaction.create( deadline, diff --git a/src/model/transaction/AddressAliasTransaction.ts b/src/model/transaction/AddressAliasTransaction.ts index 4174d8e92a..d9a85ec0fa 100644 --- a/src/model/transaction/AddressAliasTransaction.ts +++ b/src/model/transaction/AddressAliasTransaction.ts @@ -44,7 +44,6 @@ import { TransactionVersion } from './TransactionVersion'; * i.e. increase or decrease the supply. */ export class AddressAliasTransaction extends Transaction { - /** * Create a address alias transaction object * @param deadline - The deadline to include the transaction. @@ -55,13 +54,16 @@ export class AddressAliasTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {AddressAliasTransaction} */ - public static create(deadline: Deadline, - aliasAction: AliasAction, - namespaceId: NamespaceId, - address: Address, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): AddressAliasTransaction { - return new AddressAliasTransaction(networkType, + public static create( + deadline: Deadline, + aliasAction: AliasAction, + namespaceId: NamespaceId, + address: Address, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): AddressAliasTransaction { + return new AddressAliasTransaction( + networkType, TransactionVersion.ADDRESS_ALIAS, deadline, maxFee, @@ -83,25 +85,27 @@ export class AddressAliasTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The alias action type. - */ - public readonly aliasAction: AliasAction, - /** - * The namespace id that will be an alias. - */ - public readonly namespaceId: NamespaceId, - /** - * The address. - */ - public readonly address: Address, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The alias action type. + */ + public readonly aliasAction: AliasAction, + /** + * The namespace id that will be an alias. + */ + public readonly namespaceId: NamespaceId, + /** + * The address. + */ + public readonly address: Address, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.ADDRESS_ALIAS, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -111,23 +115,21 @@ export class AddressAliasTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedAddressAliasTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - AddressAliasTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedAddressAliasTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : AddressAliasTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = AddressAliasTransaction.create( isEmbedded ? Deadline.create() : Deadline.createFromDTO((builder as AddressAliasTransactionBuilder).getDeadline().timestamp), builder.getAliasAction().valueOf(), new NamespaceId(builder.getNamespaceId().namespaceId), - Address.createFromEncoded( - Convert.uint8ToHex(builder.getAddress().address)), + Address.createFromEncoded(Convert.uint8ToHex(builder.getAddress().address)), networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as AddressAliasTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** diff --git a/src/model/transaction/AggregateTransaction.ts b/src/model/transaction/AggregateTransaction.ts index 16fa41fe4a..0086cf8241 100644 --- a/src/model/transaction/AggregateTransaction.ts +++ b/src/model/transaction/AggregateTransaction.ts @@ -50,7 +50,6 @@ import { TransactionVersion } from './TransactionVersion'; * Aggregate innerTransactions contain multiple innerTransactions that can be initiated by different accounts. */ export class AggregateTransaction extends Transaction { - /** * @param networkType * @param type @@ -63,22 +62,24 @@ export class AggregateTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - type: number, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The array of innerTransactions included in the aggregate transaction. - */ - public readonly innerTransactions: InnerTransaction[], - /** - * The array of transaction cosigners signatures. - */ - public readonly cosignatures: AggregateTransactionCosignature[], - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + type: number, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The array of innerTransactions included in the aggregate transaction. + */ + public readonly innerTransactions: InnerTransaction[], + /** + * The array of transaction cosigners signatures. + */ + public readonly cosignatures: AggregateTransactionCosignature[], + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(type, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -91,12 +92,15 @@ export class AggregateTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {AggregateTransaction} */ - public static createComplete(deadline: Deadline, - innerTransactions: InnerTransaction[], - networkType: NetworkType, - cosignatures: AggregateTransactionCosignature[], - maxFee: UInt64 = new UInt64([0, 0])): AggregateTransaction { - return new AggregateTransaction(networkType, + public static createComplete( + deadline: Deadline, + innerTransactions: InnerTransaction[], + networkType: NetworkType, + cosignatures: AggregateTransactionCosignature[], + maxFee: UInt64 = new UInt64([0, 0]), + ): AggregateTransaction { + return new AggregateTransaction( + networkType, TransactionType.AGGREGATE_COMPLETE, TransactionVersion.AGGREGATE_COMPLETE, deadline, @@ -115,12 +119,15 @@ export class AggregateTransaction extends Transaction { * @param {UInt64} maxFee - (Optional) Max fee defined by the sender * @return {AggregateTransaction} */ - public static createBonded(deadline: Deadline, - innerTransactions: InnerTransaction[], - networkType: NetworkType, - cosignatures: AggregateTransactionCosignature[] = [], - maxFee: UInt64 = new UInt64([0, 0])): AggregateTransaction { - return new AggregateTransaction(networkType, + public static createBonded( + deadline: Deadline, + innerTransactions: InnerTransaction[], + networkType: NetworkType, + cosignatures: AggregateTransactionCosignature[] = [], + maxFee: UInt64 = new UInt64([0, 0]), + ): AggregateTransaction { + return new AggregateTransaction( + networkType, TransactionType.AGGREGATE_BONDED, TransactionVersion.AGGREGATE_BONDED, deadline, @@ -141,9 +148,10 @@ export class AggregateTransaction extends Transaction { * As buffer uses separate builder class for Complete and bonded */ const type = parseInt(Convert.uint8ToHex(Convert.hexToUint8(payload.substring(220, 224)).reverse()), 16); - const builder = type === TransactionType.AGGREGATE_COMPLETE ? - AggregateCompleteTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - AggregateBondedTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + const builder = + type === TransactionType.AGGREGATE_COMPLETE + ? AggregateCompleteTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : AggregateBondedTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const innerTransactions = builder.getTransactions().map((t) => Convert.uint8ToHex(EmbeddedTransactionHelper.serialize(t))); const networkType = builder.getNetwork().valueOf(); const consignatures = builder.getCosignatures().map((cosig) => { @@ -153,24 +161,25 @@ export class AggregateTransaction extends Transaction { ); }); - return type === TransactionType.AGGREGATE_COMPLETE ? - AggregateTransaction.createComplete( - Deadline.createFromDTO(builder.deadline.timestamp), - innerTransactions.map((transactionRaw) => { - return CreateTransactionFromPayload(transactionRaw, true) as InnerTransaction; - }), - networkType, - consignatures, - new UInt64(builder.fee.amount), - ) : AggregateTransaction.createBonded( - Deadline.createFromDTO(builder.deadline.timestamp), - innerTransactions.map((transactionRaw) => { - return CreateTransactionFromPayload(transactionRaw, true) as InnerTransaction; - }), - networkType, - consignatures, - new UInt64(builder.fee.amount), - ); + return type === TransactionType.AGGREGATE_COMPLETE + ? AggregateTransaction.createComplete( + Deadline.createFromDTO(builder.deadline.timestamp), + innerTransactions.map((transactionRaw) => { + return CreateTransactionFromPayload(transactionRaw, true) as InnerTransaction; + }), + networkType, + consignatures, + new UInt64(builder.fee.amount), + ) + : AggregateTransaction.createBonded( + Deadline.createFromDTO(builder.deadline.timestamp), + innerTransactions.map((transactionRaw) => { + return CreateTransactionFromPayload(transactionRaw, true) as InnerTransaction; + }), + networkType, + consignatures, + new UInt64(builder.fee.amount), + ); } /** @@ -181,7 +190,7 @@ export class AggregateTransaction extends Transaction { */ public addTransactions(transactions: InnerTransaction[]): AggregateTransaction { const innerTransactions = this.innerTransactions.concat(transactions); - return DtoMapping.assign(this, {innerTransactions}); + return DtoMapping.assign(this, { innerTransactions }); } /** @@ -192,7 +201,7 @@ export class AggregateTransaction extends Transaction { */ public addCosignatures(cosigs: AggregateTransactionCosignature[]): AggregateTransaction { const cosignatures = this.cosignatures.concat(cosigs); - return DtoMapping.assign(this, {cosignatures}); + return DtoMapping.assign(this, { cosignatures }); } /** @@ -203,9 +212,11 @@ export class AggregateTransaction extends Transaction { * @param generationHash - Network generation hash hex * @returns {SignedTransaction} */ - public signTransactionWithCosignatories(initiatorAccount: Account, - cosignatories: Account[], - generationHash: string): SignedTransaction { + public signTransactionWithCosignatories( + initiatorAccount: Account, + cosignatories: Account[], + generationHash: string, + ): SignedTransaction { const signedTransaction = this.signWith(initiatorAccount, generationHash); const transactionHashBytes = Convert.hexToUint8(signedTransaction.hash); let signedPayload = signedTransaction.payload; @@ -218,12 +229,11 @@ export class AggregateTransaction extends Transaction { // Calculate new size const size = `00000000${(signedPayload.length / 2).toString(16)}`; const formatedSize = size.substr(size.length - 8, size.length); - const littleEndianSize = formatedSize.substr(6, 2) + formatedSize.substr(4, 2) + - formatedSize.substr(2, 2) + formatedSize.substr(0, 2); + const littleEndianSize = + formatedSize.substr(6, 2) + formatedSize.substr(4, 2) + formatedSize.substr(2, 2) + formatedSize.substr(0, 2); signedPayload = littleEndianSize + signedPayload.substr(8, signedPayload.length - 8); - return new SignedTransaction(signedPayload, signedTransaction.hash, initiatorAccount.publicKey, - this.type, this.networkType); + return new SignedTransaction(signedPayload, signedTransaction.hash, initiatorAccount.publicKey, this.type, this.networkType); } /** @@ -235,9 +245,11 @@ export class AggregateTransaction extends Transaction { * @param generationHash - Network generation hash hex * @return {SignedTransaction} */ - public signTransactionGivenSignatures(initiatorAccount: Account, - cosignatureSignedTransactions: CosignatureSignedTransaction[], - generationHash: string): SignedTransaction { + public signTransactionGivenSignatures( + initiatorAccount: Account, + cosignatureSignedTransactions: CosignatureSignedTransaction[], + generationHash: string, + ): SignedTransaction { const signedTransaction = this.signWith(initiatorAccount, generationHash); let signedPayload = signedTransaction.payload; cosignatureSignedTransactions.forEach((cosignedTransaction) => { @@ -247,12 +259,11 @@ export class AggregateTransaction extends Transaction { // Calculate new size const size = `00000000${(signedPayload.length / 2).toString(16)}`; const formatedSize = size.substr(size.length - 8, size.length); - const littleEndianSize = formatedSize.substr(6, 2) + formatedSize.substr(4, 2) + - formatedSize.substr(2, 2) + formatedSize.substr(0, 2); + const littleEndianSize = + formatedSize.substr(6, 2) + formatedSize.substr(4, 2) + formatedSize.substr(2, 2) + formatedSize.substr(0, 2); signedPayload = littleEndianSize + signedPayload.substr(8, signedPayload.length - 8); - return new SignedTransaction(signedPayload, signedTransaction.hash, initiatorAccount.publicKey, - this.type, this.networkType); + return new SignedTransaction(signedPayload, signedTransaction.hash, initiatorAccount.publicKey, this.type, this.networkType); } /** @@ -261,8 +272,10 @@ export class AggregateTransaction extends Transaction { * @returns {boolean} */ public signedByAccount(publicAccount: PublicAccount): boolean { - return this.cosignatures.find((cosignature) => cosignature.signer.equals(publicAccount)) !== undefined - || (this.signer !== undefined && this.signer.equals(publicAccount)); + return ( + this.cosignatures.find((cosignature) => cosignature.signer.equals(publicAccount)) !== undefined || + (this.signer !== undefined && this.signer.equals(publicAccount)) + ); } /** @@ -289,8 +302,7 @@ export class AggregateTransaction extends Transaction { }); const byteCosignatures = this.cosignatures.length * 96; - return byteSize + byteTransactionHash + bytePayloadSize + byteHeader_Reserved1 + - byteTransactions + byteCosignatures; + return byteSize + byteTransactionHash + bytePayloadSize + byteHeader_Reserved1 + byteTransactions + byteCosignatures; } /** @@ -304,37 +316,35 @@ export class AggregateTransaction extends Transaction { const cosignatures = this.cosignatures.map((cosignature) => { const signerBytes = Convert.hexToUint8(cosignature.signer.publicKey); const signatureBytes = Convert.hexToUint8(cosignature.signature); - return new CosignatureBuilder( - new KeyDto(signerBytes), - new SignatureDto(signatureBytes), - ); + return new CosignatureBuilder(new KeyDto(signerBytes), new SignatureDto(signatureBytes)); }); - const transactionBuilder = this.type === TransactionType.AGGREGATE_COMPLETE ? - new AggregateCompleteTransactionBuilder( - new SignatureDto(signatureBuffer), - new KeyDto(signerBuffer), - this.versionToDTO(), - this.networkType.valueOf(), - this.type.valueOf(), - new AmountDto(this.maxFee.toDTO()), - new TimestampDto(this.deadline.toDTO()), - new Hash256Dto(this.calculateInnerTransactionHash()), - transactions, - cosignatures, - ) : - new AggregateBondedTransactionBuilder( - new SignatureDto(signatureBuffer), - new KeyDto(signerBuffer), - this.versionToDTO(), - this.networkType.valueOf(), - this.type.valueOf(), - new AmountDto(this.maxFee.toDTO()), - new TimestampDto(this.deadline.toDTO()), - new Hash256Dto(this.calculateInnerTransactionHash()), - transactions, - cosignatures, - ); + const transactionBuilder = + this.type === TransactionType.AGGREGATE_COMPLETE + ? new AggregateCompleteTransactionBuilder( + new SignatureDto(signatureBuffer), + new KeyDto(signerBuffer), + this.versionToDTO(), + this.networkType.valueOf(), + this.type.valueOf(), + new AmountDto(this.maxFee.toDTO()), + new TimestampDto(this.deadline.toDTO()), + new Hash256Dto(this.calculateInnerTransactionHash()), + transactions, + cosignatures, + ) + : new AggregateBondedTransactionBuilder( + new SignatureDto(signatureBuffer), + new KeyDto(signerBuffer), + this.versionToDTO(), + this.networkType.valueOf(), + this.type.valueOf(), + new AmountDto(this.maxFee.toDTO()), + new TimestampDto(this.deadline.toDTO()), + new Hash256Dto(this.calculateInnerTransactionHash()), + transactions, + cosignatures, + ); return transactionBuilder.serialize(); } @@ -353,7 +363,7 @@ export class AggregateTransaction extends Transaction { */ private calculateInnerTransactionHash(): Uint8Array { // Note: Transaction hashing *always* uses SHA3 - const hasher = SHA3Hasher.createHasher(32); + const hasher = SHA3Hasher.createHasher(32); const builder = new MerkleHashBuilder(32); this.innerTransactions.forEach((transaction) => { const entityHash: Uint8Array = new Uint8Array(32); @@ -384,10 +394,31 @@ export class AggregateTransaction extends Transaction { * @internal * @returns {AggregateTransaction} */ - resolveAliases(statement: Statement): AggregateTransaction { + public resolveAliases(statement: Statement): AggregateTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); - return DtoMapping.assign(this, - {innerTransactions: this.innerTransactions.map((tx) => tx.resolveAliases(statement, transactionInfo.index)) - .sort((a, b) => a.transactionInfo!.index - b.transactionInfo!.index)}); + return DtoMapping.assign(this, { + innerTransactions: this.innerTransactions + .map((tx) => tx.resolveAliases(statement, transactionInfo.index)) + .sort((a, b) => a.transactionInfo!.index - b.transactionInfo!.index), + }); + } + + /** + * Set transaction maxFee using fee multiplier for **ONLY AGGREGATE TRANSACTIONS** + * @param feeMultiplier The fee multiplier + * @param requiredCosignatures Required number of cosignatures + * @returns {AggregateTransaction} + */ + public setMaxFeeForAggregate(feeMultiplier: number, requiredCosignatures: number): AggregateTransaction { + if (this.type !== TransactionType.AGGREGATE_BONDED && this.type !== TransactionType.AGGREGATE_COMPLETE) { + throw new Error('setMaxFeeForAggregate can only be used for aggregate transactions.'); + } + // Check if current cosignature count is greater than requiredCosignatures. + const calculatedCosignatures = requiredCosignatures > this.cosignatures.length ? requiredCosignatures : this.cosignatures.length; + // Remove current cosignature length and use the calculated one. + const calculatedSize = this.size - this.cosignatures.length * 96 + calculatedCosignatures * 96; + return DtoMapping.assign(this, { + maxFee: UInt64.fromUint(calculatedSize * feeMultiplier), + }); } } diff --git a/src/model/transaction/AggregateTransactionCosignature.ts b/src/model/transaction/AggregateTransactionCosignature.ts index 55a0e09345..d9ae9a5afe 100644 --- a/src/model/transaction/AggregateTransactionCosignature.ts +++ b/src/model/transaction/AggregateTransactionCosignature.ts @@ -14,32 +14,30 @@ * limitations under the License. */ -import {PublicAccount} from '../account/PublicAccount'; -import { NetworkType } from '../network/NetworkType'; +import { PublicAccount } from '../account/PublicAccount'; /** * Model representing cosignature of an aggregate transaction. */ export class AggregateTransactionCosignature { - /** * @param signature * @param signer */ - constructor(/** - * The signature of aggregate transaction done by the cosigner. - */ - public readonly signature: string, - /** - * The cosigner public account. - */ - public readonly signer: PublicAccount) { - - } + constructor( + /** + * The signature of aggregate transaction done by the cosigner. + */ + public readonly signature: string, + /** + * The cosigner public account. + */ + public readonly signer: PublicAccount, + ) {} /** * Create DTO object */ - public toDTO() { + public toDTO(): any { return { signature: this.signature, signerPublicKey: this.signer.toDTO(), diff --git a/src/model/transaction/AggregateTransactionInfo.ts b/src/model/transaction/AggregateTransactionInfo.ts index 0e47831f75..3521257169 100644 --- a/src/model/transaction/AggregateTransactionInfo.ts +++ b/src/model/transaction/AggregateTransactionInfo.ts @@ -14,14 +14,13 @@ * limitations under the License. */ -import {UInt64} from '../UInt64'; -import {TransactionInfo} from './TransactionInfo'; +import { UInt64 } from '../UInt64'; +import { TransactionInfo } from './TransactionInfo'; /** * Inner transaction information model included in all aggregate inner transactions */ export class AggregateTransactionInfo extends TransactionInfo { - /** * @param height * @param index @@ -29,18 +28,19 @@ export class AggregateTransactionInfo extends TransactionInfo { * @param aggregateHash * @param aggregateId */ - constructor(height: UInt64, - index: number, - id: string, - /** - * The hash of the aggregate transaction. - */ - public readonly aggregateHash: string, - /** - * The id of the aggregate transaction. - */ - public readonly aggregateId: string) { - + constructor( + height: UInt64, + index: number, + id: string, + /** + * The hash of the aggregate transaction. + */ + public readonly aggregateHash: string, + /** + * The id of the aggregate transaction. + */ + public readonly aggregateId: string, + ) { super(height, index, id); } } diff --git a/src/model/transaction/AliasTransaction.ts b/src/model/transaction/AliasTransaction.ts index 321f3e012c..09f8e53907 100644 --- a/src/model/transaction/AliasTransaction.ts +++ b/src/model/transaction/AliasTransaction.ts @@ -26,7 +26,6 @@ import { MosaicAliasTransaction } from './MosaicAliasTransaction'; import { Transaction } from './Transaction'; export abstract class AliasTransaction extends Transaction { - /** * Create an address alias transaction object * @param deadline - The deadline to include the transaction. @@ -37,20 +36,15 @@ export abstract class AliasTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {AddressAliasTransaction} */ - public static createForAddress(deadline: Deadline, - aliasAction: AliasAction, - namespaceId: NamespaceId, - address: Address, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): AliasTransaction { - return AddressAliasTransaction.create( - deadline, - aliasAction, - namespaceId, - address, - networkType, - maxFee, - ); + public static createForAddress( + deadline: Deadline, + aliasAction: AliasAction, + namespaceId: NamespaceId, + address: Address, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): AliasTransaction { + return AddressAliasTransaction.create(deadline, aliasAction, namespaceId, address, networkType, maxFee); } /** @@ -63,20 +57,14 @@ export abstract class AliasTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {MosaicAliasTransaction} */ - public static createForMosaic(deadline: Deadline, - aliasAction: AliasAction, - namespaceId: NamespaceId, - mosaicId: MosaicId, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): AliasTransaction { - return MosaicAliasTransaction.create( - deadline, - aliasAction, - namespaceId, - mosaicId, - networkType, - maxFee, - ); + public static createForMosaic( + deadline: Deadline, + aliasAction: AliasAction, + namespaceId: NamespaceId, + mosaicId: MosaicId, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): AliasTransaction { + return MosaicAliasTransaction.create(deadline, aliasAction, namespaceId, mosaicId, networkType, maxFee); } - } diff --git a/src/model/transaction/CosignatureSignedTransaction.ts b/src/model/transaction/CosignatureSignedTransaction.ts index 2aca6cbe99..e9004b16f7 100644 --- a/src/model/transaction/CosignatureSignedTransaction.ts +++ b/src/model/transaction/CosignatureSignedTransaction.ts @@ -24,16 +24,17 @@ export class CosignatureSignedTransaction { * @param signerPublicKey */ constructor( - /** - * The hash of parent aggregate transaction that has been signed by a cosignatory of the transaction - */ - public readonly parentHash: string, - /** - * The signatures generated by signing the parent aggregate transaction hash. - */ - public readonly signature: string, - /** - * The signer publicKey of the transaction. - */ - public readonly signerPublicKey: string) {} + /** + * The hash of parent aggregate transaction that has been signed by a cosignatory of the transaction + */ + public readonly parentHash: string, + /** + * The signatures generated by signing the parent aggregate transaction hash. + */ + public readonly signature: string, + /** + * The signer publicKey of the transaction. + */ + public readonly signerPublicKey: string, + ) {} } diff --git a/src/model/transaction/CosignatureTransaction.ts b/src/model/transaction/CosignatureTransaction.ts index bdfe492cd8..3c1dcbf31a 100644 --- a/src/model/transaction/CosignatureTransaction.ts +++ b/src/model/transaction/CosignatureTransaction.ts @@ -14,11 +14,11 @@ * limitations under the License. */ -import { KeyPair, SHA3Hasher } from '../../core/crypto'; +import { KeyPair } from '../../core/crypto'; import { Convert } from '../../core/format/Convert'; -import {Account} from '../account/Account'; -import {AggregateTransaction} from './AggregateTransaction'; -import {CosignatureSignedTransaction} from './CosignatureSignedTransaction'; +import { Account } from '../account/Account'; +import { AggregateTransaction } from './AggregateTransaction'; +import { CosignatureSignedTransaction } from './CosignatureSignedTransaction'; import { Transaction } from './Transaction'; /** @@ -28,12 +28,12 @@ export class CosignatureTransaction { /** * @param transactionToCosign */ - constructor(/** - * Transaction to cosign. - */ - public readonly transactionToCosign: AggregateTransaction) { - - } + constructor( + /** + * Transaction to cosign. + */ + public readonly transactionToCosign: AggregateTransaction, + ) {} /** * Create a cosignature transaction @@ -52,22 +52,15 @@ export class CosignatureTransaction { * @param generationHash - Network generation hash * @returns {CosignatureSignedTransaction} */ - public static signTransactionPayload(account: Account, - payload: string, - generationHash: string): CosignatureSignedTransaction { + public static signTransactionPayload(account: Account, payload: string, generationHash: string): CosignatureSignedTransaction { /** * For aggregated complete transaction, cosignatories are gathered off chain announced. */ - const transactionHash = - Transaction.createTransactionHash(payload, Array.from(Convert.hexToUint8(generationHash)), account.networkType); + const transactionHash = Transaction.createTransactionHash(payload, Array.from(Convert.hexToUint8(generationHash))); const hashBytes = Convert.hexToUint8(transactionHash); const keyPairEncoded = KeyPair.createKeyPairFromPrivateKeyString(account.privateKey); const signature = KeyPair.sign(keyPairEncoded, new Uint8Array(hashBytes)); - return new CosignatureSignedTransaction( - Convert.uint8ToHex(hashBytes), - Convert.uint8ToHex(signature), - account.publicKey, - ); + return new CosignatureSignedTransaction(Convert.uint8ToHex(hashBytes), Convert.uint8ToHex(signature), account.publicKey); } /** @@ -83,10 +76,6 @@ export class CosignatureTransaction { const hashBytes = Convert.hexToUint8(hash ? hash : ''); const keyPairEncoded = KeyPair.createKeyPairFromPrivateKeyString(account.privateKey); const signature = KeyPair.sign(keyPairEncoded, new Uint8Array(hashBytes)); - return new CosignatureSignedTransaction( - hash ? hash : '', - Convert.uint8ToHex(signature), - account.publicKey, - ); + return new CosignatureSignedTransaction(hash ? hash : '', Convert.uint8ToHex(signature), account.publicKey); } } diff --git a/src/model/transaction/Deadline.ts b/src/model/transaction/Deadline.ts index 81090ef04e..c9f4c8feac 100644 --- a/src/model/transaction/Deadline.ts +++ b/src/model/transaction/Deadline.ts @@ -14,15 +14,14 @@ * limitations under the License. */ -import {ChronoUnit, Instant, LocalDateTime, ZoneId} from 'js-joda'; -import {UInt64} from '../UInt64'; +import { ChronoUnit, Instant, LocalDateTime, ZoneId } from 'js-joda'; +import { UInt64 } from '../UInt64'; /** * The deadline of the transaction. The deadline is given as the number of seconds elapsed since the creation of the nemesis block. * If a transaction does not get included in a block before the deadline is reached, it is deleted. */ export class Deadline { - /** * @type {number} */ @@ -39,8 +38,8 @@ export class Deadline { * @param chronoUnit * @returns {Deadline} */ - public static create(deadline: number = 2, chronoUnit: ChronoUnit = ChronoUnit.HOURS): Deadline { - const networkTimeStamp = (new Date()).getTime(); + public static create(deadline = 2, chronoUnit: ChronoUnit = ChronoUnit.HOURS): Deadline { + const networkTimeStamp = new Date().getTime(); const timeStampDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(networkTimeStamp), ZoneId.SYSTEM); const deadlineDateTime = timeStampDateTime.plus(deadline, chronoUnit); @@ -63,7 +62,8 @@ export class Deadline { const dateSeconds = uint64Value.compact(); const deadline = LocalDateTime.ofInstant( Instant.ofEpochMilli(Math.round(dateSeconds + Deadline.timestampNemesisBlock * 1000)), - ZoneId.SYSTEM); + ZoneId.SYSTEM, + ); return new Deadline(deadline); } @@ -78,9 +78,7 @@ export class Deadline { * @internal */ public toDTO(): number[] { - return UInt64.fromUint( - (this.value.atZone(ZoneId.SYSTEM).toInstant().toEpochMilli() - Deadline.timestampNemesisBlock * 1000), - ).toDTO(); + return UInt64.fromUint(this.value.atZone(ZoneId.SYSTEM).toInstant().toEpochMilli() - Deadline.timestampNemesisBlock * 1000).toDTO(); } /** @@ -88,7 +86,7 @@ export class Deadline { */ public toString(): string { return UInt64.fromUint( - (this.value.atZone(ZoneId.SYSTEM).toInstant().toEpochMilli() - Deadline.timestampNemesisBlock * 1000), + this.value.atZone(ZoneId.SYSTEM).toInstant().toEpochMilli() - Deadline.timestampNemesisBlock * 1000, ).toString(); } } diff --git a/src/model/transaction/HashLockTransaction.ts b/src/model/transaction/HashLockTransaction.ts index 28ff754601..3530cbbf4c 100644 --- a/src/model/transaction/HashLockTransaction.ts +++ b/src/model/transaction/HashLockTransaction.ts @@ -19,5 +19,4 @@ import { LockFundsTransaction } from './LockFundsTransaction'; /* * An alias for LockFundsTransaction class */ -export class HashLockTransaction extends LockFundsTransaction { -} +export class HashLockTransaction extends LockFundsTransaction {} diff --git a/src/model/transaction/InnerTransaction.ts b/src/model/transaction/InnerTransaction.ts index c3d05f9cfa..5f69a6def1 100644 --- a/src/model/transaction/InnerTransaction.ts +++ b/src/model/transaction/InnerTransaction.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import {PublicAccount} from '../account/PublicAccount'; -import {Transaction} from './Transaction'; +import { PublicAccount } from '../account/PublicAccount'; +import { Transaction } from './Transaction'; /** * Transaction with signer included, used when adding signer to transactions included in an aggregate transaction. */ -export type InnerTransaction = Transaction & {signer?: PublicAccount}; +export type InnerTransaction = Transaction & { signer?: PublicAccount }; diff --git a/src/model/transaction/LockFundsTransaction.ts b/src/model/transaction/LockFundsTransaction.ts index 27145c6c6c..8f0be67b1a 100644 --- a/src/model/transaction/LockFundsTransaction.ts +++ b/src/model/transaction/LockFundsTransaction.ts @@ -50,7 +50,6 @@ import { TransactionVersion } from './TransactionVersion'; * @since 1.0 */ export class LockFundsTransaction extends Transaction { - /** * Aggregate bonded hash. */ @@ -67,21 +66,15 @@ export class LockFundsTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {LockFundsTransaction} */ - public static create(deadline: Deadline, - mosaic: Mosaic, - duration: UInt64, - signedTransaction: SignedTransaction, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): LockFundsTransaction { - return new LockFundsTransaction( - networkType, - TransactionVersion.HASH_LOCK, - deadline, - maxFee, - mosaic, - duration, - signedTransaction, - ); + public static create( + deadline: Deadline, + mosaic: Mosaic, + duration: UInt64, + signedTransaction: SignedTransaction, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): LockFundsTransaction { + return new LockFundsTransaction(networkType, TransactionVersion.HASH_LOCK, deadline, maxFee, mosaic, duration, signedTransaction); } /** @@ -96,22 +89,24 @@ export class LockFundsTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The locked mosaic. - */ - public readonly mosaic: Mosaic, - /** - * The funds lock duration. - */ - public readonly duration: UInt64, - signedTransaction: SignedTransaction, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The locked mosaic. + */ + public readonly mosaic: Mosaic, + /** + * The funds lock duration. + */ + public readonly duration: UInt64, + signedTransaction: SignedTransaction, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.HASH_LOCK, networkType, version, deadline, maxFee, signature, signer, transactionInfo); this.hash = signedTransaction.hash; this.signedTransaction = signedTransaction; @@ -126,25 +121,21 @@ export class LockFundsTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedHashLockTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - HashLockTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedHashLockTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : HashLockTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = LockFundsTransaction.create( isEmbedded ? Deadline.create() : Deadline.createFromDTO((builder as HashLockTransactionBuilder).getDeadline().timestamp), - new Mosaic( - new MosaicId(builder.getMosaic().mosaicId.unresolvedMosaicId), - new UInt64(builder.getMosaic().amount.amount), - ), + new Mosaic(new MosaicId(builder.getMosaic().mosaicId.unresolvedMosaicId), new UInt64(builder.getMosaic().amount.amount)), new UInt64(builder.getDuration().blockDuration), new SignedTransaction('', Convert.uint8ToHex(builder.getHash().hash256), '', TransactionType.AGGREGATE_BONDED, networkType), networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as HashLockTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -181,8 +172,7 @@ export class LockFundsTransaction extends Transaction { TransactionType.HASH_LOCK.valueOf(), new AmountDto(this.maxFee.toDTO()), new TimestampDto(this.deadline.toDTO()), - new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(this.mosaic.id.id.toDTO()), - new AmountDto(this.mosaic.amount.toDTO())), + new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(this.mosaic.id.id.toDTO()), new AmountDto(this.mosaic.amount.toDTO())), new BlockDurationDto(this.duration.toDTO()), new Hash256Dto(Convert.hexToUint8(this.hash)), ); @@ -199,8 +189,7 @@ export class LockFundsTransaction extends Transaction { this.versionToDTO(), this.networkType.valueOf(), TransactionType.HASH_LOCK.valueOf(), - new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(this.mosaic.id.id.toDTO()), - new AmountDto(this.mosaic.amount.toDTO())), + new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(this.mosaic.id.id.toDTO()), new AmountDto(this.mosaic.amount.toDTO())), new BlockDurationDto(this.duration.toDTO()), new Hash256Dto(Convert.hexToUint8(this.hash)), ); @@ -212,10 +201,15 @@ export class LockFundsTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {LockFundsTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): LockFundsTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): LockFundsTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - mosaic: statement.resolveMosaic(this.mosaic, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)}); + mosaic: statement.resolveMosaic( + this.mosaic, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + }); } } diff --git a/src/model/transaction/HashType.ts b/src/model/transaction/LockHashAlgorithm.ts similarity index 66% rename from src/model/transaction/HashType.ts rename to src/model/transaction/LockHashAlgorithm.ts index 6219e7cb05..5b84bdd524 100644 --- a/src/model/transaction/HashType.ts +++ b/src/model/transaction/LockHashAlgorithm.ts @@ -21,23 +21,27 @@ * 2: Op_Hash_160 (first with SHA-256 and then with RIPEMD-160 (BTC compatibility)) * 3: Op_Hash_256: input is hashed twice with SHA-256 (BTC compatibility) */ -import {Convert as convert} from '../../core/format'; +import { Convert as convert } from '../../core/format'; -export enum HashType { +export enum LockHashAlgorithm { Op_Sha3_256 = 0, - Op_Keccak_256 = 1, - Op_Hash_160 = 2, - Op_Hash_256 = 3, + Op_Hash_160 = 1, + Op_Hash_256 = 2, } -export function HashTypeLengthValidator(hashType: HashType, input: string): boolean { +/** + * Validate the hash length + * @param hashAlgorithm Secret lock hash algorithm + * @param input Hashed value + * @returns {boolean} + */ +export function LockHashAlgorithmLengthValidator(hashAlgorithm: LockHashAlgorithm, input: string): boolean { if (convert.isHexString(input)) { - switch (hashType) { - case HashType.Op_Sha3_256: - case HashType.Op_Hash_256: - case HashType.Op_Keccak_256: + switch (hashAlgorithm) { + case LockHashAlgorithm.Op_Sha3_256: + case LockHashAlgorithm.Op_Hash_256: return input.length === 64; - case HashType.Op_Hash_160: + case LockHashAlgorithm.Op_Hash_160: return input.length === 40 || input.length === 64; default: break; diff --git a/src/model/transaction/MosaicAddressRestrictionTransaction.ts b/src/model/transaction/MosaicAddressRestrictionTransaction.ts index 598342da18..3d36efde49 100644 --- a/src/model/transaction/MosaicAddressRestrictionTransaction.ts +++ b/src/model/transaction/MosaicAddressRestrictionTransaction.ts @@ -43,7 +43,6 @@ import { TransactionType } from './TransactionType'; import { TransactionVersion } from './TransactionVersion'; export class MosaicAddressRestrictionTransaction extends Transaction { - /** * Create a mosaic address restriction transaction object * @@ -65,15 +64,18 @@ export class MosaicAddressRestrictionTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {MosaicAddressRestrictionTransaction} */ - public static create(deadline: Deadline, - mosaicId: MosaicId | NamespaceId, - restrictionKey: UInt64, - targetAddress: Address | NamespaceId, - newRestrictionValue: UInt64, - networkType: NetworkType, - previousRestrictionValue: UInt64 = UInt64.fromHex('FFFFFFFFFFFFFFFF'), - maxFee: UInt64 = new UInt64([0, 0])): MosaicAddressRestrictionTransaction { - return new MosaicAddressRestrictionTransaction(networkType, + public static create( + deadline: Deadline, + mosaicId: MosaicId | NamespaceId, + restrictionKey: UInt64, + targetAddress: Address | NamespaceId, + newRestrictionValue: UInt64, + networkType: NetworkType, + previousRestrictionValue: UInt64 = UInt64.fromHex('FFFFFFFFFFFFFFFF'), + maxFee: UInt64 = new UInt64([0, 0]), + ): MosaicAddressRestrictionTransaction { + return new MosaicAddressRestrictionTransaction( + networkType, TransactionVersion.MOSAIC_ADDRESS_RESTRICTION, deadline, maxFee, @@ -100,33 +102,35 @@ export class MosaicAddressRestrictionTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The mosaic id. - */ - public readonly mosaicId: MosaicId | NamespaceId, - /** - * The restriction key. - */ - public readonly restrictionKey: UInt64, - /** - * The affected unresolved address. - */ - public readonly targetAddress: Address | NamespaceId, - /** - * The previous restriction value. - */ - public readonly previousRestrictionValue: UInt64, - /** - * The new restriction value. - */ - public readonly newRestrictionValue: UInt64, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The mosaic id. + */ + public readonly mosaicId: MosaicId | NamespaceId, + /** + * The restriction key. + */ + public readonly restrictionKey: UInt64, + /** + * The affected unresolved address. + */ + public readonly targetAddress: Address | NamespaceId, + /** + * The previous restriction value. + */ + public readonly previousRestrictionValue: UInt64, + /** + * The new restriction value. + */ + public readonly newRestrictionValue: UInt64, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.MOSAIC_ADDRESS_RESTRICTION, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -136,15 +140,16 @@ export class MosaicAddressRestrictionTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedMosaicAddressRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - MosaicAddressRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedMosaicAddressRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : MosaicAddressRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = MosaicAddressRestrictionTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as MosaicAddressRestrictionTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as MosaicAddressRestrictionTransactionBuilder).getDeadline().timestamp), UnresolvedMapping.toUnresolvedMosaic(new UInt64(builder.getMosaicId().unresolvedMosaicId).toHex()), new UInt64(builder.getRestrictionKey()), UnresolvedMapping.toUnresolvedAddress(Convert.uint8ToHex(builder.getTargetAddress().unresolvedAddress)), @@ -153,8 +158,7 @@ export class MosaicAddressRestrictionTransaction extends Transaction { new UInt64(builder.getPreviousRestrictionValue()), isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as MosaicAddressRestrictionTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -173,8 +177,7 @@ export class MosaicAddressRestrictionTransaction extends Transaction { const byteNewRestrictionValue = 8; const byteTargetAddress = 25; - return byteSize + byteMosaicId + byteRestrictionKey + - byteTargetAddress + bytePreviousRestrictionValue + byteNewRestrictionValue; + return byteSize + byteMosaicId + byteRestrictionKey + byteTargetAddress + bytePreviousRestrictionValue + byteNewRestrictionValue; } /** @@ -183,7 +186,6 @@ export class MosaicAddressRestrictionTransaction extends Transaction { * @returns {string} */ public targetAddressToString(): string { - if (this.targetAddress instanceof NamespaceId) { // namespaceId recipient, return hexadecimal notation return (this.targetAddress as NamespaceId).toHex(); @@ -242,12 +244,21 @@ export class MosaicAddressRestrictionTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {MosaicAddressRestrictionTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): MosaicAddressRestrictionTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): MosaicAddressRestrictionTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - mosaicId: statement.resolveMosaicId(this.mosaicId, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex), - targetAddress: statement.resolveAddress(this.targetAddress, - transactionInfo.height.toString(), transactionInfo.index, aggregateTransactionIndex)}); + mosaicId: statement.resolveMosaicId( + this.mosaicId, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + targetAddress: statement.resolveAddress( + this.targetAddress, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + }); } } diff --git a/src/model/transaction/MosaicAliasTransaction.ts b/src/model/transaction/MosaicAliasTransaction.ts index 420c975590..466a1c6e84 100644 --- a/src/model/transaction/MosaicAliasTransaction.ts +++ b/src/model/transaction/MosaicAliasTransaction.ts @@ -40,7 +40,6 @@ import { TransactionType } from './TransactionType'; import { TransactionVersion } from './TransactionVersion'; export class MosaicAliasTransaction extends Transaction { - /** * Create a mosaic alias transaction object * @param deadline - The deadline to include the transaction. @@ -51,13 +50,16 @@ export class MosaicAliasTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {MosaicAliasTransaction} */ - public static create(deadline: Deadline, - aliasAction: AliasAction, - namespaceId: NamespaceId, - mosaicId: MosaicId, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): MosaicAliasTransaction { - return new MosaicAliasTransaction(networkType, + public static create( + deadline: Deadline, + aliasAction: AliasAction, + namespaceId: NamespaceId, + mosaicId: MosaicId, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): MosaicAliasTransaction { + return new MosaicAliasTransaction( + networkType, TransactionVersion.MOSAIC_ALIAS, deadline, maxFee, @@ -79,25 +81,27 @@ export class MosaicAliasTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The alias action type. - */ - public readonly aliasAction: AliasAction, - /** - * The namespace id that will be an alias. - */ - public readonly namespaceId: NamespaceId, - /** - * The mosaic id. - */ - public readonly mosaicId: MosaicId, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The alias action type. + */ + public readonly aliasAction: AliasAction, + /** + * The namespace id that will be an alias. + */ + public readonly namespaceId: NamespaceId, + /** + * The mosaic id. + */ + public readonly mosaicId: MosaicId, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.MOSAIC_ALIAS, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -107,10 +111,10 @@ export class MosaicAliasTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedMosaicAliasTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - MosaicAliasTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedMosaicAliasTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : MosaicAliasTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = MosaicAliasTransaction.create( @@ -121,8 +125,7 @@ export class MosaicAliasTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as MosaicAliasTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** diff --git a/src/model/transaction/MosaicDefinitionTransaction.ts b/src/model/transaction/MosaicDefinitionTransaction.ts index ba5fee1622..7bcde4e26f 100644 --- a/src/model/transaction/MosaicDefinitionTransaction.ts +++ b/src/model/transaction/MosaicDefinitionTransaction.ts @@ -45,7 +45,6 @@ import { TransactionVersion } from './TransactionVersion'; * This is done via a mosaic definition transaction. */ export class MosaicDefinitionTransaction extends Transaction { - /** * Create a mosaic creation transaction object * @param deadline - The deadline to include the transaction. @@ -58,15 +57,18 @@ export class MosaicDefinitionTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {MosaicDefinitionTransaction} */ - public static create(deadline: Deadline, - nonce: MosaicNonce, - mosaicId: MosaicId, - flags: MosaicFlags, - divisibility: number, - duration: UInt64, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): MosaicDefinitionTransaction { - return new MosaicDefinitionTransaction(networkType, + public static create( + deadline: Deadline, + nonce: MosaicNonce, + mosaicId: MosaicId, + flags: MosaicFlags, + divisibility: number, + duration: UInt64, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): MosaicDefinitionTransaction { + return new MosaicDefinitionTransaction( + networkType, TransactionVersion.MOSAIC_DEFINITION, deadline, maxFee, @@ -92,33 +94,35 @@ export class MosaicDefinitionTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The mosaic nonce. - */ - public readonly nonce: MosaicNonce, - /** - * The mosaic id. - */ - public readonly mosaicId: MosaicId, - /** - * The mosaic properties. - */ - public readonly flags: MosaicFlags, - /** - * Mosaic divisibility - */ - public readonly divisibility: number, - /** - * Mosaic duration, 0 value for eternal mosaic - */ - public readonly duration: UInt64 = UInt64.fromUint(0), - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The mosaic nonce. + */ + public readonly nonce: MosaicNonce, + /** + * The mosaic id. + */ + public readonly mosaicId: MosaicId, + /** + * The mosaic properties. + */ + public readonly flags: MosaicFlags, + /** + * Mosaic divisibility + */ + public readonly divisibility: number, + /** + * Mosaic duration, 0 value for eternal mosaic + */ + public readonly duration: UInt64 = UInt64.fromUint(0), + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.MOSAIC_DEFINITION, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -128,28 +132,25 @@ export class MosaicDefinitionTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedMosaicDefinitionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - MosaicDefinitionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedMosaicDefinitionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : MosaicDefinitionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = MosaicDefinitionTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as MosaicDefinitionTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as MosaicDefinitionTransactionBuilder).getDeadline().timestamp), MosaicNonce.createFromUint8Array(builder.getNonce().serialize()), new MosaicId(builder.getId().mosaicId), - MosaicFlags.create( - (builder.getFlags() & 1) === 1, - (builder.getFlags() & 2) === 2, - (builder.getFlags() & 4) === 4), + MosaicFlags.create((builder.getFlags() & 1) === 1, (builder.getFlags() & 2) === 2, (builder.getFlags() & 4) === 4), builder.getDivisibility(), new UInt64(builder.getDuration().blockDuration), networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as MosaicDefinitionTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** diff --git a/src/model/transaction/MosaicGlobalRestrictionTransaction.ts b/src/model/transaction/MosaicGlobalRestrictionTransaction.ts index 8eaabb8ccf..65088f0d89 100644 --- a/src/model/transaction/MosaicGlobalRestrictionTransaction.ts +++ b/src/model/transaction/MosaicGlobalRestrictionTransaction.ts @@ -42,7 +42,6 @@ import { TransactionType } from './TransactionType'; import { TransactionVersion } from './TransactionVersion'; export class MosaicGlobalRestrictionTransaction extends Transaction { - /** * Create a mosaic address restriction transaction object * @@ -69,17 +68,20 @@ export class MosaicGlobalRestrictionTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {MosaicGlobalRestrictionTransaction} */ - public static create(deadline: Deadline, - mosaicId: MosaicId | NamespaceId, - restrictionKey: UInt64, - previousRestrictionValue: UInt64, - previousRestrictionType: MosaicRestrictionType, - newRestrictionValue: UInt64, - newRestrictionType: MosaicRestrictionType, - networkType: NetworkType, - referenceMosaicId: MosaicId | NamespaceId = UnresolvedMapping.toUnresolvedMosaic(UInt64.fromUint(0).toHex()), - maxFee: UInt64 = new UInt64([0, 0])): MosaicGlobalRestrictionTransaction { - return new MosaicGlobalRestrictionTransaction(networkType, + public static create( + deadline: Deadline, + mosaicId: MosaicId | NamespaceId, + restrictionKey: UInt64, + previousRestrictionValue: UInt64, + previousRestrictionType: MosaicRestrictionType, + newRestrictionValue: UInt64, + newRestrictionType: MosaicRestrictionType, + networkType: NetworkType, + referenceMosaicId: MosaicId | NamespaceId = UnresolvedMapping.toUnresolvedMosaic(UInt64.fromUint(0).toHex()), + maxFee: UInt64 = new UInt64([0, 0]), + ): MosaicGlobalRestrictionTransaction { + return new MosaicGlobalRestrictionTransaction( + networkType, TransactionVersion.MOSAIC_GLOBAL_RESTRICTION, deadline, maxFee, @@ -109,41 +111,43 @@ export class MosaicGlobalRestrictionTransaction extends Transaction { * @param signer - The signer * @param transactionInfo - The transaction info */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The mosaic id. - */ - public readonly mosaicId: MosaicId | NamespaceId, - /** - * The refrence mosaic id. - */ - public readonly referenceMosaicId: MosaicId | NamespaceId, - /** - * The restriction key. - */ - public readonly restrictionKey: UInt64, - /** - * The previous restriction value. - */ - public readonly previousRestrictionValue: UInt64, - /** - * The previous restriction type. - */ - public readonly previousRestrictionType: MosaicRestrictionType, - /** - * The new restriction value. - */ - public readonly newRestrictionValue: UInt64, - /** - * The new restriction type. - */ - public readonly newRestrictionType: MosaicRestrictionType, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The mosaic id. + */ + public readonly mosaicId: MosaicId | NamespaceId, + /** + * The refrence mosaic id. + */ + public readonly referenceMosaicId: MosaicId | NamespaceId, + /** + * The restriction key. + */ + public readonly restrictionKey: UInt64, + /** + * The previous restriction value. + */ + public readonly previousRestrictionValue: UInt64, + /** + * The previous restriction type. + */ + public readonly previousRestrictionType: MosaicRestrictionType, + /** + * The new restriction value. + */ + public readonly newRestrictionValue: UInt64, + /** + * The new restriction type. + */ + public readonly newRestrictionType: MosaicRestrictionType, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.MOSAIC_GLOBAL_RESTRICTION, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -153,15 +157,16 @@ export class MosaicGlobalRestrictionTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedMosaicGlobalRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - MosaicGlobalRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedMosaicGlobalRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : MosaicGlobalRestrictionTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = MosaicGlobalRestrictionTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as MosaicGlobalRestrictionTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as MosaicGlobalRestrictionTransactionBuilder).getDeadline().timestamp), UnresolvedMapping.toUnresolvedMosaic(new UInt64(builder.getMosaicId().unresolvedMosaicId).toHex()), new UInt64(builder.getRestrictionKey()), new UInt64(builder.getPreviousRestrictionValue()), @@ -172,8 +177,7 @@ export class MosaicGlobalRestrictionTransaction extends Transaction { UnresolvedMapping.toUnresolvedMosaic(new UInt64(builder.getReferenceMosaicId().unresolvedMosaicId).toHex()), isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as MosaicGlobalRestrictionTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -194,9 +198,16 @@ export class MosaicGlobalRestrictionTransaction extends Transaction { const bytePreviousRestrictionType = 1; const byteNewRestrictionType = 1; - return byteSize + byteMosaicId + byteRestrictionKey + byteReferenceMosaicId + - bytePreviousRestrictionValue + byteNewRestrictionValue + byteNewRestrictionType + - bytePreviousRestrictionType; + return ( + byteSize + + byteMosaicId + + byteRestrictionKey + + byteReferenceMosaicId + + bytePreviousRestrictionValue + + byteNewRestrictionValue + + byteNewRestrictionType + + bytePreviousRestrictionType + ); } /** @@ -252,12 +263,21 @@ export class MosaicGlobalRestrictionTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {MosaicGlobalRestrictionTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): MosaicGlobalRestrictionTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): MosaicGlobalRestrictionTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - mosaicId: statement.resolveMosaicId(this.mosaicId, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex), - referenceMosaicId: statement.resolveMosaicId(this.referenceMosaicId, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)}); + mosaicId: statement.resolveMosaicId( + this.mosaicId, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + referenceMosaicId: statement.resolveMosaicId( + this.referenceMosaicId, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + }); } } diff --git a/src/model/transaction/MosaicMetadataTransaction.ts b/src/model/transaction/MosaicMetadataTransaction.ts index 41e21d2214..68a0c364b5 100644 --- a/src/model/transaction/MosaicMetadataTransaction.ts +++ b/src/model/transaction/MosaicMetadataTransaction.ts @@ -58,15 +58,18 @@ export class MosaicMetadataTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {MosaicMetadataTransaction} */ - public static create(deadline: Deadline, - targetPublicKey: string, - scopedMetadataKey: UInt64, - targetMosaicId: MosaicId | NamespaceId, - valueSizeDelta: number, - value: string, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): MosaicMetadataTransaction { - return new MosaicMetadataTransaction(networkType, + public static create( + deadline: Deadline, + targetPublicKey: string, + scopedMetadataKey: UInt64, + targetMosaicId: MosaicId | NamespaceId, + valueSizeDelta: number, + value: string, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): MosaicMetadataTransaction { + return new MosaicMetadataTransaction( + networkType, TransactionVersion.MOSAIC_METADATA, deadline, maxFee, @@ -74,7 +77,8 @@ export class MosaicMetadataTransaction extends Transaction { scopedMetadataKey, targetMosaicId, valueSizeDelta, - value); + value, + ); } /** @@ -91,38 +95,37 @@ export class MosaicMetadataTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * Public key of the target account. - */ - public readonly targetPublicKey: string, - /** - * Metadata key scoped to source, target and type. - */ - public readonly scopedMetadataKey: UInt64, - /** - * Target mosaic identifier. - */ - public readonly targetMosaicId: MosaicId | NamespaceId, - /** - * Change in value size in bytes. - */ - public readonly valueSizeDelta: number, - /** - * String value with UTF-8 encoding. - * Difference between the previous value and new value. - */ - public readonly value: string, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * Public key of the target account. + */ + public readonly targetPublicKey: string, + /** + * Metadata key scoped to source, target and type. + */ + public readonly scopedMetadataKey: UInt64, + /** + * Target mosaic identifier. + */ + public readonly targetMosaicId: MosaicId | NamespaceId, + /** + * Change in value size in bytes. + */ + public readonly valueSizeDelta: number, + /** + * String value with UTF-8 encoding. + * Difference between the previous value and new value. + */ + public readonly value: string, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.MOSAIC_METADATA, networkType, version, deadline, maxFee, signature, signer, transactionInfo); - if (value.length > 1024) { - throw new Error('The maximum value size is 1024'); - } } /** @@ -131,10 +134,10 @@ export class MosaicMetadataTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedMosaicMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - MosaicMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedMosaicMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : MosaicMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = MosaicMetadataTransaction.create( @@ -147,8 +150,7 @@ export class MosaicMetadataTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as MosaicMetadataTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -167,8 +169,7 @@ export class MosaicMetadataTransaction extends Transaction { const byteValueSizeDelta = 2; const valueSize = 2; - return byteSize + targetPublicKey + byteScopedMetadataKey + - byteTargetMosaicId + byteValueSizeDelta + valueSize + this.value.length; + return byteSize + targetPublicKey + byteScopedMetadataKey + byteTargetMosaicId + byteValueSizeDelta + valueSize + this.value.length; } /** @@ -220,10 +221,15 @@ export class MosaicMetadataTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {MosaicMetadataTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): MosaicMetadataTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): MosaicMetadataTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - targetMosaicId: statement.resolveMosaicId(this.targetMosaicId, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)}); + targetMosaicId: statement.resolveMosaicId( + this.targetMosaicId, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + }); } } diff --git a/src/model/transaction/MosaicSupplyChangeTransaction.ts b/src/model/transaction/MosaicSupplyChangeTransaction.ts index a2cee6f602..bda8cff8be 100644 --- a/src/model/transaction/MosaicSupplyChangeTransaction.ts +++ b/src/model/transaction/MosaicSupplyChangeTransaction.ts @@ -46,7 +46,6 @@ import { TransactionVersion } from './TransactionVersion'; * i.e. increase or decrease the supply. */ export class MosaicSupplyChangeTransaction extends Transaction { - /** * Create a mosaic supply change transaction object * @param deadline - The deadline to include the transaction. @@ -57,13 +56,16 @@ export class MosaicSupplyChangeTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {MosaicSupplyChangeTransaction} */ - public static create(deadline: Deadline, - mosaicId: MosaicId | NamespaceId, - action: MosaicSupplyChangeAction, - delta: UInt64, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): MosaicSupplyChangeTransaction { - return new MosaicSupplyChangeTransaction(networkType, + public static create( + deadline: Deadline, + mosaicId: MosaicId | NamespaceId, + action: MosaicSupplyChangeAction, + delta: UInt64, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): MosaicSupplyChangeTransaction { + return new MosaicSupplyChangeTransaction( + networkType, TransactionVersion.MOSAIC_SUPPLY_CHANGE, deadline, maxFee, @@ -85,25 +87,27 @@ export class MosaicSupplyChangeTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The unresolved mosaic id. - */ - public readonly mosaicId: MosaicId | NamespaceId, - /** - * The supply type. - */ - public readonly action: MosaicSupplyChangeAction, - /** - * The supply change in units for the mosaic. - */ - public readonly delta: UInt64, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The unresolved mosaic id. + */ + public readonly mosaicId: MosaicId | NamespaceId, + /** + * The supply type. + */ + public readonly action: MosaicSupplyChangeAction, + /** + * The supply change in units for the mosaic. + */ + public readonly delta: UInt64, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.MOSAIC_SUPPLY_CHANGE, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -113,23 +117,23 @@ export class MosaicSupplyChangeTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedMosaicSupplyChangeTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - MosaicSupplyChangeTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedMosaicSupplyChangeTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : MosaicSupplyChangeTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = MosaicSupplyChangeTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as MosaicSupplyChangeTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as MosaicSupplyChangeTransactionBuilder).getDeadline().timestamp), UnresolvedMapping.toUnresolvedMosaic(new UInt64(builder.getMosaicId().unresolvedMosaicId).toHex()), builder.getAction().valueOf(), new UInt64(builder.getDelta().amount), networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as MosaicSupplyChangeTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -194,10 +198,15 @@ export class MosaicSupplyChangeTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {MosaicSupplyChangeTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): MosaicSupplyChangeTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): MosaicSupplyChangeTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - mosaicId: statement.resolveMosaicId(this.mosaicId, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)}); + mosaicId: statement.resolveMosaicId( + this.mosaicId, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + }); } } diff --git a/src/model/transaction/MultisigAccountModificationTransaction.ts b/src/model/transaction/MultisigAccountModificationTransaction.ts index 399d329a92..89a3ba021e 100644 --- a/src/model/transaction/MultisigAccountModificationTransaction.ts +++ b/src/model/transaction/MultisigAccountModificationTransaction.ts @@ -41,7 +41,6 @@ import { TransactionVersion } from './TransactionVersion'; * @since 1.0 */ export class MultisigAccountModificationTransaction extends Transaction { - /** * Create a modify multisig account transaction object * @param deadline - The deadline to include the transaction. @@ -53,21 +52,25 @@ export class MultisigAccountModificationTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {MultisigAccountModificationTransaction} */ - public static create(deadline: Deadline, - minApprovalDelta: number, - minRemovalDelta: number, - publicKeyAdditions: PublicAccount[], - publicKeyDeletions: PublicAccount[], - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): MultisigAccountModificationTransaction { - return new MultisigAccountModificationTransaction(networkType, + public static create( + deadline: Deadline, + minApprovalDelta: number, + minRemovalDelta: number, + publicKeyAdditions: PublicAccount[], + publicKeyDeletions: PublicAccount[], + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): MultisigAccountModificationTransaction { + return new MultisigAccountModificationTransaction( + networkType, TransactionVersion.MULTISIG_ACCOUNT_MODIFICATION, deadline, maxFee, minApprovalDelta, minRemovalDelta, publicKeyAdditions, - publicKeyDeletions); + publicKeyDeletions, + ); } /** @@ -83,31 +86,33 @@ export class MultisigAccountModificationTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The number of signatures needed to approve a transaction. - * If we are modifying and existing multi-signature account this indicates the relative change of the minimum cosignatories. - */ - public readonly minApprovalDelta: number, - /** - * The number of signatures needed to remove a cosignatory. - * If we are modifying and existing multi-signature account this indicates the relative change of the minimum cosignatories. - */ - public readonly minRemovalDelta: number, - /** - * The Cosignatory public key additions. - */ - public readonly publicKeyAdditions: PublicAccount[], - /** - * The Cosignatory public key deletion. - */ - public readonly publicKeyDeletions: PublicAccount[], - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The number of signatures needed to approve a transaction. + * If we are modifying and existing multi-signature account this indicates the relative change of the minimum cosignatories. + */ + public readonly minApprovalDelta: number, + /** + * The number of signatures needed to remove a cosignatory. + * If we are modifying and existing multi-signature account this indicates the relative change of the minimum cosignatories. + */ + public readonly minRemovalDelta: number, + /** + * The Cosignatory public key additions. + */ + public readonly publicKeyAdditions: PublicAccount[], + /** + * The Cosignatory public key deletion. + */ + public readonly publicKeyDeletions: PublicAccount[], + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.MULTISIG_ACCOUNT_MODIFICATION, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -117,15 +122,16 @@ export class MultisigAccountModificationTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedMultisigAccountModificationTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - MultisigAccountModificationTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedMultisigAccountModificationTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : MultisigAccountModificationTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = MultisigAccountModificationTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as MultisigAccountModificationTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as MultisigAccountModificationTransactionBuilder).getDeadline().timestamp), builder.getMinApprovalDelta(), builder.getMinRemovalDelta(), builder.getPublicKeyAdditions().map((addition) => { @@ -137,8 +143,7 @@ export class MultisigAccountModificationTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as MultisigAccountModificationTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -159,8 +164,16 @@ export class MultisigAccountModificationTransaction extends Transaction { const bytePublicKeyDeletions = 32 * this.publicKeyDeletions.length; const byteReserved1 = 4; - return byteSize + byteRemovalDelta + byteApprovalDelta + byteAdditionCount + - byteDeletionCount + bytePublicKeyAdditions + bytePublicKeyDeletions + byteReserved1; + return ( + byteSize + + byteRemovalDelta + + byteApprovalDelta + + byteAdditionCount + + byteDeletionCount + + bytePublicKeyAdditions + + bytePublicKeyDeletions + + byteReserved1 + ); } /** diff --git a/src/model/transaction/MultisigCosignatoryModification.ts b/src/model/transaction/MultisigCosignatoryModification.ts index 8369b0fca6..189139a77f 100644 --- a/src/model/transaction/MultisigCosignatoryModification.ts +++ b/src/model/transaction/MultisigCosignatoryModification.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {PublicAccount} from '../account/PublicAccount'; -import {CosignatoryModificationAction} from './CosignatoryModificationAction'; +import { PublicAccount } from '../account/PublicAccount'; +import { CosignatoryModificationAction } from './CosignatoryModificationAction'; /** * Multisig cosignatory modifications are part of the NEM's multisig account system. @@ -24,28 +24,26 @@ import {CosignatoryModificationAction} from './CosignatoryModificationAction'; * */ export class MultisigCosignatoryModification { - /** * Constructor * @param modificationAction * @param cosignatoryPublicAccount */ constructor( - /** - * Multi-signature modification type. - */ - public readonly modificationAction: CosignatoryModificationAction, - /** - * Cosignatory public account. - */ - public readonly cosignatoryPublicAccount: PublicAccount) { - - } + /** + * Multi-signature modification type. + */ + public readonly modificationAction: CosignatoryModificationAction, + /** + * Cosignatory public account. + */ + public readonly cosignatoryPublicAccount: PublicAccount, + ) {} /** * @internal */ - toDTO() { + toDTO(): any { return { cosignatoryPublicKey: this.cosignatoryPublicAccount.publicKey, modificationAction: this.modificationAction, diff --git a/src/model/transaction/NamespaceMetadataTransaction.ts b/src/model/transaction/NamespaceMetadataTransaction.ts index a2e6df2457..a0e2b4dbe7 100644 --- a/src/model/transaction/NamespaceMetadataTransaction.ts +++ b/src/model/transaction/NamespaceMetadataTransaction.ts @@ -54,15 +54,18 @@ export class NamespaceMetadataTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {NamespaceMetadataTransaction} */ - public static create(deadline: Deadline, - targetPublicKey: string, - scopedMetadataKey: UInt64, - targetNamespaceId: NamespaceId, - valueSizeDelta: number, - value: string, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): NamespaceMetadataTransaction { - return new NamespaceMetadataTransaction(networkType, + public static create( + deadline: Deadline, + targetPublicKey: string, + scopedMetadataKey: UInt64, + targetNamespaceId: NamespaceId, + valueSizeDelta: number, + value: string, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): NamespaceMetadataTransaction { + return new NamespaceMetadataTransaction( + networkType, TransactionVersion.NAMESPACE_METADATA, deadline, maxFee, @@ -70,7 +73,8 @@ export class NamespaceMetadataTransaction extends Transaction { scopedMetadataKey, targetNamespaceId, valueSizeDelta, - value); + value, + ); } /** @@ -87,38 +91,37 @@ export class NamespaceMetadataTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * Public key of the target account. - */ - public readonly targetPublicKey: string, - /** - * Metadata key scoped to source, target and type. - */ - public readonly scopedMetadataKey: UInt64, - /** - * Target namespace identifier. - */ - public readonly targetNamespaceId: NamespaceId, - /** - * Change in value size in bytes. - */ - public readonly valueSizeDelta: number, - /** - * String value with UTF-8 encoding. - * Difference between the previous value and new value. - */ - public readonly value: string, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * Public key of the target account. + */ + public readonly targetPublicKey: string, + /** + * Metadata key scoped to source, target and type. + */ + public readonly scopedMetadataKey: UInt64, + /** + * Target namespace identifier. + */ + public readonly targetNamespaceId: NamespaceId, + /** + * Change in value size in bytes. + */ + public readonly valueSizeDelta: number, + /** + * String value with UTF-8 encoding. + * Difference between the previous value and new value. + */ + public readonly value: string, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.NAMESPACE_METADATA, networkType, version, deadline, maxFee, signature, signer, transactionInfo); - if (value.length > 1024) { - throw new Error('The maximum value size is 1024'); - } } /** @@ -127,15 +130,16 @@ export class NamespaceMetadataTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedNamespaceMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - NamespaceMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedNamespaceMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : NamespaceMetadataTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = NamespaceMetadataTransaction.create( - isEmbedded ? Deadline.create() : - Deadline.createFromDTO((builder as NamespaceMetadataTransactionBuilder).getDeadline().timestamp), + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as NamespaceMetadataTransactionBuilder).getDeadline().timestamp), Convert.uint8ToHex(builder.getTargetPublicKey().key), new UInt64(builder.getScopedMetadataKey()), new NamespaceId(builder.getTargetNamespaceId().namespaceId), @@ -144,8 +148,7 @@ export class NamespaceMetadataTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as NamespaceMetadataTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -164,8 +167,15 @@ export class NamespaceMetadataTransaction extends Transaction { const byteValueSizeDelta = 2; const byteValueSize = 2; - return byteSize + targetPublicKey + byteScopedMetadataKey + - byteTargetNamespaceId + byteValueSizeDelta + byteValueSize + this.value.length; + return ( + byteSize + + targetPublicKey + + byteScopedMetadataKey + + byteTargetNamespaceId + + byteValueSizeDelta + + byteValueSize + + this.value.length + ); } /** diff --git a/src/model/transaction/NamespaceRegistrationTransaction.ts b/src/model/transaction/NamespaceRegistrationTransaction.ts index 9bb4e98643..7de573ae91 100644 --- a/src/model/transaction/NamespaceRegistrationTransaction.ts +++ b/src/model/transaction/NamespaceRegistrationTransaction.ts @@ -44,7 +44,6 @@ import { TransactionVersion } from './TransactionVersion'; * This is done via a NamespaceRegistrationTransaction. */ export class NamespaceRegistrationTransaction extends Transaction { - /** * Create a root namespace object * @param deadline - The deadline to include the transaction. @@ -54,12 +53,15 @@ export class NamespaceRegistrationTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {NamespaceRegistrationTransaction} */ - public static createRootNamespace(deadline: Deadline, - namespaceName: string, - duration: UInt64, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): NamespaceRegistrationTransaction { - return new NamespaceRegistrationTransaction(networkType, + public static createRootNamespace( + deadline: Deadline, + namespaceName: string, + duration: UInt64, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): NamespaceRegistrationTransaction { + return new NamespaceRegistrationTransaction( + networkType, TransactionVersion.NAMESPACE_REGISTRATION, deadline, maxFee, @@ -79,26 +81,29 @@ export class NamespaceRegistrationTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {NamespaceRegistrationTransaction} */ - public static createSubNamespace(deadline: Deadline, - namespaceName: string, - parentNamespace: string | NamespaceId, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): NamespaceRegistrationTransaction { + public static createSubNamespace( + deadline: Deadline, + namespaceName: string, + parentNamespace: string | NamespaceId, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): NamespaceRegistrationTransaction { let parentId: NamespaceId; if (typeof parentNamespace === 'string') { parentId = new NamespaceId(NamespaceMosaicIdGenerator.subnamespaceParentId(parentNamespace, namespaceName)); } else { parentId = parentNamespace; } - return new NamespaceRegistrationTransaction(networkType, + return new NamespaceRegistrationTransaction( + networkType, TransactionVersion.NAMESPACE_REGISTRATION, deadline, maxFee, NamespaceRegistrationType.SubNamespace, namespaceName, - typeof parentNamespace === 'string' ? - new NamespaceId(NamespaceMosaicIdGenerator.subnamespaceNamespaceId(parentNamespace, namespaceName)) : - new NamespaceId(NamespaceMosaicIdGenerator.namespaceId(namespaceName)), + typeof parentNamespace === 'string' + ? new NamespaceId(NamespaceMosaicIdGenerator.subnamespaceNamespaceId(parentNamespace, namespaceName)) + : new NamespaceId(NamespaceMosaicIdGenerator.namespaceId(namespaceName)), undefined, parentId, ); @@ -118,34 +123,36 @@ export class NamespaceRegistrationTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The namespace type could be namespace or sub namespace - */ - public readonly registrationType: NamespaceRegistrationType, - /** - * The namespace name - */ - public readonly namespaceName: string, - /** - * The id of the namespace derived from namespaceName. - * When creating a sub namespace the namespaceId is derived from namespaceName and parentName. - */ - public readonly namespaceId: NamespaceId, - /** - * The number of blocks a namespace is active - */ - public readonly duration?: UInt64, - /** - * The id of the parent sub namespace - */ - public readonly parentId?: NamespaceId, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The namespace type could be namespace or sub namespace + */ + public readonly registrationType: NamespaceRegistrationType, + /** + * The namespace name + */ + public readonly namespaceName: string, + /** + * The id of the namespace derived from namespaceName. + * When creating a sub namespace the namespaceId is derived from namespaceName and parentName. + */ + public readonly namespaceId: NamespaceId, + /** + * The number of blocks a namespace is active + */ + public readonly duration?: UInt64, + /** + * The id of the parent sub namespace + */ + public readonly parentId?: NamespaceId, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.NAMESPACE_REGISTRATION, networkType, version, deadline, maxFee, signature, signer, transactionInfo); } @@ -155,31 +162,34 @@ export class NamespaceRegistrationTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedNamespaceRegistrationTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - NamespaceRegistrationTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedNamespaceRegistrationTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : NamespaceRegistrationTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const registrationType = builder.getRegistrationType().valueOf(); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); - const transaction = registrationType === NamespaceRegistrationType.RootNamespace ? - NamespaceRegistrationTransaction.createRootNamespace( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as NamespaceRegistrationTransactionBuilder).getDeadline().timestamp), - Convert.decodeHex(Convert.uint8ToHex(builder.getName())), - new UInt64(builder.getDuration()!.blockDuration), - networkType, - isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as NamespaceRegistrationTransactionBuilder).fee.amount), - ) : NamespaceRegistrationTransaction.createSubNamespace( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as NamespaceRegistrationTransactionBuilder).getDeadline().timestamp), - Convert.decodeHex(Convert.uint8ToHex(builder.getName())), - new NamespaceId(builder.getParentId()!.namespaceId), - networkType, - isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as NamespaceRegistrationTransactionBuilder).fee.amount), - ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + const transaction = + registrationType === NamespaceRegistrationType.RootNamespace + ? NamespaceRegistrationTransaction.createRootNamespace( + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as NamespaceRegistrationTransactionBuilder).getDeadline().timestamp), + Convert.decodeHex(Convert.uint8ToHex(builder.getName())), + new UInt64(builder.getDuration()!.blockDuration), + networkType, + isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as NamespaceRegistrationTransactionBuilder).fee.amount), + ) + : NamespaceRegistrationTransaction.createSubNamespace( + isEmbedded + ? Deadline.create() + : Deadline.createFromDTO((builder as NamespaceRegistrationTransactionBuilder).getDeadline().timestamp), + Convert.decodeHex(Convert.uint8ToHex(builder.getName())), + new NamespaceId(builder.getParentId()!.namespaceId), + networkType, + isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as NamespaceRegistrationTransactionBuilder).fee.amount), + ); + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** diff --git a/src/model/transaction/PersistentDelegationRequestTransaction.ts b/src/model/transaction/PersistentDelegationRequestTransaction.ts index d971c30acc..a74f076352 100644 --- a/src/model/transaction/PersistentDelegationRequestTransaction.ts +++ b/src/model/transaction/PersistentDelegationRequestTransaction.ts @@ -33,13 +33,13 @@ export class PersistentDelegationRequestTransaction extends TransferTransaction * @returns {TransferTransaction} */ public static createPersistentDelegationRequestTransaction( - deadline: Deadline, - delegatedPrivateKey: string, - recipientPublicKey: string, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): PersistentDelegationRequestTransaction { - const message = PersistentHarvestingDelegationMessage - .create(delegatedPrivateKey, recipientPublicKey, networkType); + deadline: Deadline, + delegatedPrivateKey: string, + recipientPublicKey: string, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): PersistentDelegationRequestTransaction { + const message = PersistentHarvestingDelegationMessage.create(delegatedPrivateKey, recipientPublicKey, networkType); return super.create(deadline, Address.createFromPublicKey(recipientPublicKey, networkType), [], message, networkType, maxFee); } } diff --git a/src/model/transaction/SecretLockTransaction.ts b/src/model/transaction/SecretLockTransaction.ts index 3dc82dab84..5545f4d692 100644 --- a/src/model/transaction/SecretLockTransaction.ts +++ b/src/model/transaction/SecretLockTransaction.ts @@ -38,7 +38,7 @@ import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; -import { HashType, HashTypeLengthValidator } from './HashType'; +import { LockHashAlgorithmLengthValidator, LockHashAlgorithm } from './LockHashAlgorithm'; import { InnerTransaction } from './InnerTransaction'; import { Transaction } from './Transaction'; import { TransactionInfo } from './TransactionInfo'; @@ -46,14 +46,13 @@ import { TransactionType } from './TransactionType'; import { TransactionVersion } from './TransactionVersion'; export class SecretLockTransaction extends Transaction { - /** * Create a secret lock transaction object. * * @param deadline - The deadline to include the transaction. * @param mosaic - The locked mosaic. * @param duration - The funds lock duration. - * @param hashType - The hash algorithm secret is generated with. + * @param hashAlgorithm - The hash algorithm secret is generated with. * @param secret - The proof hashed. * @param recipientAddress - The unresolved recipient address of the funds. * @param networkType - The network type. @@ -61,14 +60,16 @@ export class SecretLockTransaction extends Transaction { * * @return a SecretLockTransaction instance */ - public static create(deadline: Deadline, - mosaic: Mosaic, - duration: UInt64, - hashType: HashType, - secret: string, - recipientAddress: Address | NamespaceId, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): SecretLockTransaction { + public static create( + deadline: Deadline, + mosaic: Mosaic, + duration: UInt64, + hashAlgorithm: LockHashAlgorithm, + secret: string, + recipientAddress: Address | NamespaceId, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): SecretLockTransaction { return new SecretLockTransaction( networkType, TransactionVersion.SECRET_LOCK, @@ -76,7 +77,7 @@ export class SecretLockTransaction extends Transaction { maxFee, mosaic, duration, - hashType, + hashAlgorithm, secret, recipientAddress, ); @@ -89,43 +90,45 @@ export class SecretLockTransaction extends Transaction { * @param maxFee * @param mosaic * @param duration - * @param hashType + * @param hashAlgorithm * @param secret * @param recipientAddress * @param signature * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The locked mosaic. - */ - public readonly mosaic: Mosaic, - /** - * The duration for the funds to be released or returned. - */ - public readonly duration: UInt64, - /** - * The hash algorithm, secret is generated with. - */ - public readonly hashType: HashType, - /** - * The proof hashed. - */ - public readonly secret: string, - /** - * The unresolved recipientAddress of the funds. - */ - public readonly recipientAddress: Address | NamespaceId, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The locked mosaic. + */ + public readonly mosaic: Mosaic, + /** + * The duration for the funds to be released or returned. + */ + public readonly duration: UInt64, + /** + * The hash algorithm, secret is generated with. + */ + public readonly hashAlgorithm: LockHashAlgorithm, + /** + * The proof hashed. + */ + public readonly secret: string, + /** + * The unresolved recipientAddress of the funds. + */ + public readonly recipientAddress: Address | NamespaceId, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.SECRET_LOCK, networkType, version, deadline, maxFee, signature, signer, transactionInfo); - if (!HashTypeLengthValidator(hashType, this.secret)) { - throw new Error('HashType and Secret have incompatible length or not hexadecimal string'); + if (!LockHashAlgorithmLengthValidator(hashAlgorithm, this.secret)) { + throw new Error('HashAlgorithm and Secret have incompatible length or not hexadecimal string'); } } @@ -135,15 +138,14 @@ export class SecretLockTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedSecretLockTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - SecretLockTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedSecretLockTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : SecretLockTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = SecretLockTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as SecretLockTransactionBuilder).getDeadline().timestamp), + isEmbedded ? Deadline.create() : Deadline.createFromDTO((builder as SecretLockTransactionBuilder).getDeadline().timestamp), new Mosaic( UnresolvedMapping.toUnresolvedMosaic(new UInt64(builder.getMosaic().mosaicId.unresolvedMosaicId).toHex()), new UInt64(builder.getMosaic().amount.amount), @@ -155,8 +157,7 @@ export class SecretLockTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as SecretLockTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -207,10 +208,9 @@ export class SecretLockTransaction extends Transaction { new AmountDto(this.maxFee.toDTO()), new TimestampDto(this.deadline.toDTO()), new Hash256Dto(this.getSecretByte()), - new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(this.mosaic.id.id.toDTO()), - new AmountDto(this.mosaic.amount.toDTO())), + new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(this.mosaic.id.id.toDTO()), new AmountDto(this.mosaic.amount.toDTO())), new BlockDurationDto(this.duration.toDTO()), - this.hashType.valueOf(), + this.hashAlgorithm.valueOf(), new UnresolvedAddressDto(UnresolvedMapping.toUnresolvedAddressBytes(this.recipientAddress, this.networkType)), ); return transactionBuilder.serialize(); @@ -227,10 +227,9 @@ export class SecretLockTransaction extends Transaction { this.networkType.valueOf(), TransactionType.SECRET_LOCK.valueOf(), new Hash256Dto(this.getSecretByte()), - new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(this.mosaic.id.id.toDTO()), - new AmountDto(this.mosaic.amount.toDTO())), + new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(this.mosaic.id.id.toDTO()), new AmountDto(this.mosaic.amount.toDTO())), new BlockDurationDto(this.duration.toDTO()), - this.hashType.valueOf(), + this.hashAlgorithm.valueOf(), new UnresolvedAddressDto(UnresolvedMapping.toUnresolvedAddressBytes(this.recipientAddress, this.networkType)), ); } @@ -241,12 +240,21 @@ export class SecretLockTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {SecretLockTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): SecretLockTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): SecretLockTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - recipientAddress: statement.resolveAddress(this.recipientAddress, - transactionInfo.height.toString(), transactionInfo.index, aggregateTransactionIndex), - mosaic: statement.resolveMosaic(this.mosaic, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex)}); + recipientAddress: statement.resolveAddress( + this.recipientAddress, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + mosaic: statement.resolveMosaic( + this.mosaic, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + }); } } diff --git a/src/model/transaction/SecretProofTransaction.ts b/src/model/transaction/SecretProofTransaction.ts index 5f4db4f18c..d5a61be38b 100644 --- a/src/model/transaction/SecretProofTransaction.ts +++ b/src/model/transaction/SecretProofTransaction.ts @@ -35,7 +35,7 @@ import { NetworkType } from '../network/NetworkType'; import { Statement } from '../receipt/Statement'; import { UInt64 } from '../UInt64'; import { Deadline } from './Deadline'; -import { HashType, HashTypeLengthValidator } from './HashType'; +import { LockHashAlgorithmLengthValidator, LockHashAlgorithm } from './LockHashAlgorithm'; import { InnerTransaction } from './InnerTransaction'; import { Transaction } from './Transaction'; import { TransactionInfo } from './TransactionInfo'; @@ -43,12 +43,11 @@ import { TransactionType } from './TransactionType'; import { TransactionVersion } from './TransactionVersion'; export class SecretProofTransaction extends Transaction { - /** * Create a secret proof transaction object. * * @param deadline - The deadline to include the transaction. - * @param hashType - The hash algorithm secret is generated with. + * @param hashAlgorithm - The hash algorithm secret is generated with. * @param secret - The seed proof hashed. * @param recipientAddress - UnresolvedAddress * @param proof - The seed proof. @@ -57,19 +56,21 @@ export class SecretProofTransaction extends Transaction { * * @return a SecretProofTransaction instance */ - public static create(deadline: Deadline, - hashType: HashType, - secret: string, - recipientAddress: Address | NamespaceId, - proof: string, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): SecretProofTransaction { + public static create( + deadline: Deadline, + hashAlgorithm: LockHashAlgorithm, + secret: string, + recipientAddress: Address | NamespaceId, + proof: string, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): SecretProofTransaction { return new SecretProofTransaction( networkType, TransactionVersion.SECRET_PROOF, deadline, maxFee, - hashType, + hashAlgorithm, secret, recipientAddress, proof, @@ -81,7 +82,7 @@ export class SecretProofTransaction extends Transaction { * @param version * @param deadline * @param maxFee - * @param hashType + * @param hashAlgorithm * @param secret * @param recipientAddress * @param proof @@ -89,19 +90,21 @@ export class SecretProofTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - public readonly hashType: HashType, - public readonly secret: string, - public readonly recipientAddress: Address | NamespaceId, - public readonly proof: string, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + public readonly hashAlgorithm: LockHashAlgorithm, + public readonly secret: string, + public readonly recipientAddress: Address | NamespaceId, + public readonly proof: string, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.SECRET_PROOF, networkType, version, deadline, maxFee, signature, signer, transactionInfo); - if (!HashTypeLengthValidator(hashType, this.secret)) { + if (!LockHashAlgorithmLengthValidator(hashAlgorithm, this.secret)) { throw new Error('HashType and Secret have incompatible length or not hexadecimal string'); } } @@ -112,15 +115,14 @@ export class SecretProofTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedSecretProofTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - SecretProofTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedSecretProofTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : SecretProofTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = SecretProofTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as SecretProofTransactionBuilder).getDeadline().timestamp), + isEmbedded ? Deadline.create() : Deadline.createFromDTO((builder as SecretProofTransactionBuilder).getDeadline().timestamp), builder.getHashAlgorithm().valueOf(), Convert.uint8ToHex(builder.getSecret().hash256), UnresolvedMapping.toUnresolvedAddress(Convert.uint8ToHex(builder.getRecipientAddress().unresolvedAddress)), @@ -128,8 +130,7 @@ export class SecretProofTransaction extends Transaction { networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as SecretProofTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** @@ -188,7 +189,7 @@ export class SecretProofTransaction extends Transaction { new AmountDto(this.maxFee.toDTO()), new TimestampDto(this.deadline.toDTO()), new Hash256Dto(this.getSecretByte()), - this.hashType.valueOf(), + this.hashAlgorithm.valueOf(), new UnresolvedAddressDto(UnresolvedMapping.toUnresolvedAddressBytes(this.recipientAddress, this.networkType)), this.getProofByte(), ); @@ -206,7 +207,7 @@ export class SecretProofTransaction extends Transaction { this.networkType.valueOf(), TransactionType.SECRET_PROOF.valueOf(), new Hash256Dto(this.getSecretByte()), - this.hashType.valueOf(), + this.hashAlgorithm.valueOf(), new UnresolvedAddressDto(UnresolvedMapping.toUnresolvedAddressBytes(this.recipientAddress, this.networkType)), this.getProofByte(), ); @@ -218,10 +219,15 @@ export class SecretProofTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {SecretProofTransaction} */ - resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): SecretProofTransaction { + resolveAliases(statement: Statement, aggregateTransactionIndex = 0): SecretProofTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); return DtoMapping.assign(this, { - recipientAddress: statement.resolveAddress(this.recipientAddress, - transactionInfo.height.toString(), transactionInfo.index, aggregateTransactionIndex)}); + recipientAddress: statement.resolveAddress( + this.recipientAddress, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + }); } } diff --git a/src/model/transaction/SignedTransaction.ts b/src/model/transaction/SignedTransaction.ts index 8644b47fed..99ff871ab6 100644 --- a/src/model/transaction/SignedTransaction.ts +++ b/src/model/transaction/SignedTransaction.ts @@ -16,7 +16,7 @@ import { Address } from '../account/Address'; import { PublicAccount } from '../account/PublicAccount'; -import {NetworkType} from '../network/NetworkType'; +import { NetworkType } from '../network/NetworkType'; import { TransactionType } from './TransactionType'; /** @@ -30,26 +30,28 @@ export class SignedTransaction { * @param type * @param networkType */ - constructor(/** - * Transaction serialized data - */ - public readonly payload: string, - /** - * Transaction hash - */ - public readonly hash: string, - /** - * Transaction signerPublicKey - */ - public readonly signerPublicKey: string, - /** - * Transaction type - */ - public readonly type: TransactionType, - /** - * Signer network type - */ - public readonly networkType: NetworkType) { + constructor( + /** + * Transaction serialized data + */ + public readonly payload: string, + /** + * Transaction hash + */ + public readonly hash: string, + /** + * Transaction signerPublicKey + */ + public readonly signerPublicKey: string, + /** + * Transaction type + */ + public readonly type: TransactionType, + /** + * Signer network type + */ + public readonly networkType: NetworkType, + ) { if (hash.length !== 64) { throw new Error('hash must be 64 characters long'); } @@ -58,7 +60,7 @@ export class SignedTransaction { /** * Create DTO object */ - toDTO() { + toDTO(): any { return { payload: this.payload, hash: this.hash, diff --git a/src/model/transaction/SyncAnnounce.ts b/src/model/transaction/SyncAnnounce.ts index 5efe2fcfda..17f1b5ffa1 100644 --- a/src/model/transaction/SyncAnnounce.ts +++ b/src/model/transaction/SyncAnnounce.ts @@ -33,6 +33,6 @@ export class SyncAnnounce { /** * Transaction address */ - public readonly address: string) { - } + public readonly address: string, + ) {} } diff --git a/src/model/transaction/Transaction.ts b/src/model/transaction/Transaction.ts index d6595853a6..0aa5b8e1de 100644 --- a/src/model/transaction/Transaction.ts +++ b/src/model/transaction/Transaction.ts @@ -35,7 +35,6 @@ import { TransactionType } from './TransactionType'; * An abstract transaction class that serves as the base class of all NEM transactions. */ export abstract class Transaction { - /** * Transaction header size * @@ -77,40 +76,41 @@ export abstract class Transaction { * @param signer * @param transactionInfo */ - constructor(/** - * The transaction type. - */ - public readonly type: number, - /** - * The network type. - */ - public readonly networkType: NetworkType, - /** - * The transaction version number. - */ - public readonly version: number, - /** - * The deadline to include the transaction. - */ - public readonly deadline: Deadline, - /** - * A sender of a transaction must specify during the transaction definition a max_fee, - * meaning the maximum fee the account allows to spend for this transaction. - */ - public readonly maxFee: UInt64, - /** - * The transaction signature (missing if part of an aggregate transaction). - */ - public readonly signature?: string, - /** - * The account of the transaction creator. - */ - public readonly signer?: PublicAccount, - /** - * Transactions meta data object contains additional information about the transaction. - */ - public readonly transactionInfo?: TransactionInfo | AggregateTransactionInfo) { - } + constructor( + /** + * The transaction type. + */ + public readonly type: number, + /** + * The network type. + */ + public readonly networkType: NetworkType, + /** + * The transaction version number. + */ + public readonly version: number, + /** + * The deadline to include the transaction. + */ + public readonly deadline: Deadline, + /** + * A sender of a transaction must specify during the transaction definition a max_fee, + * meaning the maximum fee the account allows to spend for this transaction. + */ + public readonly maxFee: UInt64, + /** + * The transaction signature (missing if part of an aggregate transaction). + */ + public readonly signature?: string, + /** + * The account of the transaction creator. + */ + public readonly signer?: PublicAccount, + /** + * Transactions meta data object contains additional information about the transaction. + */ + public readonly transactionInfo?: TransactionInfo | AggregateTransactionInfo, + ) {} /** * Generate transaction hash hex @@ -120,11 +120,9 @@ export abstract class Transaction { * @see https://github.com/nemtech/catapult-server/blob/master/sdk/src/extensions/TransactionExtensions.cpp#L46 * @param {string} transactionPayload HexString Payload * @param {Array} generationHashBuffer Network generation hash byte - * @param {NetworkType} networkType Catapult network identifier * @returns {string} Returns Transaction Payload hash */ - public static createTransactionHash(transactionPayload: string, generationHashBuffer: number[], networkType: NetworkType): string { - + public static createTransactionHash(transactionPayload: string, generationHashBuffer: number[]): string { // prepare const entityHash: Uint8Array = new Uint8Array(32); const transactionBytes: Uint8Array = Convert.hexToUint8(transactionPayload); @@ -133,10 +131,9 @@ export abstract class Transaction { const typeIdx: number = Transaction.Type_Index; const typeBytes: Uint8Array = transactionBytes.slice(typeIdx, typeIdx + 2).reverse(); // REVERSED const entityType: TransactionType = parseInt(Convert.uint8ToHex(typeBytes), 16); - const isAggregateTransaction = [ - TransactionType.AGGREGATE_BONDED, - TransactionType.AGGREGATE_COMPLETE, - ].find((type: TransactionType) => entityType === type) !== undefined; + const isAggregateTransaction = + [TransactionType.AGGREGATE_BONDED, TransactionType.AGGREGATE_COMPLETE].find((type: TransactionType) => entityType === type) !== + undefined; // 1) add full signature const signature: Uint8Array = transactionBytes.slice(8, 8 + 64); @@ -162,10 +159,7 @@ export abstract class Transaction { // 5) concatenate binary hash parts // layout: `signature_R || signerPublicKey || generationHash || EntityDataBuffer` const entityHashBytes: Uint8Array = new Uint8Array( - signature.length - + publicKey.length - + generationHash.length - + transactionBody.length, + signature.length + publicKey.length + generationHash.length + transactionBody.length, ); entityHashBytes.set(signature, 0); entityHashBytes.set(publicKey, pubKeyIdx); @@ -197,12 +191,17 @@ export abstract class Transaction { abstract resolveAliases(statement?: Statement, aggregateTransactionIndex?: number): Transaction; /** - * Set transaction maxFee using fee multiplier + * Set transaction maxFee using fee multiplier for **ONLY NONE AGGREGATE TRANSACTIONS** * @param feeMultiplier The fee multiplier * @returns {TransferTransaction} */ public setMaxFee(feeMultiplier: number): Transaction { - return DtoMapping.assign(this, {maxFee: UInt64.fromUint(this.size * feeMultiplier)}); + if (this.type === TransactionType.AGGREGATE_BONDED || this.type === TransactionType.AGGREGATE_COMPLETE) { + throw new Error('setMaxFee can only be used for none aggregate transactions.'); + } + return DtoMapping.assign(this, { + maxFee: UInt64.fromUint(this.size * feeMultiplier), + }); } /** @@ -223,23 +222,24 @@ export abstract class Transaction { .concat(signature) .concat(Array.from(keyPairEncoded.publicKey)) .concat(Array.from(new Uint8Array(4))) - .concat(byteBuffer - .splice(64 + 32 + 4, byteBuffer.length)); + .concat(byteBuffer.splice(64 + 32 + 4, byteBuffer.length)); const payload = Convert.uint8ToHex(signedTransactionBuffer); return new SignedTransaction( payload, - Transaction.createTransactionHash(payload, generationHashBytes, account.networkType), + Transaction.createTransactionHash(payload, generationHashBytes), account.publicKey, this.type, - this.networkType); + this.networkType, + ); } /** * Generate signing bytes * @param payloadBytes Payload buffer * @param generationHashBytes GenerationHash buffer + * @return {number[]} */ - public getSigningBytes(payloadBytes: number[], generationHashBytes: number[]) { + public getSigningBytes(payloadBytes: number[], generationHashBytes: number[]): number[] { const byteBufferWithoutHeader = payloadBytes.slice(4 + 64 + 32 + 8); if (this.type === TransactionType.AGGREGATE_BONDED || this.type === TransactionType.AGGREGATE_COMPLETE) { return generationHashBytes.concat(byteBufferWithoutHeader.slice(0, 52)); @@ -258,12 +258,14 @@ export abstract class Transaction { resultBytes.splice(0, 4 + 64 + 32); resultBytes = Array.from(signerPublicKey).concat(resultBytes); resultBytes.splice(32 + 2 + 2, 16); - return Array.from((new Uint8Array([ - (resultBytes.length + 4 & 0x000000ff), - (resultBytes.length + 4 & 0x0000ff00) >> 8, - (resultBytes.length + 4 & 0x00ff0000) >> 16, - (resultBytes.length + 4 & 0xff000000) >> 24, - ]))).concat(resultBytes); + return Array.from( + new Uint8Array([ + (resultBytes.length + 4) & 0x000000ff, + ((resultBytes.length + 4) & 0x0000ff00) >> 8, + ((resultBytes.length + 4) & 0x00ff0000) >> 16, + ((resultBytes.length + 4) & 0xff000000) >> 24, + ]), + ).concat(resultBytes); } /** @@ -277,7 +279,7 @@ export abstract class Transaction { if (this.type === TransactionType.AGGREGATE_BONDED || this.type === TransactionType.AGGREGATE_COMPLETE) { throw new Error('Inner transaction cannot be an aggregated transaction.'); } - return DtoMapping.assign(this, {signer}); + return DtoMapping.assign(this, { signer }); } /** @@ -285,10 +287,8 @@ export abstract class Transaction { * * @return transaction with signer serialized to be part of an aggregate transaction */ - public toAggregateTransactionBytes() { - return EmbeddedTransactionHelper.serialize( - this.toEmbeddedTransaction(), - ); + public toAggregateTransactionBytes(): Uint8Array { + return EmbeddedTransactionHelper.serialize(this.toEmbeddedTransaction()); } /** @@ -296,10 +296,13 @@ export abstract class Transaction { * @returns {boolean} */ public isUnconfirmed(): boolean { - return this.transactionInfo != null && this.transactionInfo.height.compact() === 0 - && this.transactionInfo.hash !== undefined - && this.transactionInfo.merkleComponentHash !== undefined - && this.transactionInfo.hash.toUpperCase() === this.transactionInfo.merkleComponentHash.toUpperCase(); + return ( + this.transactionInfo != null && + this.transactionInfo.height.compact() === 0 && + this.transactionInfo.hash !== undefined && + this.transactionInfo.merkleComponentHash !== undefined && + this.transactionInfo.hash.toUpperCase() === this.transactionInfo.merkleComponentHash.toUpperCase() + ); } /** @@ -315,10 +318,13 @@ export abstract class Transaction { * @returns {boolean} */ public hasMissingSignatures(): boolean { - return this.transactionInfo != null && this.transactionInfo.height.compact() === 0 - && (this.transactionInfo.hash !== undefined - && this.transactionInfo.merkleComponentHash !== undefined - && this.transactionInfo.hash.toUpperCase() !== this.transactionInfo.merkleComponentHash.toUpperCase()); + return ( + this.transactionInfo != null && + this.transactionInfo.height.compact() === 0 && + this.transactionInfo.hash !== undefined && + this.transactionInfo.merkleComponentHash !== undefined && + this.transactionInfo.hash.toUpperCase() !== this.transactionInfo.merkleComponentHash.toUpperCase() + ); } /** @@ -351,9 +357,9 @@ export abstract class Transaction { */ public reapplyGiven(deadline: Deadline = Deadline.create()): Transaction { if (this.isUnannounced()) { - return DtoMapping.assign(this, {deadline}); + return DtoMapping.assign(this, { deadline }); } - throw new Error('an Announced transaction can\'t be modified'); + throw new Error("an Announced transaction can't be modified"); } /** @@ -362,16 +368,17 @@ export abstract class Transaction { * @memberof Transaction */ public get size(): number { - const byteSize = 4 // size - + 4 // verifiableEntityHeader_Reserved1 - + 64 // signature - + 32 // signerPublicKey - + 4 // entityBody_Reserved1 - + 1 // version - + 1 // networkType - + 2 // type - + 8 // maxFee - + 8; // deadline + const byteSize = + 4 + // size + 4 + // verifiableEntityHeader_Reserved1 + 64 + // signature + 32 + // signerPublicKey + 4 + // entityBody_Reserved1 + 1 + // version + 1 + // networkType + 2 + // type + 8 + // maxFee + 8; // deadline return byteSize; } @@ -390,7 +397,7 @@ export abstract class Transaction { * @returns {Object} * @memberof Transaction */ - public toJSON() { + public toJSON(): any { const commonTransactionObject = { type: this.type, network: this.networkType, @@ -401,11 +408,15 @@ export abstract class Transaction { }; if (this.signer) { - Object.assign(commonTransactionObject, {signerPublicKey: this.signer.publicKey}); + Object.assign(commonTransactionObject, { + signerPublicKey: this.signer.publicKey, + }); } const childClassObject = SerializeTransactionToJSON(this); - return {transaction: Object.assign(commonTransactionObject, childClassObject)}; + return { + transaction: Object.assign(commonTransactionObject, childClassObject), + }; } /** @@ -414,9 +425,7 @@ export abstract class Transaction { * @returns TransactionInfo */ protected checkTransactionHeightAndIndex(): TransactionInfo { - if (this.transactionInfo === undefined || - this.transactionInfo.height === undefined || - this.transactionInfo.index === undefined) { + if (this.transactionInfo === undefined || this.transactionInfo.height === undefined || this.transactionInfo.index === undefined) { throw new Error('Transaction height or index undefined'); } return this.transactionInfo; diff --git a/src/model/transaction/TransactionAnnounceResponse.ts b/src/model/transaction/TransactionAnnounceResponse.ts index 26697e3428..6a6c775bb3 100644 --- a/src/model/transaction/TransactionAnnounceResponse.ts +++ b/src/model/transaction/TransactionAnnounceResponse.ts @@ -18,16 +18,14 @@ * Transaction response of an announce transaction */ export class TransactionAnnounceResponse { - /** * @internal * @param message */ constructor( - /** - * The success or error message. - */ - public readonly message: string) { - - } + /** + * The success or error message. + */ + public readonly message: string, + ) {} } diff --git a/src/model/transaction/TransactionInfo.ts b/src/model/transaction/TransactionInfo.ts index 367b001b0d..ac5fa23ca9 100644 --- a/src/model/transaction/TransactionInfo.ts +++ b/src/model/transaction/TransactionInfo.ts @@ -14,13 +14,12 @@ * limitations under the License. */ -import {UInt64} from '../UInt64'; +import { UInt64 } from '../UInt64'; /** * Transaction information model included in all transactions */ export class TransactionInfo { - /** * @param height * @param index @@ -29,24 +28,25 @@ export class TransactionInfo { * @param merkleComponentHash */ constructor( - /** - * The block height in which the transaction was included. - */ - public readonly height: UInt64, - /** - * The index representing either transaction index/position within block or within an aggregate transaction. - */ - public readonly index: number, - /** - * The transaction db id. - */ - public readonly id: string, - /** - * The transaction hash. - */ - public readonly hash?: string, - /** - * The transaction merkle hash. - */ - public readonly merkleComponentHash?: string) {} + /** + * The block height in which the transaction was included. + */ + public readonly height: UInt64, + /** + * The index representing either transaction index/position within block or within an aggregate transaction. + */ + public readonly index: number, + /** + * The transaction db id. + */ + public readonly id: string, + /** + * The transaction hash. + */ + public readonly hash?: string, + /** + * The transaction merkle hash. + */ + public readonly merkleComponentHash?: string, + ) {} } diff --git a/src/model/transaction/TransactionStatus.ts b/src/model/transaction/TransactionStatus.ts index a286c0ec51..a9bdc63af8 100644 --- a/src/model/transaction/TransactionStatus.ts +++ b/src/model/transaction/TransactionStatus.ts @@ -15,14 +15,13 @@ */ import { TransactionStateTypeEnum, TransactionStatusTypeEnum } from 'symbol-openapi-typescript-node-client'; -import {UInt64} from '../UInt64'; -import {Deadline} from './Deadline'; +import { UInt64 } from '../UInt64'; +import { Deadline } from './Deadline'; /** * Transaction status contains basic of a transaction announced to the blockchain. */ export class TransactionStatus { - /** * @param group * @param code @@ -31,24 +30,25 @@ export class TransactionStatus { * @param height */ constructor( - /** - * The transaction status group "failed", "unconfirmed", "confirmed", etc... - */ - public readonly group: TransactionStateTypeEnum, - /** - * The transaction hash. - */ - public readonly hash: string, - /** - * The transaction deadline. - */ - public readonly deadline: Deadline, - /** - * The transaction status code being the error name in case of failure and success otherwise. - */ - public readonly code?: TransactionStatusTypeEnum, - /** - * The height of the block at which it was confirmed or rejected. - */ - public readonly height?: UInt64) {} + /** + * The transaction status group "failed", "unconfirmed", "confirmed", etc... + */ + public readonly group: TransactionStateTypeEnum, + /** + * The transaction hash. + */ + public readonly hash: string, + /** + * The transaction deadline. + */ + public readonly deadline: Deadline, + /** + * The transaction status code being the error name in case of failure and success otherwise. + */ + public readonly code?: TransactionStatusTypeEnum, + /** + * The height of the block at which it was confirmed or rejected. + */ + public readonly height?: UInt64, + ) {} } diff --git a/src/model/transaction/TransactionStatusError.ts b/src/model/transaction/TransactionStatusError.ts index 01cb7d9c97..ab0a9ae4a7 100644 --- a/src/model/transaction/TransactionStatusError.ts +++ b/src/model/transaction/TransactionStatusError.ts @@ -14,14 +14,13 @@ * limitations under the License. */ -import {Address} from '../account/Address'; -import {Deadline} from './Deadline'; +import { Address } from '../account/Address'; +import { Deadline } from './Deadline'; /** * Transaction status error model returned by listeners */ export class TransactionStatusError { - /** * @internal * @param address @@ -30,23 +29,22 @@ export class TransactionStatusError { * @param deadline */ constructor( - /** - * The address of the account that signed the invalid transaction. - * It's the address listened when calling Lister.status. - */ - public readonly address: Address, - /** - * The transaction hash. - */ - public readonly hash: string, - /** - * The error code. - */ - public readonly code: string, - /** - * The transaction deadline. - */ - public readonly deadline: Deadline) { - - } + /** + * The address of the account that signed the invalid transaction. + * It's the address listened when calling Lister.status. + */ + public readonly address: Address, + /** + * The transaction hash. + */ + public readonly hash: string, + /** + * The error code. + */ + public readonly code: string, + /** + * The transaction deadline. + */ + public readonly deadline: Deadline, + ) {} } diff --git a/src/model/transaction/TransactionType.ts b/src/model/transaction/TransactionType.ts index b80dc77dae..82e9d317b1 100644 --- a/src/model/transaction/TransactionType.ts +++ b/src/model/transaction/TransactionType.ts @@ -18,7 +18,6 @@ * Enum containing transaction type constants. */ export enum TransactionType { - /** Reserved entity type. */ RESERVED = 0, /** @@ -31,31 +30,31 @@ export enum TransactionType { * Register namespace transaction type. * @type {number} */ - NAMESPACE_REGISTRATION = 0x414E, + NAMESPACE_REGISTRATION = 0x414e, /** * Address alias transaction type * @type {number} */ - ADDRESS_ALIAS = 0x424E, + ADDRESS_ALIAS = 0x424e, /** * Mosaic alias transaction type * @type {number} */ - MOSAIC_ALIAS = 0x434E, + MOSAIC_ALIAS = 0x434e, /** * Mosaic definition transaction type. * @type {number} */ - MOSAIC_DEFINITION = 0x414D, + MOSAIC_DEFINITION = 0x414d, /** * Mosaic supply change transaction. * @type {number} */ - MOSAIC_SUPPLY_CHANGE = 0x424D, + MOSAIC_SUPPLY_CHANGE = 0x424d, /** * Modify multisig account transaction type. @@ -114,7 +113,7 @@ export enum TransactionType { * Link account transaction type * @type {number} */ - ACCOUNT_LINK = 0x414C, + ACCOUNT_LINK = 0x414c, /** * Mosaic address restriction type diff --git a/src/model/transaction/TransactionVersion.ts b/src/model/transaction/TransactionVersion.ts index ceaf282902..7b83023f72 100644 --- a/src/model/transaction/TransactionVersion.ts +++ b/src/model/transaction/TransactionVersion.ts @@ -26,7 +26,6 @@ * @see https://github.com/nemtech/catapult-server/blob/master/plugins/txes/transfer/src/model/TransferTransaction.h#L37 */ export class TransactionVersion { - /** * Transfer Transaction transaction version. * @type {number} diff --git a/src/model/transaction/TransferTransaction.ts b/src/model/transaction/TransferTransaction.ts index 26464ef947..05b0cd2108 100644 --- a/src/model/transaction/TransferTransaction.ts +++ b/src/model/transaction/TransferTransaction.ts @@ -66,19 +66,15 @@ export class TransferTransaction extends Transaction { * @param maxFee - (Optional) Max fee defined by the sender * @returns {TransferTransaction} */ - public static create(deadline: Deadline, - recipientAddress: Address | NamespaceId, - mosaics: Mosaic[], - message: Message, - networkType: NetworkType, - maxFee: UInt64 = new UInt64([0, 0])): TransferTransaction { - return new TransferTransaction(networkType, - TransactionVersion.TRANSFER, - deadline, - maxFee, - recipientAddress, - mosaics, - message); + public static create( + deadline: Deadline, + recipientAddress: Address | NamespaceId, + mosaics: Mosaic[], + message: Message, + networkType: NetworkType, + maxFee: UInt64 = new UInt64([0, 0]), + ): TransferTransaction { + return new TransferTransaction(networkType, TransactionVersion.TRANSFER, deadline, maxFee, recipientAddress, mosaics, message); } /** @@ -93,25 +89,27 @@ export class TransferTransaction extends Transaction { * @param signer * @param transactionInfo */ - constructor(networkType: NetworkType, - version: number, - deadline: Deadline, - maxFee: UInt64, - /** - * The address of the recipient address. - */ - public readonly recipientAddress: Address | NamespaceId, - /** - * The array of Mosaic objects. - */ - public readonly mosaics: Mosaic[], - /** - * The transaction message of 2048 characters. - */ - public readonly message: Message, - signature?: string, - signer?: PublicAccount, - transactionInfo?: TransactionInfo) { + constructor( + networkType: NetworkType, + version: number, + deadline: Deadline, + maxFee: UInt64, + /** + * The address of the recipient address. + */ + public readonly recipientAddress: Address | NamespaceId, + /** + * The array of Mosaic objects. + */ + public readonly mosaics: Mosaic[], + /** + * The transaction message of 2048 characters. + */ + public readonly message: Message, + signature?: string, + signer?: PublicAccount, + transactionInfo?: TransactionInfo, + ) { super(TransactionType.TRANSFER, networkType, version, deadline, maxFee, signature, signer, transactionInfo); this.validate(); } @@ -122,39 +120,35 @@ export class TransferTransaction extends Transaction { * @param {Boolean} isEmbedded Is embedded transaction (Default: false) * @returns {Transaction | InnerTransaction} */ - public static createFromPayload(payload: string, - isEmbedded: boolean = false): Transaction | InnerTransaction { - const builder = isEmbedded ? EmbeddedTransferTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) : - TransferTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); + public static createFromPayload(payload: string, isEmbedded = false): Transaction | InnerTransaction { + const builder = isEmbedded + ? EmbeddedTransferTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)) + : TransferTransactionBuilder.loadFromBinary(Convert.hexToUint8(payload)); const messageType = builder.getMessage()[0]; const messageHex = Convert.uint8ToHex(builder.getMessage()).substring(2); const signerPublicKey = Convert.uint8ToHex(builder.getSignerPublicKey().key); const networkType = builder.getNetwork().valueOf(); const transaction = TransferTransaction.create( - isEmbedded ? Deadline.create() : Deadline.createFromDTO( - (builder as TransferTransactionBuilder).getDeadline().timestamp), + isEmbedded ? Deadline.create() : Deadline.createFromDTO((builder as TransferTransactionBuilder).getDeadline().timestamp), UnresolvedMapping.toUnresolvedAddress(Convert.uint8ToHex(builder.getRecipientAddress().unresolvedAddress)), builder.getMosaics().map((mosaic) => { const id = new UInt64(mosaic.mosaicId.unresolvedMosaicId).toHex(); - return new Mosaic( - UnresolvedMapping.toUnresolvedMosaic(id), - new UInt64(mosaic.amount.amount)); + return new Mosaic(UnresolvedMapping.toUnresolvedMosaic(id), new UInt64(mosaic.amount.amount)); }), - messageType === MessageType.PlainMessage ? - PlainMessage.createFromPayload(messageHex) : - EncryptedMessage.createFromPayload(messageHex), + messageType === MessageType.PlainMessage + ? PlainMessage.createFromPayload(messageHex) + : EncryptedMessage.createFromPayload(messageHex), networkType, isEmbedded ? new UInt64([0, 0]) : new UInt64((builder as TransferTransactionBuilder).fee.amount), ); - return isEmbedded ? - transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; + return isEmbedded ? transaction.toAggregate(PublicAccount.createFromPublicKey(signerPublicKey, networkType)) : transaction; } /** * Validate Transfer transaction creation with provided message * @internal */ - protected validate() { + protected validate(): void { if (this.message.type === MessageType.PersistentHarvestingDelegationMessage) { if (this.mosaics.length > 0) { throw new Error('PersistentDelegationRequestTransaction should be created without Mosaic'); @@ -170,7 +164,6 @@ export class TransferTransaction extends Transaction { * @returns {string} */ public recipientToString(): string { - if (this.recipientAddress instanceof NamespaceId) { // namespaceId recipient, return hexadecimal notation return (this.recipientAddress as NamespaceId).toHex(); @@ -199,12 +192,15 @@ export class TransferTransaction extends Transaction { * @returns {Uint8Array} */ public getMessageBuffer(): Uint8Array { - const messgeHex = this.message.type === MessageType.PersistentHarvestingDelegationMessage ? - this.message.payload : Convert.utf8ToHex(this.message.payload); + const messgeHex = + this.message.type === MessageType.PersistentHarvestingDelegationMessage + ? this.message.payload + : Convert.utf8ToHex(this.message.payload); const payloadBuffer = Convert.hexToUint8(messgeHex); const typeBuffer = GeneratorUtils.uintToBuffer(this.message.type, 1); - return this.message.type === MessageType.PersistentHarvestingDelegationMessage ? - payloadBuffer : GeneratorUtils.concatTypedArrays(typeBuffer, payloadBuffer); + return this.message.type === MessageType.PersistentHarvestingDelegationMessage + ? payloadBuffer + : GeneratorUtils.concatTypedArrays(typeBuffer, payloadBuffer); } /** @@ -228,8 +224,15 @@ export class TransferTransaction extends Transaction { // mosaicId / namespaceId are written on 8 bytes + 8 bytes for the amount. const byteMosaics = (8 + 8) * this.mosaics.length; - return byteSize + byteMosaicsCount + byteRecipientAddress + - + byteTransferTransactionBody_Reserved1 + byteMessageSize + bytePayload + byteMosaics; + return ( + byteSize + + byteMosaicsCount + + byteRecipientAddress + + +byteTransferTransactionBody_Reserved1 + + byteMessageSize + + bytePayload + + byteMosaics + ); } /** @@ -250,8 +253,7 @@ export class TransferTransaction extends Transaction { new TimestampDto(this.deadline.toDTO()), new UnresolvedAddressDto(UnresolvedMapping.toUnresolvedAddressBytes(this.recipientAddress, this.networkType)), this.sortMosaics().map((mosaic) => { - return new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(mosaic.id.id.toDTO()), - new AmountDto(mosaic.amount.toDTO())); + return new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(mosaic.id.id.toDTO()), new AmountDto(mosaic.amount.toDTO())); }), this.getMessageBuffer(), ); @@ -270,8 +272,7 @@ export class TransferTransaction extends Transaction { TransactionType.TRANSFER.valueOf(), new UnresolvedAddressDto(UnresolvedMapping.toUnresolvedAddressBytes(this.recipientAddress, this.networkType)), this.sortMosaics().map((mosaic) => { - return new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(mosaic.id.id.toDTO()), - new AmountDto(mosaic.amount.toDTO())); + return new UnresolvedMosaicBuilder(new UnresolvedMosaicIdDto(mosaic.id.id.toDTO()), new AmountDto(mosaic.amount.toDTO())); }), this.getMessageBuffer(), ); @@ -283,11 +284,18 @@ export class TransferTransaction extends Transaction { * @param aggregateTransactionIndex Transaction index for aggregated transaction * @returns {TransferTransaction} */ - public resolveAliases(statement: Statement, aggregateTransactionIndex: number = 0): TransferTransaction { + public resolveAliases(statement: Statement, aggregateTransactionIndex = 0): TransferTransaction { const transactionInfo = this.checkTransactionHeightAndIndex(); - return DtoMapping.assign(this, {recipientAddress: statement.resolveAddress(this.recipientAddress, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex), - mosaics: this.mosaics.map((mosaic) => statement.resolveMosaic(mosaic, transactionInfo.height.toString(), - transactionInfo.index, aggregateTransactionIndex))}); + return DtoMapping.assign(this, { + recipientAddress: statement.resolveAddress( + this.recipientAddress, + transactionInfo.height.toString(), + transactionInfo.index, + aggregateTransactionIndex, + ), + mosaics: this.mosaics.map((mosaic) => + statement.resolveMosaic(mosaic, transactionInfo.height.toString(), transactionInfo.index, aggregateTransactionIndex), + ), + }); } } diff --git a/src/model/wallet/EncryptedPrivateKey.ts b/src/model/wallet/EncryptedPrivateKey.ts deleted file mode 100644 index 42fb702dad..0000000000 --- a/src/model/wallet/EncryptedPrivateKey.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2018 NEM - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import {Crypto} from '../../core/crypto'; -import {Password} from './Password'; -import { WalletAlgorithm } from './WalletAlgorithm'; - -/** - * EncryptedPrivateKey model - */ -export class EncryptedPrivateKey { - /** - * @param encryptedKey - * @param iv - */ - constructor( - /** - * Encrypted private key data - */ - public readonly encryptedKey: string, - /** - * Initialization vector used in the decrypt process - */ - public readonly iv: string) { - - } - - /** - * Decrypt an encrypted private key - * @param password - */ - public decrypt(password: Password): string { - const common = { - password: password.value, - privateKey: '', - }; - const wallet = { - encrypted: this.encryptedKey, - iv: this.iv, - }; - Crypto.passwordToPrivateKey(common, wallet, WalletAlgorithm.Pass_bip32); - return common.privateKey; - } -} diff --git a/src/model/wallet/ISimpleWalletDTO.ts b/src/model/wallet/ISimpleWalletDTO.ts index a4aec8d8e9..3c8bfa75fe 100644 --- a/src/model/wallet/ISimpleWalletDTO.ts +++ b/src/model/wallet/ISimpleWalletDTO.ts @@ -1,5 +1,5 @@ /* - * Copyright 2019 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,10 @@ export interface ISimpleWalletDTO { name: string; network: number; address: { - address: string - networkType: number, + address: string; + networkType: number; }; creationDate: string; schema: string; - encryptedPrivateKey: { - encryptedKey: string - iv: string, - }; + encryptedPrivateKey: string; } diff --git a/src/model/wallet/Password.ts b/src/model/wallet/Password.ts index d2f13abb6a..6ab749c59c 100644 --- a/src/model/wallet/Password.ts +++ b/src/model/wallet/Password.ts @@ -28,8 +28,9 @@ export class Password { * @param password */ constructor(password: string) { - if (password.length < 8) { throw new Error('Password must be at least 8 characters'); } + if (password.length < 8) { + throw new Error('Password must be at least 8 characters'); + } this.value = password; } - } diff --git a/src/model/wallet/SimpleWallet.ts b/src/model/wallet/SimpleWallet.ts index f5673ccf3c..0ab29ad7ba 100644 --- a/src/model/wallet/SimpleWallet.ts +++ b/src/model/wallet/SimpleWallet.ts @@ -1,5 +1,5 @@ /* - * Copyright 2018 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,38 +14,24 @@ * limitations under the License. */ -import {LocalDateTime} from 'js-joda'; -import {Crypto, KeyPair, SHA3Hasher} from '../../core/crypto'; -import {Convert as convert} from '../../core/format'; -import {Account} from '../account/Account'; -import {Address} from '../account/Address'; -import {NetworkType} from '../network/NetworkType'; -import {EncryptedPrivateKey} from './EncryptedPrivateKey'; -import {ISimpleWalletDTO} from './ISimpleWalletDTO'; -import {Password} from './Password'; -import {Wallet} from './Wallet'; +import { Crypto, KeyPair } from '../../core/crypto'; +import { Convert as convert } from '../../core/format'; +import { Account } from '../account/Account'; +import { Address } from '../account/Address'; +import { NetworkType } from '../network/NetworkType'; +import { ISimpleWalletDTO } from './ISimpleWalletDTO'; +import { Password } from './Password'; +import { Wallet } from './Wallet'; -/** - * Simple wallet model generates a private key from a PRNG - */ export class SimpleWallet extends Wallet { - /** - * @param name - * @param network - * @param address - * @param creationDate - * @param encryptedPrivateKey + *Creates an instance of SimpleWallet. + * @param {string} name + * @param {Address} address + * @param {string} encryptedPrivateKey */ - constructor(name: string, - network: NetworkType, - address: Address, - creationDate: LocalDateTime, - /** - * The encrypted private key and information to decrypt it - */ - public readonly encryptedPrivateKey: EncryptedPrivateKey) { - super(name, network, address, creationDate, 'simple_v1'); + constructor(name: string, address: Address, public readonly encryptedPrivateKey: string) { + super(name, address, 'simple_v2'); } /** @@ -55,9 +41,7 @@ export class SimpleWallet extends Wallet { * @param network - Network id * @returns {SimpleWallet} */ - public static create(name: string, - password: Password, - network: NetworkType): SimpleWallet { + public static create(name: string, password: Password, network: NetworkType): SimpleWallet { // Create random bytes const randomBytesArray = Crypto.randomBytes(32); // Hash random bytes with entropy seed @@ -65,17 +49,15 @@ export class SimpleWallet extends Wallet { const hashKey = convert.uint8ToHex(randomBytesArray); // TODO: derive private key correctly // Create KeyPair from hash key - const keyPair = KeyPair.createKeyPairFromPrivateKeyString(hashKey); + const { publicKey, privateKey } = KeyPair.createKeyPairFromPrivateKeyString(hashKey); // Create address from public key - const address = Address.createFromPublicKey(convert.uint8ToHex(keyPair.publicKey), network); + const address = Address.createFromPublicKey(convert.uint8ToHex(publicKey), network); // Encrypt private key using password - const encrypted = Crypto.encodePrivateKey(hashKey, password.value); + const encryptedPrivateKey = Crypto.encrypt(convert.uint8ToHex(privateKey), password.value); - const encryptedPrivateKey = new EncryptedPrivateKey(encrypted.ciphertext, encrypted.iv); - - return new SimpleWallet(name, network, address, LocalDateTime.now(), encryptedPrivateKey); + return new SimpleWallet(name, address, encryptedPrivateKey); } /** @@ -86,10 +68,7 @@ export class SimpleWallet extends Wallet { * @param network - Network id * @returns {SimpleWallet} */ - static createFromPrivateKey(name: string, - password: Password, - privateKey: string, - network: NetworkType): SimpleWallet { + static createFromPrivateKey(name: string, password: Password, privateKey: string, network: NetworkType): SimpleWallet { // Create KeyPair from hash key const keyPair = KeyPair.createKeyPairFromPrivateKeyString(privateKey); @@ -97,11 +76,9 @@ export class SimpleWallet extends Wallet { const address = Address.createFromPublicKey(convert.uint8ToHex(keyPair.publicKey), network); // Encrypt private key using password - const encrypted = Crypto.encodePrivateKey(privateKey, password.value); - - const encryptedPrivateKey = new EncryptedPrivateKey(encrypted.ciphertext, encrypted.iv); + const encryptedPrivateKey = Crypto.encrypt(privateKey, password.value); - return new SimpleWallet(name, network, address, LocalDateTime.now(), encryptedPrivateKey); + return new SimpleWallet(name, address, encryptedPrivateKey); } /** @@ -112,13 +89,8 @@ export class SimpleWallet extends Wallet { static createFromDTO(simpleWalletDTO: ISimpleWalletDTO): SimpleWallet { return new SimpleWallet( simpleWalletDTO.name, - simpleWalletDTO.network, Address.createFromRawAddress(simpleWalletDTO.address.address), - LocalDateTime.now(), - new EncryptedPrivateKey( - simpleWalletDTO.encryptedPrivateKey.encryptedKey, - simpleWalletDTO.encryptedPrivateKey.iv, - ), + simpleWalletDTO.encryptedPrivateKey, ); } @@ -127,7 +99,7 @@ export class SimpleWallet extends Wallet { * @returns {ISimpleWalletDTO} */ public toDTO(): ISimpleWalletDTO { - return JSON.parse(JSON.stringify(this)) + return JSON.parse(JSON.stringify(this)); } /** @@ -136,7 +108,7 @@ export class SimpleWallet extends Wallet { * @returns {Account} */ public open(password: Password): Account { - return Account.createFromPrivateKey(this.encryptedPrivateKey.decrypt(password), this.network); + const privateKey = Crypto.decrypt(this.encryptedPrivateKey, password.value); + return Account.createFromPrivateKey(privateKey, this.networkType); } - } diff --git a/src/model/wallet/Wallet.ts b/src/model/wallet/Wallet.ts index e7ae15ae3f..ff6156bceb 100644 --- a/src/model/wallet/Wallet.ts +++ b/src/model/wallet/Wallet.ts @@ -1,5 +1,5 @@ /* - * Copyright 2018 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,11 +14,10 @@ * limitations under the License. */ -import {LocalDateTime} from 'js-joda'; -import {Account} from '../account/Account'; -import {Address} from '../account/Address'; -import {NetworkType} from '../network/NetworkType'; -import {Password} from './Password'; +import { Account } from '../account/Account'; +import { Address } from '../account/Address'; +import { NetworkType } from '../network/NetworkType'; +import { Password } from './Password'; /** * Wallet base model @@ -33,28 +32,19 @@ export abstract class Wallet { * @param schema */ constructor( - /** - * The wallet's name - */ - public readonly name: string, - /** - * The wallet's network - */ - public readonly network: NetworkType, - /** - * The wallet's address - */ - public readonly address: Address, - /** - * The wallet's creation date - */ - public readonly creationDate: LocalDateTime, - /** - * Wallet schema number - */ - public readonly schema: string) { - - } + /** + * The wallet's name + */ + public readonly name: string, + /** + * The wallet's address + */ + public readonly address: Address, + /** + * Wallet schema number + */ + public readonly schema: string, + ) {} /** * Abstract open wallet method returning an account from current wallet. @@ -62,4 +52,12 @@ export abstract class Wallet { * @returns {Account} */ public abstract open(password: Password): Account; + + /** + * The wallet's network type + * @type {NetworkType} + */ + public get networkType(): NetworkType { + return this.address.networkType; + } } diff --git a/src/service/AccountService.ts b/src/service/AccountService.ts new file mode 100644 index 0000000000..52b2e025f4 --- /dev/null +++ b/src/service/AccountService.ts @@ -0,0 +1,137 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Observable, of } from 'rxjs'; +import { map, withLatestFrom } from 'rxjs/operators'; +import { RepositoryFactory } from '../infrastructure/RepositoryFactory'; +import { AccountRepository } from '../infrastructure/AccountRepository'; +import { NamespaceRepository } from '../infrastructure/NamespaceRepository'; +import { Address } from '../model/account/Address'; +import { mergeMap } from 'rxjs/operators'; +import { DtoMapping } from '../core/utils/DtoMapping'; +import { IAccountService } from './interfaces/IAccountService'; +import { NamespaceInfoWithName } from '../model/namespace/NamespaceInfoWithName'; +import { ResolvedMosaic } from '../model/mosaic/ResolvedMosaic'; +import { Mosaic } from '../model/mosaic/Mosaic'; +import { MosaicId } from '../model/mosaic/MosaicId'; +import { NamespaceId } from '../model/namespace/NamespaceId'; +import { AccountInfoResolvedMosaic } from '../model/account/AccountInfoResolvedMosaic'; +import { AccountInfo } from '../model/account/AccountInfo'; +import { NamespaceName } from '../model/namespace/NamespaceName'; +/** + * Account Service + */ +export class AccountService implements IAccountService { + private readonly accountRepository: AccountRepository; + + private readonly namespaceRepository: NamespaceRepository; + + /** + * Constructor + * @param repositoryFactory + */ + constructor(public readonly repositoryFactory: RepositoryFactory) { + this.accountRepository = repositoryFactory.createAccountRepository(); + this.namespaceRepository = repositoryFactory.createNamespaceRepository(); + } + + /** + * Get account info with resolved mosaic + * @param addresses Array of addresses + */ + public accountInfoWithResolvedMosaic(addresses: Address[]): Observable { + const accountInfoObservable = this.accountRepository.getAccountsInfo(addresses); + const distinctNames = accountInfoObservable.pipe( + mergeMap((info) => { + const namespaceIds = this.getDistinctNamespaceIdFromAccountInfos(info); + if (namespaceIds.length) { + return this.namespaceRepository.getNamespacesName(namespaceIds); + } + return of([]); + }), + ); + + return accountInfoObservable.pipe( + withLatestFrom(distinctNames), + map(([infos, names]) => { + return infos.map((info) => { + const resolved = this.resolveMosaics(info.mosaics, names); + return DtoMapping.assign(info, { resolvedMosaics: resolved }); + }); + }), + ); + } + + /** + * Get namespace info for account with namespace name + * @param addresses Array of addresses + * @returns {Observable} + */ + public accountNamespacesWithName(addresses: Address[]): Observable { + return this.namespaceRepository.getNamespacesFromAccounts(addresses).pipe( + mergeMap((infos) => { + const namespaceIds = infos.map((i) => i.id); + return this.namespaceRepository.getNamespacesName(namespaceIds).pipe( + map((resolved) => { + return infos.map((info) => { + const name = resolved.find((r) => r.namespaceId.equals(info.id)); + return DtoMapping.assign(info, { namespaceName: name?.name }); + }); + }), + ); + }), + ); + } + + /** + * Resolve mosaics provided namespace names + * @param mosaics unresolved mosaics + * @return {ResolvedMosaic[]} + */ + private resolveMosaics(mosaics: Mosaic[], names: NamespaceName[]): ResolvedMosaic[] { + return mosaics.map((mosaic) => { + if (mosaic.id instanceof MosaicId) { + return mosaic as ResolvedMosaic; + } else { + const name = names.find((f) => f.namespaceId.equals(mosaic.id)); + if (name) { + return DtoMapping.assign(mosaic, { namespaceName: name }); + } else { + return mosaic as ResolvedMosaic; + } + } + }); + } + + /** + * Get distinct list of namespaces ids from list of account infos + * @param accountInfos List of account infos + * @returns {NamespaceId[]} + */ + private getDistinctNamespaceIdFromAccountInfos(accountInfos: AccountInfo[]): NamespaceId[] { + const namespaceIds: NamespaceId[] = []; + accountInfos.forEach((info) => { + info.mosaics.forEach((mosaic) => { + if (mosaic.id instanceof NamespaceId) { + if (!namespaceIds.find((n) => n.equals(mosaic.id))) { + namespaceIds.push(mosaic.id); + } + } + }); + }); + return namespaceIds; + } +} diff --git a/src/service/AggregateTransactionService.ts b/src/service/AggregateTransactionService.ts index 9dd430c4b0..9df2cdc832 100644 --- a/src/service/AggregateTransactionService.ts +++ b/src/service/AggregateTransactionService.ts @@ -24,17 +24,23 @@ import { InnerTransaction } from '../model/transaction/InnerTransaction'; import { MultisigAccountModificationTransaction } from '../model/transaction/MultisigAccountModificationTransaction'; import { SignedTransaction } from '../model/transaction/SignedTransaction'; import { TransactionType } from '../model/transaction/TransactionType'; +import { Address } from '../model/account/Address'; +import { RepositoryFactory } from '../infrastructure/RepositoryFactory'; +import { NetworkRepository } from '../infrastructure/NetworkRepository'; /** * Aggregated Transaction service */ export class AggregateTransactionService { - + private readonly multisigRepository: MultisigRepository; + private readonly networkRepository: NetworkRepository; /** * Constructor * @param multisigRepository */ - constructor(private readonly multisigRepository: MultisigRepository) { + constructor(repositoryFactory: RepositoryFactory) { + this.multisigRepository = repositoryFactory.createMultisigRepository(); + this.networkRepository = repositoryFactory.createNetworkRepository(); } /** @@ -47,28 +53,65 @@ export class AggregateTransactionService { /** * Include both initiator & cosigners */ - const signers = (aggregateTransaction.cosignatures.map((cosigner) => cosigner.signer.publicKey)); + const signers = aggregateTransaction.cosignatures.map((cosigner) => cosigner.signer.publicKey); if (signedTransaction.signerPublicKey) { signers.push(signedTransaction.signerPublicKey); } - return observableFrom(aggregateTransaction.innerTransactions).pipe( - mergeMap((innerTransaction) => this.multisigRepository.getMultisigAccountInfo(innerTransaction.signer!.address) - .pipe( - /** - * For multisig account, we need to get the graph info in case it has multiple levels - */ - mergeMap((_) => _.minApproval !== 0 && _.minRemoval !== 0 ? - this.multisigRepository.getMultisigAccountGraphInfo(_.account.address) - .pipe( - map((graphInfo) => this.validateCosignatories(graphInfo, signers, innerTransaction)), - ) : observableOf(signers.find((s) => s === _.account.publicKey ) !== undefined), + return observableFrom(aggregateTransaction.innerTransactions) + .pipe( + mergeMap((innerTransaction) => + this.multisigRepository.getMultisigAccountInfo(innerTransaction.signer!.address).pipe( + /** + * For multisig account, we need to get the graph info in case it has multiple levels + */ + mergeMap((_) => + _.minApproval !== 0 && _.minRemoval !== 0 + ? this.multisigRepository + .getMultisigAccountGraphInfo(_.account.address) + .pipe(map((graphInfo) => this.validateCosignatories(graphInfo, signers, innerTransaction))) + : observableOf(signers.find((s) => s === _.account.publicKey) !== undefined), ), ), ), - toArray(), - ).pipe( - flatMap((results) => { - return observableOf(results.every((isComplete) => isComplete)); + toArray(), + ) + .pipe( + flatMap((results) => { + return observableOf(results.every((isComplete) => isComplete)); + }), + ); + } + + /** + * Get total multisig account cosigner count + * @param address multisig account address + * @returns {Observable} + */ + public getMaxCosignatures(address: Address): Observable { + return this.multisigRepository.getMultisigAccountGraphInfo(address).pipe( + map((graph) => { + let count = 0; + graph.multisigAccounts.forEach((multisigInfo) => { + multisigInfo.map((multisig) => { + count += multisig.cosignatories.length; + }); + }); + return count; + }), + ); + } + + /** + * Get max cosignatures allowed per aggregate from network properties + * @returns {Observable} + */ + public getNetworkMaxCosignaturesPerAggregate(): Observable { + return this.networkRepository.getNetworkProperties().pipe( + map((properties) => { + if (!properties.plugins.aggregate?.maxCosignaturesPerAggregate) { + throw new Error('Cannot get maxCosignaturesPerAggregate from network properties.'); + } + return parseInt(properties.plugins.aggregate?.maxCosignaturesPerAggregate.replace(`'`, '')); }), ); } @@ -80,9 +123,11 @@ export class AggregateTransactionService { * @param innerTransaction - the inner transaction of the aggregated transaction * @returns {boolean} */ - private validateCosignatories(graphInfo: MultisigAccountGraphInfo, - cosignatories: string[], - innerTransaction: InnerTransaction): boolean { + private validateCosignatories( + graphInfo: MultisigAccountGraphInfo, + cosignatories: string[], + innerTransaction: InnerTransaction, + ): boolean { /** * Validate cosignatories from bottom level to top */ @@ -98,7 +143,7 @@ export class AggregateTransactionService { */ if (innerTransaction.type === TransactionType.MULTISIG_ACCOUNT_MODIFICATION) { if ((innerTransaction as MultisigAccountModificationTransaction).publicKeyDeletions.length) { - isMultisigRemoval = true; + isMultisigRemoval = true; } } @@ -106,20 +151,25 @@ export class AggregateTransactionService { const multisigInfo = graphInfo.multisigAccounts.get(key); if (multisigInfo && !validationResult) { multisigInfo.forEach((multisig) => { - if (multisig.minApproval >= 1 && multisig.minRemoval) { // To make sure it is multisig account - const matchedCosignatories = this.compareArrays(cosignatoriesReceived, - multisig.cosignatories.map((cosig) => cosig.publicKey)); + if (multisig.minApproval >= 1 && multisig.minRemoval) { + // To make sure it is multisig account + const matchedCosignatories = this.compareArrays( + cosignatoriesReceived, + multisig.cosignatories.map((cosig) => cosig.publicKey), + ); /** * if minimal signature requirement met at current level, push the multisig account * into the received signatories array for next level validation. * Otherwise return validation failed. */ - if ((matchedCosignatories.length >= multisig.minApproval && !isMultisigRemoval) || - (matchedCosignatories.length >= multisig.minRemoval && isMultisigRemoval)) { + if ( + (matchedCosignatories.length >= multisig.minApproval && !isMultisigRemoval) || + (matchedCosignatories.length >= multisig.minRemoval && isMultisigRemoval) + ) { if (cosignatoriesReceived.indexOf(multisig.account.publicKey) === -1) { cosignatoriesReceived.push(multisig.account.publicKey); - } + } validationResult = true; } else { validationResult = false; @@ -140,11 +190,13 @@ export class AggregateTransactionService { */ private compareArrays(array1: string[], array2: string[]): string[] { const results: string[] = []; - array1.forEach((a1) => array2.forEach((a2) => { - if (a1 === a2) { - results.push(a1); - } - })); + array1.forEach((a1) => + array2.forEach((a2) => { + if (a1 === a2) { + results.push(a1); + } + }), + ); return results; } diff --git a/src/service/BlockService.ts b/src/service/BlockService.ts index ff3fb00f46..269271259e 100644 --- a/src/service/BlockService.ts +++ b/src/service/BlockService.ts @@ -26,10 +26,9 @@ import { UInt64 } from '../model/UInt64'; import { IBlockService } from './interfaces/IBlockService'; /** - * Transaction Service + * Block Service */ export class BlockService implements IBlockService { - private readonly blockRepository: BlockRepository; private readonly receiptRepository: ReceiptRepository; @@ -51,9 +50,9 @@ export class BlockService implements IBlockService { public validateTransactionInBlock(leaf: string, height: UInt64): Observable { const rootHashObservable = this.blockRepository.getBlockByHeight(height); const merklePathItemObservable = this.blockRepository.getMerkleTransaction(height, leaf); - return combineLatest([rootHashObservable, merklePathItemObservable]).pipe( - map((combined) => this.validateInBlock(leaf, combined[1].merklePath, combined[0].blockTransactionsHash)), - ).pipe(catchError(() => of(false))); + return combineLatest([rootHashObservable, merklePathItemObservable]) + .pipe(map((combined) => this.validateInBlock(leaf, combined[1].merklePath, combined[0].blockTransactionsHash))) + .pipe(catchError(() => of(false))); } /** @@ -64,9 +63,9 @@ export class BlockService implements IBlockService { public validateStatementInBlock(leaf: string, height: UInt64): Observable { const rootHashObservable = this.blockRepository.getBlockByHeight(height); const merklePathItemObservable = this.receiptRepository.getMerkleReceipts(height, leaf); - return combineLatest([rootHashObservable, merklePathItemObservable]).pipe( - map((combined) => this.validateInBlock(leaf, combined[1].merklePath, combined[0].blockReceiptsHash)), - ).pipe(catchError(() => of(false))); + return combineLatest([rootHashObservable, merklePathItemObservable]) + .pipe(map((combined) => this.validateInBlock(leaf, combined[1].merklePath, combined[0].blockReceiptsHash))) + .pipe(catchError(() => of(false))); } /** @@ -78,18 +77,18 @@ export class BlockService implements IBlockService { */ private validateInBlock(leaf: string, merklePathItem: MerklePathItem[] = [], rootHash: string): boolean { if (merklePathItem.length === 0) { - return leaf.toUpperCase() === rootHash.toUpperCase(); + return leaf.toUpperCase() === rootHash.toUpperCase(); } const rootToCompare = merklePathItem.reduce((proofHash, pathItem) => { - const hasher = sha3_256.create(); - // Left - if (pathItem.position !== undefined && pathItem.position === PositionEnum.Left) { - return hasher.update(Buffer.from(pathItem.hash + proofHash, 'hex')).hex(); - } else { - // Right - return hasher.update(Buffer.from(proofHash + pathItem.hash, 'hex')).hex(); - } - }, leaf); + const hasher = sha3_256.create(); + // Left + if (pathItem.position !== undefined && pathItem.position === PositionEnum.Left) { + return hasher.update(Buffer.from(pathItem.hash + proofHash, 'hex')).hex(); + } else { + // Right + return hasher.update(Buffer.from(proofHash + pathItem.hash, 'hex')).hex(); + } + }, leaf); return rootToCompare.toUpperCase() === rootHash.toUpperCase(); } } diff --git a/src/service/MetadataTransactionService.ts b/src/service/MetadataTransactionService.ts index 59a8554536..817e1c16b6 100644 --- a/src/service/MetadataTransactionService.ts +++ b/src/service/MetadataTransactionService.ts @@ -35,13 +35,11 @@ import { UInt64 } from '../model/UInt64'; * MetadataTransaction service */ export class MetadataTransactionService { - /** * Constructor * @param metadataRepository */ - constructor(private readonly metadataRepository: MetadataRepository) { - } + constructor(private readonly metadataRepository: MetadataRepository) {} /** * Create a Metadata Transaction object without knowing previous metadata value @@ -56,16 +54,17 @@ export class MetadataTransactionService { * @param maxFee - Max fee * @return {AccountMetadataTransaction | MosaicMetadataTransaction | NamespaceMetadataTransaction} */ - public createMetadataTransaction(deadline: Deadline, - networkType: NetworkType, - metadataType: MetadataType, - targetPublicAccount: PublicAccount, - key: UInt64, - value: string, - senderPublicAccount: PublicAccount, - targetId?: MosaicId | NamespaceId, - maxFee: UInt64 = new UInt64([0, 0])): - Observable { + public createMetadataTransaction( + deadline: Deadline, + networkType: NetworkType, + metadataType: MetadataType, + targetPublicAccount: PublicAccount, + key: UInt64, + value: string, + senderPublicAccount: PublicAccount, + targetId?: MosaicId | NamespaceId, + maxFee: UInt64 = new UInt64([0, 0]), + ): Observable { switch (metadataType) { case MetadataType.Account: return this.createAccountMetadataTransaction( @@ -79,7 +78,7 @@ export class MetadataTransactionService { ); case MetadataType.Mosaic: if (!targetId || !(targetId instanceof MosaicId)) { - throw Error ('TargetId for MosaicMetadataTransaction is invalid'); + throw Error('TargetId for MosaicMetadataTransaction is invalid'); } return this.createMosaicMetadataTransaction( deadline, @@ -93,7 +92,7 @@ export class MetadataTransactionService { ); case MetadataType.Namespace: if (!targetId || !(targetId instanceof NamespaceId)) { - throw Error ('TargetId for NamespaceMetadataTransaction is invalid'); + throw Error('TargetId for NamespaceMetadataTransaction is invalid'); } return this.createNamespaceMetadataTransaction( deadline, @@ -121,44 +120,50 @@ export class MetadataTransactionService { * @param maxFee - max fee * @returns {Observable} */ - private createAccountMetadataTransaction(deadline: Deadline, - networkType: NetworkType, - targetPublicKey: string, - key: UInt64, - value: string, - senderPublicKey: string, - maxFee: UInt64): Observable { - return this.metadataRepository.getAccountMetadataByKeyAndSender(Address.createFromPublicKey(targetPublicKey, networkType), - key.toHex(), senderPublicKey) - .pipe(map((metadata: Metadata) => { - const currentValueByte = Convert.utf8ToUint8(metadata.metadataEntry.value); - const newValueBytes = Convert.utf8ToUint8(value); - return AccountMetadataTransaction.create( - deadline, - targetPublicKey, - key, - newValueBytes.length - currentValueByte.length, - Convert.decodeHex(Convert.xor(currentValueByte, newValueBytes)), - networkType, - maxFee, - ); - }), - catchError((err: Error) => { - const error = JSON.parse(err.message); - if (error && error.statusCode && error.statusCode === 404) { + private createAccountMetadataTransaction( + deadline: Deadline, + networkType: NetworkType, + targetPublicKey: string, + key: UInt64, + value: string, + senderPublicKey: string, + maxFee: UInt64, + ): Observable { + return this.metadataRepository + .getAccountMetadataByKeyAndSender(Address.createFromPublicKey(targetPublicKey, networkType), key.toHex(), senderPublicKey) + .pipe( + map((metadata: Metadata) => { + const currentValueByte = Convert.utf8ToUint8(metadata.metadataEntry.value); const newValueBytes = Convert.utf8ToUint8(value); - return of(AccountMetadataTransaction.create( + return AccountMetadataTransaction.create( deadline, targetPublicKey, key, - newValueBytes.length, - value, + newValueBytes.length - currentValueByte.length, + Convert.decodeHex(Convert.xor(currentValueByte, newValueBytes)), networkType, maxFee, - )); - } - throw Error(err.message); - })); + ); + }), + catchError((err: Error) => { + const error = JSON.parse(err.message); + if (error && error.statusCode && error.statusCode === 404) { + const newValueBytes = Convert.utf8ToUint8(value); + return of( + AccountMetadataTransaction.create( + deadline, + targetPublicKey, + key, + newValueBytes.length, + value, + networkType, + maxFee, + ), + ); + } + throw Error(err.message); + }), + ); } /** @@ -173,17 +178,18 @@ export class MetadataTransactionService { * @param maxFee - max fee * @returns {Observable} */ - private createMosaicMetadataTransaction(deadline: Deadline, - networkType: NetworkType, - targetPublicKey: string, - mosaicId: MosaicId, - key: UInt64, - value: string, - senderPublicKey: string, - maxFee: UInt64): Observable { - return this.metadataRepository.getMosaicMetadataByKeyAndSender(mosaicId, - key.toHex(), senderPublicKey) - .pipe(map((metadata: Metadata) => { + private createMosaicMetadataTransaction( + deadline: Deadline, + networkType: NetworkType, + targetPublicKey: string, + mosaicId: MosaicId, + key: UInt64, + value: string, + senderPublicKey: string, + maxFee: UInt64, + ): Observable { + return this.metadataRepository.getMosaicMetadataByKeyAndSender(mosaicId, key.toHex(), senderPublicKey).pipe( + map((metadata: Metadata) => { const currentValueByte = Convert.utf8ToUint8(metadata.metadataEntry.value); const newValueBytes = Convert.utf8ToUint8(value); return MosaicMetadataTransaction.create( @@ -201,19 +207,22 @@ export class MetadataTransactionService { const error = JSON.parse(err.message); if (error && error.statusCode && error.statusCode === 404) { const newValueBytes = Convert.utf8ToUint8(value); - return of(MosaicMetadataTransaction.create( - deadline, - targetPublicKey, - key, - mosaicId, - newValueBytes.length, - value, - networkType, - maxFee, - )); + return of( + MosaicMetadataTransaction.create( + deadline, + targetPublicKey, + key, + mosaicId, + newValueBytes.length, + value, + networkType, + maxFee, + ), + ); } throw Error(err.message); - })); + }), + ); } /** @@ -228,17 +237,18 @@ export class MetadataTransactionService { * @param maxFee - max fee * @returns {Observable} */ - private createNamespaceMetadataTransaction(deadline: Deadline, - networkType: NetworkType, - targetPublicKey: string, - namespaceId: NamespaceId, - key: UInt64, - value: string, - senderPublicKey: string, - maxFee: UInt64): Observable { - return this.metadataRepository.getNamespaceMetadataByKeyAndSender(namespaceId, - key.toHex(), senderPublicKey) - .pipe(map((metadata: Metadata) => { + private createNamespaceMetadataTransaction( + deadline: Deadline, + networkType: NetworkType, + targetPublicKey: string, + namespaceId: NamespaceId, + key: UInt64, + value: string, + senderPublicKey: string, + maxFee: UInt64, + ): Observable { + return this.metadataRepository.getNamespaceMetadataByKeyAndSender(namespaceId, key.toHex(), senderPublicKey).pipe( + map((metadata: Metadata) => { const currentValueByte = Convert.utf8ToUint8(metadata.metadataEntry.value); const newValueBytes = Convert.utf8ToUint8(value); return NamespaceMetadataTransaction.create( @@ -256,18 +266,21 @@ export class MetadataTransactionService { const error = JSON.parse(err.message); if (error && error.statusCode && error.statusCode === 404) { const newValueBytes = Convert.utf8ToUint8(value); - return of(NamespaceMetadataTransaction.create( - deadline, - targetPublicKey, - key, - namespaceId, - newValueBytes.length, - value, - networkType, - maxFee, - )); + return of( + NamespaceMetadataTransaction.create( + deadline, + targetPublicKey, + key, + namespaceId, + newValueBytes.length, + value, + networkType, + maxFee, + ), + ); } throw Error(err.message); - })); + }), + ); } } diff --git a/src/service/MosaicAmountView.ts b/src/service/MosaicAmountView.ts index 974792c382..51309c6bd6 100644 --- a/src/service/MosaicAmountView.ts +++ b/src/service/MosaicAmountView.ts @@ -14,30 +14,29 @@ * limitations under the License. */ -import {MosaicInfo} from '../model/mosaic/MosaicInfo'; -import {UInt64} from '../model/UInt64'; +import { MosaicInfo } from '../model/mosaic/MosaicInfo'; +import { UInt64 } from '../model/UInt64'; /** * Class representing mosaic view information with amount */ export class MosaicAmountView { - /** * @param mosaicInfo * @param namespaceName * @param mosaicName * @param amount */ - constructor(/** - * The mosaic information - */ - public readonly mosaicInfo: MosaicInfo, - /** - * The amount of absolute mosaics we have - */ - public readonly amount: UInt64) { - - } + constructor( + /** + * The mosaic information + */ + public readonly mosaicInfo: MosaicInfo, + /** + * The amount of absolute mosaics we have + */ + public readonly amount: UInt64, + ) {} /** * Relative amount dividing amount by the divisibility diff --git a/src/service/MosaicRestrictionTransactionService.ts b/src/service/MosaicRestrictionTransactionService.ts index d522de89d0..f8cfe3f44a 100644 --- a/src/service/MosaicRestrictionTransactionService.ts +++ b/src/service/MosaicRestrictionTransactionService.ts @@ -14,10 +14,8 @@ * limitations under the License. */ -import { Observable, of } from 'rxjs'; -import { combineLatest } from 'rxjs'; -import { catchError, map } from 'rxjs/operators'; -import { mergeMap } from 'rxjs/operators'; +import { combineLatest, Observable, of } from 'rxjs'; +import { catchError, map, mergeMap } from 'rxjs/operators'; import { NamespaceRepository } from '../infrastructure/NamespaceRepository'; import { RestrictionMosaicRepository } from '../infrastructure/RestrictionMosaicRepository'; import { Address } from '../model/account/Address'; @@ -37,7 +35,6 @@ import { UInt64 } from '../model/UInt64'; * MosaicRestrictionTransactionService service */ export class MosaicRestrictionTransactionService { - private readonly defaultMosaicAddressRestrictionValue = UInt64.fromHex('FFFFFFFFFFFFFFFF'); private readonly defaultMosaicGlobalRestrictionValue = UInt64.fromUint(0); @@ -46,9 +43,10 @@ export class MosaicRestrictionTransactionService { * @param restrictionMosaicRepository * @param namespaceRepository */ - constructor(private readonly restrictionMosaicRepository: RestrictionMosaicRepository, - private readonly namespaceRepository: NamespaceRepository) { - } + constructor( + private readonly restrictionMosaicRepository: RestrictionMosaicRepository, + private readonly namespaceRepository: NamespaceRepository, + ) {} /** * Create a MosaicGlobalRestrictionTransaction object without previous restriction data @@ -61,35 +59,41 @@ export class MosaicRestrictionTransactionService { * @param referenceMosaicId - Reference mosaic Id * @param maxFee - Max fee */ - public createMosaicGlobalRestrictionTransaction(deadline: Deadline, - networkType: NetworkType, - mosaicId: MosaicId | NamespaceId, - restrictionKey: UInt64, - restrictionValue: string, - restrictionType: MosaicRestrictionType, - referenceMosaicId: MosaicId | NamespaceId = new MosaicId(UInt64.fromUint(0).toDTO()), - maxFee: UInt64 = new UInt64([0, 0])): Observable { + public createMosaicGlobalRestrictionTransaction( + deadline: Deadline, + networkType: NetworkType, + mosaicId: MosaicId | NamespaceId, + restrictionKey: UInt64, + restrictionValue: string, + restrictionType: MosaicRestrictionType, + referenceMosaicId: MosaicId | NamespaceId = new MosaicId(UInt64.fromUint(0).toDTO()), + maxFee: UInt64 = new UInt64([0, 0]), + ): Observable { this.validateInput(restrictionValue); return this.getResolvedMosaicId(mosaicId).pipe( - mergeMap((resolvedMosaicId) => this.getGlobalRestrictionEntry(resolvedMosaicId, restrictionKey).pipe( - map((restrictionEntry: MosaicGlobalRestrictionItem | undefined) => { - const currentValue = restrictionEntry ? UInt64.fromNumericString(restrictionEntry.restrictionValue) : - this.defaultMosaicGlobalRestrictionValue; - const currentType = restrictionEntry ? restrictionEntry.restrictionType : MosaicRestrictionType.NONE; - return MosaicGlobalRestrictionTransaction.create( - deadline, - resolvedMosaicId, - restrictionKey, - currentValue, - currentType, - UInt64.fromNumericString(restrictionValue), - restrictionType, - networkType, - referenceMosaicId, - maxFee, - ); - }), - ))); + mergeMap((resolvedMosaicId) => + this.getGlobalRestrictionEntry(resolvedMosaicId, restrictionKey).pipe( + map((restrictionEntry: MosaicGlobalRestrictionItem | undefined) => { + const currentValue = restrictionEntry + ? UInt64.fromNumericString(restrictionEntry.restrictionValue) + : this.defaultMosaicGlobalRestrictionValue; + const currentType = restrictionEntry ? restrictionEntry.restrictionType : MosaicRestrictionType.NONE; + return MosaicGlobalRestrictionTransaction.create( + deadline, + resolvedMosaicId, + restrictionKey, + currentValue, + currentType, + UInt64.fromNumericString(restrictionValue), + restrictionType, + networkType, + referenceMosaicId, + maxFee, + ); + }), + ), + ), + ); } /** @@ -102,39 +106,44 @@ export class MosaicRestrictionTransactionService { * @param restrictionValue - New restriction value * @param maxFee - Max fee */ - public createMosaicAddressRestrictionTransaction(deadline: Deadline, - networkType: NetworkType, - mosaicId: MosaicId | NamespaceId, - restrictionKey: UInt64, - targetAddress: Address | NamespaceId, - restrictionValue: string, - maxFee: UInt64 = new UInt64([0, 0])): Observable { + public createMosaicAddressRestrictionTransaction( + deadline: Deadline, + networkType: NetworkType, + mosaicId: MosaicId | NamespaceId, + restrictionKey: UInt64, + targetAddress: Address | NamespaceId, + restrictionValue: string, + maxFee: UInt64 = new UInt64([0, 0]), + ): Observable { this.validateInput(restrictionValue); const combinedUnresolved = combineLatest(this.getResolvedMosaicId(mosaicId), this.getResolvedAddress(targetAddress)); return combinedUnresolved.pipe( - mergeMap(([resolvedMosaicId, resolvedAddress]) => this.getGlobalRestrictionEntry(resolvedMosaicId, restrictionKey).pipe( - mergeMap((restrictionEntry: MosaicGlobalRestrictionItem | undefined) => { - if (!restrictionEntry) { - throw new Error('Global restriction is not valid for RestrictionKey: ' + restrictionKey); - } - return this.getAddressRestrictionEntry(resolvedMosaicId, restrictionKey, resolvedAddress).pipe( - map((optionalValue) => { - const currentValue = optionalValue ? - UInt64.fromNumericString(optionalValue) : this.defaultMosaicAddressRestrictionValue; - return MosaicAddressRestrictionTransaction.create( - deadline, - mosaicId, - restrictionKey, - targetAddress, - UInt64.fromNumericString(restrictionValue), - networkType, - currentValue, - maxFee, - ); - }), - ); - }), - )), + mergeMap(([resolvedMosaicId, resolvedAddress]) => + this.getGlobalRestrictionEntry(resolvedMosaicId, restrictionKey).pipe( + mergeMap((restrictionEntry: MosaicGlobalRestrictionItem | undefined) => { + if (!restrictionEntry) { + throw new Error('Global restriction is not valid for RestrictionKey: ' + restrictionKey); + } + return this.getAddressRestrictionEntry(resolvedMosaicId, restrictionKey, resolvedAddress).pipe( + map((optionalValue) => { + const currentValue = optionalValue + ? UInt64.fromNumericString(optionalValue) + : this.defaultMosaicAddressRestrictionValue; + return MosaicAddressRestrictionTransaction.create( + deadline, + mosaicId, + restrictionKey, + targetAddress, + UInt64.fromNumericString(restrictionValue), + networkType, + currentValue, + maxFee, + ); + }), + ); + }), + ), + ), ); } @@ -156,7 +165,8 @@ export class MosaicRestrictionTransactionService { return of(undefined); } throw new Error(err.message); - })); + }), + ); } /** @@ -176,14 +186,15 @@ export class MosaicRestrictionTransactionService { return of(undefined); } throw new Error(err.message); - })); + }), + ); } /** * Check if input restriction key and value are invalid or not * @param value - Restriction value */ - private validateInput(value: string) { + private validateInput(value: string): void { if (!UInt64.isLongNumericString(value)) { throw new Error(`RestrictionValue: ${value} is not a valid numeric string.`); } diff --git a/src/service/MosaicService.ts b/src/service/MosaicService.ts index 9ef23510f5..c3b140eacd 100644 --- a/src/service/MosaicService.ts +++ b/src/service/MosaicService.ts @@ -29,16 +29,12 @@ import { MosaicView } from './MosaicView'; * Mosaic service */ export class MosaicService { - /** * Constructor * @param accountRepository * @param mosaicRepository */ - constructor(private readonly accountRepository: AccountRepository, - private readonly mosaicRepository: MosaicRepository) { - - } + constructor(private readonly accountRepository: AccountRepository, private readonly mosaicRepository: MosaicRepository) {} /** * Get mosaic view given mosaicIds @@ -47,12 +43,16 @@ export class MosaicService { */ mosaicsView(mosaicIds: MosaicId[]): Observable { return observableOf(mosaicIds).pipe( - mergeMap((_) => this.mosaicRepository.getMosaics(mosaicIds).pipe( - mergeMap((info) => info), - map((mosaicInfo: MosaicInfo) => { - return new MosaicView(mosaicInfo); - }), - toArray()))); + mergeMap(() => + this.mosaicRepository.getMosaics(mosaicIds).pipe( + mergeMap((info) => info), + map((mosaicInfo: MosaicInfo) => { + return new MosaicView(mosaicInfo); + }), + toArray(), + ), + ), + ); } /** @@ -74,7 +74,8 @@ export class MosaicService { } }); return results; - })); + }), + ); } /** @@ -85,6 +86,7 @@ export class MosaicService { mosaicsAmountViewFromAddress(address: Address): Observable { return observableOf(address).pipe( mergeMap((_) => this.accountRepository.getAccountInfo(_)), - mergeMap((_) => this.mosaicsAmountView(_.mosaics))); + mergeMap((_) => this.mosaicsAmountView(_.mosaics)), + ); } } diff --git a/src/service/MosaicView.ts b/src/service/MosaicView.ts index 97fcbd7469..5b02808c6b 100644 --- a/src/service/MosaicView.ts +++ b/src/service/MosaicView.ts @@ -14,21 +14,20 @@ * limitations under the License. */ -import {MosaicInfo} from '../model/mosaic/MosaicInfo'; +import { MosaicInfo } from '../model/mosaic/MosaicInfo'; /** * Class representing mosaic view information */ export class MosaicView { - /** * @internal * @param mosaicInfo */ - constructor(/** - * The mosaic information - */ - public readonly mosaicInfo: MosaicInfo) { - - } + constructor( + /** + * The mosaic information + */ + public readonly mosaicInfo: MosaicInfo, + ) {} } diff --git a/src/service/Namespace.ts b/src/service/Namespace.ts index 533a615048..98f3ceb638 100644 --- a/src/service/Namespace.ts +++ b/src/service/Namespace.ts @@ -14,6 +14,6 @@ * limitations under the License. */ -import {NamespaceInfo} from '../model/namespace/NamespaceInfo'; +import { NamespaceInfo } from '../model/namespace/NamespaceInfo'; export type Namespace = NamespaceInfo & { name: string }; diff --git a/src/service/NamespaceService.ts b/src/service/NamespaceService.ts index c7f18bc1fa..679b62b3af 100644 --- a/src/service/NamespaceService.ts +++ b/src/service/NamespaceService.ts @@ -26,13 +26,11 @@ import { Namespace } from './Namespace'; * Namespace service */ export class NamespaceService { - /** * Constructor * @param namespaceRepository */ - constructor(private readonly namespaceRepository: NamespaceRepository) { - } + constructor(private readonly namespaceRepository: NamespaceRepository) {} /** * Get namespace info and name from namespace Id @@ -41,22 +39,33 @@ export class NamespaceService { */ namespace(id: NamespaceId): Observable { return this.namespaceRepository.getNamespace(id).pipe( - mergeMap((namespaceInfo: NamespaceInfo) => this.namespaceRepository - .getNamespacesName(namespaceInfo.levels).pipe( - map((names) => Object.assign( - {__proto__: Object.getPrototypeOf(namespaceInfo)}, - namespaceInfo, - {name: this.extractFullNamespace(namespaceInfo, names)}))))); + mergeMap((namespaceInfo: NamespaceInfo) => + this.namespaceRepository.getNamespacesName(namespaceInfo.levels).pipe( + map((names) => + Object.assign( + { + __proto__: Object.getPrototypeOf(namespaceInfo), + }, + namespaceInfo, + { + name: this.extractFullNamespace(namespaceInfo, names), + }, + ), + ), + ), + ), + ); } private extractFullNamespace(namespace: NamespaceInfo, namespaceNames: NamespaceName[]): string { - return namespace.levels.map((level) => { - const namespaceName = namespaceNames.find((name) => name.namespaceId.equals(level)); - if (namespace === undefined) { - throw new Error('Not found'); - } - return namespaceName; - }) + return namespace.levels + .map((level) => { + const namespaceName = namespaceNames.find((name) => name.namespaceId.equals(level)); + if (namespace === undefined) { + throw new Error('Not found'); + } + return namespaceName; + }) .map((namespaceName: NamespaceName) => namespaceName.name) .join('.'); } diff --git a/src/service/TransactionService.ts b/src/service/TransactionService.ts index c0fd3bf768..01c31c52dd 100644 --- a/src/service/TransactionService.ts +++ b/src/service/TransactionService.ts @@ -41,15 +41,12 @@ import { ITransactionService } from './interfaces/ITransactionService'; * Transaction Service */ export class TransactionService implements ITransactionService { - /** * Constructor * @param transactionRepository * @param receiptRepository */ - constructor(private readonly transactionRepository: TransactionRepository, - private readonly receiptRepository: ReceiptRepository) { - } + constructor(private readonly transactionRepository: TransactionRepository, private readonly receiptRepository: ReceiptRepository) {} /** * Resolve unresolved mosaic / address from array of transactions @@ -72,8 +69,12 @@ export class TransactionService implements ITransactionService { public announce(signedTransaction: SignedTransaction, listener: IListener): Observable { const signerAddress = signedTransaction.getSignerAddress(); this.transactionRepository.announce(signedTransaction); - return this.getTransactionOrRaiseError(listener, - signerAddress, signedTransaction.hash, listener.confirmed(signerAddress, signedTransaction.hash)); + return this.getTransactionOrRaiseError( + listener, + signerAddress, + signedTransaction.hash, + listener.confirmed(signerAddress, signedTransaction.hash), + ); } /** @@ -85,9 +86,9 @@ export class TransactionService implements ITransactionService { */ public announceAggregateBonded(signedTransaction: SignedTransaction, listener: IListener): Observable { const signerAddress = signedTransaction.getSignerAddress(); - const transactionObservable = this.transactionRepository.announceAggregateBonded(signedTransaction).pipe( - flatMap(() => listener.aggregateBondedAdded(signerAddress, signedTransaction.hash)), - ); + const transactionObservable = this.transactionRepository + .announceAggregateBonded(signedTransaction) + .pipe(flatMap(() => listener.aggregateBondedAdded(signerAddress, signedTransaction.hash))); return this.getTransactionOrRaiseError(listener, signerAddress, signedTransaction.hash, transactionObservable); } @@ -101,9 +102,11 @@ export class TransactionService implements ITransactionService { * @param listener Websocket listener * @returns {Observable} */ - public announceHashLockAggregateBonded(signedHashLockTransaction: SignedTransaction, - signedAggregateTransaction: SignedTransaction, - listener: IListener): Observable { + public announceHashLockAggregateBonded( + signedHashLockTransaction: SignedTransaction, + signedAggregateTransaction: SignedTransaction, + listener: IListener, + ): Observable { return this.announce(signedHashLockTransaction, listener).pipe( flatMap(() => this.announceAggregateBonded(signedAggregateTransaction, listener)), ); @@ -120,16 +123,23 @@ export class TransactionService implements ITransactionService { * @param transactionHash the transaction hash * @param transactionObservable the observable with the valid transaction */ - private getTransactionOrRaiseError(listener: IListener, address: Address, transactionHash: string, - transactionObservable: Observable): Observable { + private getTransactionOrRaiseError( + listener: IListener, + address: Address, + transactionHash: string, + transactionObservable: Observable, + ): Observable { const errorObservable = listener.status(address).pipe(filter((t) => t.hash.toUpperCase() === transactionHash.toUpperCase())); - return merge(transactionObservable, errorObservable).pipe(first(), map((errorOrTransaction) => { - if (errorOrTransaction instanceof TransactionStatusError) { - throw new Error(errorOrTransaction.code); - } else { - return errorOrTransaction; - } - })); + return merge(transactionObservable, errorObservable).pipe( + first(), + map((errorOrTransaction) => { + if (errorOrTransaction instanceof TransactionStatusError) { + throw new Error(errorOrTransaction.code); + } else { + return errorOrTransaction; + } + }), + ); } /** @@ -139,7 +149,7 @@ export class TransactionService implements ITransactionService { */ private resolveTransaction(transaction: Transaction): Observable { if ([TransactionType.AGGREGATE_BONDED, TransactionType.AGGREGATE_COMPLETE].includes(transaction.type)) { - if ((transaction as AggregateTransaction).innerTransactions.find((tx) => this.checkShouldResolve((tx as Transaction)))) { + if ((transaction as AggregateTransaction).innerTransactions.find((tx) => this.checkShouldResolve(tx as Transaction))) { return this.resolvedFromReceipt(transaction, transaction.transactionInfo!.index); } return of(transaction); @@ -167,22 +177,30 @@ export class TransactionService implements ITransactionService { return false; case TransactionType.ACCOUNT_ADDRESS_RESTRICTION: const accountAddressRestriction = transaction as AccountAddressRestrictionTransaction; - return accountAddressRestriction.restrictionAdditions.find((address) => address instanceof NamespaceId) !== undefined || - accountAddressRestriction.restrictionDeletions.find((address) => address instanceof NamespaceId) !== undefined; + return ( + accountAddressRestriction.restrictionAdditions.find((address) => address instanceof NamespaceId) !== undefined || + accountAddressRestriction.restrictionDeletions.find((address) => address instanceof NamespaceId) !== undefined + ); case TransactionType.ACCOUNT_MOSAIC_RESTRICTION: const accountMosaicRestriction = transaction as AccountAddressRestrictionTransaction; - return accountMosaicRestriction.restrictionAdditions.find((mosaicId) => mosaicId instanceof NamespaceId) !== undefined || - accountMosaicRestriction.restrictionDeletions.find((mosaicId) => mosaicId instanceof NamespaceId) !== undefined; + return ( + accountMosaicRestriction.restrictionAdditions.find((mosaicId) => mosaicId instanceof NamespaceId) !== undefined || + accountMosaicRestriction.restrictionDeletions.find((mosaicId) => mosaicId instanceof NamespaceId) !== undefined + ); case TransactionType.HASH_LOCK: return (transaction as LockFundsTransaction).mosaic.id instanceof NamespaceId; case TransactionType.MOSAIC_ADDRESS_RESTRICTION: const mosaicAddressRestriction = transaction as MosaicAddressRestrictionTransaction; - return mosaicAddressRestriction.targetAddress instanceof NamespaceId || - mosaicAddressRestriction.mosaicId instanceof NamespaceId; + return ( + mosaicAddressRestriction.targetAddress instanceof NamespaceId || + mosaicAddressRestriction.mosaicId instanceof NamespaceId + ); case TransactionType.MOSAIC_GLOBAL_RESTRICTION: const mosaicGlobalRestriction = transaction as MosaicGlobalRestrictionTransaction; - return mosaicGlobalRestriction.referenceMosaicId instanceof NamespaceId || - mosaicGlobalRestriction.mosaicId instanceof NamespaceId; + return ( + mosaicGlobalRestriction.referenceMosaicId instanceof NamespaceId || + mosaicGlobalRestriction.mosaicId instanceof NamespaceId + ); case TransactionType.MOSAIC_METADATA: return (transaction as MosaicMetadataTransaction).targetMosaicId instanceof NamespaceId; case TransactionType.MOSAIC_SUPPLY_CHANGE: @@ -191,12 +209,13 @@ export class TransactionService implements ITransactionService { return (transaction as SecretProofTransaction).recipientAddress instanceof NamespaceId; case TransactionType.SECRET_LOCK: const secretLock = transaction as SecretLockTransaction; - return secretLock.recipientAddress instanceof NamespaceId || - secretLock.mosaic.id instanceof NamespaceId; + return secretLock.recipientAddress instanceof NamespaceId || secretLock.mosaic.id instanceof NamespaceId; case TransactionType.TRANSFER: const transfer = transaction as TransferTransaction; - return transfer.recipientAddress instanceof NamespaceId || - transfer.mosaics.find((mosaic) => mosaic.id instanceof NamespaceId) !== undefined; + return ( + transfer.recipientAddress instanceof NamespaceId || + transfer.mosaics.find((mosaic) => mosaic.id instanceof NamespaceId) !== undefined + ); default: throw new Error('Transaction type not not recogonised.'); } @@ -210,8 +229,8 @@ export class TransactionService implements ITransactionService { * @return {Observable} */ private resolvedFromReceipt(transaction: Transaction, aggregateIndex: number): Observable { - return this.receiptRepository.getBlockReceipts(transaction.transactionInfo!.height).pipe( - map((statement) => transaction.resolveAliases(statement, aggregateIndex)), - ); + return this.receiptRepository + .getBlockReceipts(transaction.transactionInfo!.height) + .pipe(map((statement) => transaction.resolveAliases(statement, aggregateIndex))); } } diff --git a/src/service/interfaces/IAccountService.ts b/src/service/interfaces/IAccountService.ts new file mode 100644 index 0000000000..2d70b21b4c --- /dev/null +++ b/src/service/interfaces/IAccountService.ts @@ -0,0 +1,38 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Observable } from 'rxjs'; +import { Address } from '../../model/account/Address'; +import { AccountInfoResolvedMosaic } from '../../model/account/AccountInfoResolvedMosaic'; +import { NamespaceInfoWithName } from '../../model/namespace/NamespaceInfoWithName'; + +/** + * Block Service Interface + */ +export interface IAccountService { + /** + * Get account info with resolved mosaic + * @param addresses Array of addresses + */ + accountInfoWithResolvedMosaic(addresses: Address[]): Observable; + + /** + * Get namespace info for account with namespace name + * @param addresses Array of addresses + * @returns {Observable} + */ + accountNamespacesWithName(addresses: Address[]): Observable; +} diff --git a/src/service/interfaces/IBlockService.ts b/src/service/interfaces/IBlockService.ts index e8d349c25b..7e6afb26bf 100644 --- a/src/service/interfaces/IBlockService.ts +++ b/src/service/interfaces/IBlockService.ts @@ -21,7 +21,6 @@ import { UInt64 } from '../../model/UInt64'; * Block Service Interface */ export interface IBlockService { - /** * Validate transaction hash in block * @param leaf transaction hash diff --git a/src/service/interfaces/ITransactionService.ts b/src/service/interfaces/ITransactionService.ts index 3e25faa458..a7d655c988 100644 --- a/src/service/interfaces/ITransactionService.ts +++ b/src/service/interfaces/ITransactionService.ts @@ -24,7 +24,6 @@ import { Transaction } from '../../model/transaction/Transaction'; * Transaction Service Interface */ export interface ITransactionService { - /** * @param transactionHashes List of transaction hashes. * @returns {Observable} @@ -90,7 +89,9 @@ export interface ITransactionService { * @param listener Websocket listener * @returns {Observable} */ - announceHashLockAggregateBonded(signedHashLockTransaction: SignedTransaction, - signedAggregateTransaction: SignedTransaction, - listener: IListener): Observable; + announceHashLockAggregateBonded( + signedHashLockTransaction: SignedTransaction, + signedAggregateTransaction: SignedTransaction, + listener: IListener, + ): Observable; } diff --git a/src/service/service.ts b/src/service/service.ts index c9edfe3112..54a474613f 100644 --- a/src/service/service.ts +++ b/src/service/service.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +export * from './AccountService'; export * from './NamespaceService'; export * from './MosaicService'; export * from './AggregateTransactionService'; @@ -21,5 +22,6 @@ export * from './MetadataTransactionService'; export * from './MosaicRestrictionTransactionService'; export * from './TransactionService'; export * from './BlockService'; +export * from './interfaces/IAccountService'; export * from './interfaces/IBlockService'; export * from './interfaces/ITransactionService'; diff --git a/test/conf/conf.spec.ts b/test/conf/conf.spec.ts index d3b6c76927..fed52157ec 100644 --- a/test/conf/conf.spec.ts +++ b/test/conf/conf.spec.ts @@ -14,27 +14,32 @@ * limitations under the License. */ -import {Account} from '../../src/model/account/Account'; -import {NetworkType} from '../../src/model/network/NetworkType'; +import { Account } from '../../src/model/account/Account'; +import { NetworkType } from '../../src/model/network/NetworkType'; export const TestingAccount = Account.createFromPrivateKey( '26b64cb10f005e5988a36744ca19e20d835ccc7c105aaa5f3b212da593180930', - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, +); export const MultisigAccount = Account.createFromPrivateKey( '5edebfdbeb32e9146d05ffd232c8af2cf9f396caf9954289daa0362d097fff3b', - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, +); export const CosignatoryAccount = Account.createFromPrivateKey( '2a2b1f5d366a5dd5dc56c3c757cf4fe6c66e2787087692cf329d7a49a594658b', - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, +); export const Cosignatory2Account = Account.createFromPrivateKey( 'b8afae6f4ad13a1b8aad047b488e0738a437c7389d4ff30c359ac068910c1d59', - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, +); export const Cosignatory3Account = Account.createFromPrivateKey( '111602be4d36f92dd60ca6a3c68478988578f26f6a02f8c72089839515ab603e', - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, +); export const NIS2_URL = 'http://localhost:3000'; diff --git a/test/core/crypto/MerkleHashBuilder.spec.ts b/test/core/crypto/MerkleHashBuilder.spec.ts index 9618be63d4..c4f15edfe3 100644 --- a/test/core/crypto/MerkleHashBuilder.spec.ts +++ b/test/core/crypto/MerkleHashBuilder.spec.ts @@ -26,7 +26,6 @@ describe('MerkleHashBuilder should', () => { const rootHash = builder.getRootHash(); expect(Convert.uint8ToHex(rootHash)).equal('0000000000000000000000000000000000000000000000000000000000000000'); - }); it('return first hash given single child', () => { @@ -38,7 +37,6 @@ describe('MerkleHashBuilder should', () => { const rootHash = builder.getRootHash(); expect(Convert.uint8ToHex(rootHash)).equal('215B158F0BD416B596271BCE527CD9DC8E4A639CC271D896F9156AF6F441EEB9'); - }); it('create correct merkle hash given two children', () => { @@ -51,7 +49,6 @@ describe('MerkleHashBuilder should', () => { const rootHash = builder.getRootHash(); expect(Convert.uint8ToHex(rootHash).toLocaleLowerCase()).equal('1c704e3ac99b124f92d2648649ec72c7a19ea4e2bb24f669b976180a295876fa'); - }); it('create correct merkle hash given three children', () => { @@ -65,7 +62,5 @@ describe('MerkleHashBuilder should', () => { const rootHash = builder.getRootHash(); expect(Convert.uint8ToHex(rootHash).toLocaleLowerCase()).equal('5dc17b2409d50bcc7c1faa720d0ec8b79a1705d0c517bcc0bdbd316540974d5e'); - }); - }); diff --git a/test/core/crypto/crypto.spec.ts b/test/core/crypto/crypto.spec.ts index 4f800ec320..2b6958e132 100644 --- a/test/core/crypto/crypto.spec.ts +++ b/test/core/crypto/crypto.spec.ts @@ -1,5 +1,5 @@ /* - * Copyright 2019 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,330 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import {Crypto} from '../../../src/core/crypto'; +import { expect } from 'chai'; +import { Crypto } from '../../../src/core/crypto'; import { KeyPair } from '../../../src/core/crypto/KeyPair'; -import {Convert, Convert as convert} from '../../../src/core/format'; -import { WalletAlgorithm } from '../../../src/model/wallet/WalletAlgorithm'; +import { Convert, Convert as convert } from '../../../src/core/format'; -import CryptoJS = require('crypto-js'); describe('crypto tests', () => { - it('Can derive a key from password and count', () => { - // Arrange: - const password = 'TestTest'; - const count = 20; - const expectedKey = '8cd87bc513857a7079d182a6e19b370e907107d97bd3f81a85bcebcc4b5bd3b5'; - - // Act: - const result = Crypto.derivePassSha(password, count); - - // Assert: - expect(result.priv).equal(expectedKey); - }); - - it('Can encrypt a private key', () => { - // Arrange: - const password = 'TestTest'; - const privateKey = '2a91e1d5c110a8d0105aad4683f962c2a56663a3cad46666b16d243174673d90'; - const expectedKey = '8cd87bc513857a7079d182a6e19b370e907107d97bd3f81a85bcebcc4b5bd3b5'; - - // Act: - const result = Crypto.encodePrivateKey(privateKey, password); - const pass = Crypto.derivePassSha(password, 20); - - // Assert: - expect(pass.priv).equal(expectedKey); - expect(result.iv.length).equal(16 * 2); - expect(result.ciphertext.length).equal(48 * 2); - }); - - it('Can decrypt a private key', () => { - // Arrange: - const expectedPrivateKey = '2a91e1d5c110a8d0105aad4683f962c2a56663a3cad46666b16d243174673d90'; - const key = '8cd87bc513857a7079d182a6e19b370e907107d97bd3f81a85bcebcc4b5bd3b5'; - const encrypted = 'c09ef3ed0cadd6ca6d3638b5dd854ac871a0afaec6b7fed791166b571a64d57f564376dc0180c851b0a1120b5896e6a0'; - const iv = '0329814121c7a4bb11418084dbe40560'; - const obj = { - ciphertext: CryptoJS.enc.Hex.parse(encrypted), - iv: convert.hexToUint8(iv), - key: convert.hexToUint8(key), - }; - - // Act: - const decrypted = Crypto.decrypt(obj); - - // Assert: - expect(decrypted).equal(expectedPrivateKey); - }); - - it('Can encrypt and decrypt private Key', () => { - // Arrange: - const password = 'TestTest'; - const privateKey = '2a91e1d5c110a8d0105aad4683f962c2a56663a3cad46666b16d243174673d90'; - - // Act: - const result = Crypto.encodePrivateKey(privateKey, password); - const pass = Crypto.derivePassSha(password, 20); - const obj = { - ciphertext: CryptoJS.enc.Hex.parse(result.ciphertext), - iv: convert.hexToUint8(result.iv), - key: convert.hexToUint8(pass.priv), - }; - const decrypted = Crypto.decrypt(obj); - - // Assert: - expect(privateKey).equal(decrypted); - }); - - describe('Encrypt private key edge-cases', () => { - it('Encryption throw error if no password', () => { - // Arrange: - const password = ''; - const privateKey = '2a91e1d5c110a8d0105aad4683f962c2a56663a3cad46666b16d243174673d90'; - - // Act: - const result = Crypto.encodePrivateKey.bind(null, privateKey, password); - - // Assert: - expect(result).to.throw('Missing argument !'); - }); - - it('Encryption throw error if no private key', () => { - // Arrange: - const password = 'TestTest'; - const privateKey = ''; - - // Act - const result = Crypto.encodePrivateKey.bind(null, privateKey, password); - - // Assert: - expect(result).to.throw('Missing argument !'); - }); - }); - - it('Can decrypt private key of pass:enc wallets', () => { - // Arrange: - const common = { - password: 'TestTest', - privateKey: '', - }; - const walletAccount = { - encrypted: '2e1717f245b7e1138b0dfe99dfce65b16b1c9d8ca03a9f90b86b43677b6337ce56ec474c64f73244790eb2490ad14752', - iv: 'dccffaa4883cda85d6b06714aabe6ec6', - }; - const mainAlgo = WalletAlgorithm.Pass_enc; - const expectedPrivateKey = '2a91e1d5c110a8d0105aad4683f962c2a56663a3cad46666b16d243174673d90'; - - // Act: - const result = Crypto.passwordToPrivateKey(common, walletAccount, mainAlgo); - - // Assert: - expect(result).equal(true); - expect(common.privateKey).equal(expectedPrivateKey); - }); - - it('Can decrypt private key of pass:bip32 wallets', () => { - // Arrange: - const common = { - password: 'TestTest', - privateKey: '', - }; - const walletAccount = { - encrypted: '2e1717f245b7e1138b0dfe99dfce65b16b1c9d8ca03a9f90b86b43677b6337ce56ec474c64f73244790eb2490ad14752', - iv: 'dccffaa4883cda85d6b06714aabe6ec6', - }; - const mainAlgo = WalletAlgorithm.Pass_bip32; - const expectedPrivateKey = '2a91e1d5c110a8d0105aad4683f962c2a56663a3cad46666b16d243174673d90'; - - // Act: - const result = Crypto.passwordToPrivateKey(common, walletAccount, mainAlgo); - - // Assert: - expect(result).equal(true); - expect(common.privateKey).equal(expectedPrivateKey); - }); - - it('Can decrypt private key of pass:6k wallets', () => { - // Arrange: - const common = { - password: 'TestTest', - privateKey: '', - }; - const walletAccount = { - encrypted: '', - iv: '', - }; - const mainAlgo = WalletAlgorithm.Pass_6k; - const expectedPrivateKey = '8fac70ea9aca3ae3418e25c0d31d9a0723e0a1790ae8fa97747c00dc0037472e'; - - // Act: - const result = Crypto.passwordToPrivateKey(common, walletAccount, mainAlgo); - - // Assert: - expect(result).equal(true); - expect(common.privateKey).equal(expectedPrivateKey); - }); - - it('Can decrypt private key of pass:6k wallets childs', () => { - // Arrange: - const common = { - password: 'TestTest', - privateKey: '', - }; - const walletAccount = { - encrypted: '5c3a7ebbefb391e5175a29ec5a22cb162cd590bb2e0b09416273f86bdc39fa83c04c4bb53b9c64fd1e6eaba5dba149bd', - iv: 'f131d9a4dfb1b0b696e05ccae9412e8f', - }; - const mainAlgo = WalletAlgorithm.Pass_6k; - const expectedPrivateKey = '4f27ca43521bbc394a6f6dde65b533e0768f954fa47ce320b0e9f4b5fe450f9d'; - - // Act: - const result = Crypto.passwordToPrivateKey(common, walletAccount, mainAlgo); - - // Assert: - expect(result).equal(true); - expect(common.privateKey).equal(expectedPrivateKey); - }); - - describe('Decrypt private key edge-cases', () => { - it('Private key decryption throw error if no algo', () => { - // Arrange: - const common = { - password: 'TestTest', - privateKey: '', - }; - const walletAccount = { - encrypted: '2e1717f245b7e1138b0dfe99dfce65b16b1c9d8ca03a9f90b86b43677b6337ce56ec474c64f73244790eb2490ad14752', - iv: 'dccffaa4883cda85d6b06714aabe6ec6', - }; - const mainAlgo = ''; - - // Act: - const result = Crypto.passwordToPrivateKey.bind(null, common, walletAccount, mainAlgo); - - // Assert: - expect(result).to.throw('Missing argument !'); - }); - - it('Decryption of pass:enc wallets thow error if no password', () => { - // Arrange: - const common = { - password: '', - privateKey: '', - }; - const walletAccount = { - encrypted: '2e1717f245b7e1138b0dfe99dfce65b16b1c9d8ca03a9f90b86b43677b6337ce56ec474c64f73244790eb2490ad14752', - iv: 'dccffaa4883cda85d6b06714aabe6ec6', - }; - const mainAlgo = WalletAlgorithm.Pass_enc; - - // Act: - const result = Crypto.passwordToPrivateKey.bind(null, common, walletAccount, mainAlgo); - - // Assert: - expect(result).to.throw('Missing argument !'); - }); - - it('Decryption of pass:bip32 wallets throw error if no password', () => { - // Arrange: - const common = { - password: '', - privateKey: '', - }; - const walletAccount = { - encrypted: '2e1717f245b7e1138b0dfe99dfce65b16b1c9d8ca03a9f90b86b43677b6337ce56ec474c64f73244790eb2490ad14752', - iv: 'dccffaa4883cda85d6b06714aabe6ec6', - }; - const mainAlgo = WalletAlgorithm.Pass_bip32; - - // Act: - const result = Crypto.passwordToPrivateKey.bind(null, common, walletAccount, mainAlgo); - - // Assert: - expect(result).to.throw('Missing argument !'); - }); - - it('Decryption of pass:6k wallets throw error if no password', () => { - // Arrange: - const common = { - password: '', - privateKey: '', - }; - const walletAccount = { - encrypted: '2e1717f245b7e1138b0dfe99dfce65b16b1c9d8ca03a9f90b86b43677b6337ce56ec474c64f73244790eb2490ad14752', - iv: 'dccffaa4883cda85d6b06714aabe6ec6', - }; - const mainAlgo = WalletAlgorithm.Pass_6k; - - // Act: - const result = Crypto.passwordToPrivateKey.bind(null, common, walletAccount, mainAlgo); - - // Assert: - expect(result).to.throw('Missing argument !'); - }); - - it('Decryption of pass:6k wallets generate a private key if no encrypted and iv in wallet account', () => { - // Arrange: - const common = { - password: 'TestTest', - privateKey: '', - }; - const walletAccount = { - encrypted: '', - iv: '', - }; - const mainAlgo = WalletAlgorithm.Pass_6k; - const expectedPrivateKey = '8fac70ea9aca3ae3418e25c0d31d9a0723e0a1790ae8fa97747c00dc0037472e'; - - // Act: - const result = Crypto.passwordToPrivateKey(common, walletAccount, mainAlgo); - - // Assert: - expect(result).equal(true); - expect(common.privateKey).equal(expectedPrivateKey); - }); - - it('Decryption of pass:6k wallets return false if encrypted data but no iv', () => { - // Arrange: - const common = { - password: 'TestTest', - privateKey: '', - }; - const walletAccount = { - encrypted: '2e1717f245b7e1138b0dfe99dfce65b16b1c9d8ca03a9f90b86b43677b6337ce56ec474c64f73244790eb2490ad14752', - iv: '', - }; - const mainAlgo = WalletAlgorithm.Pass_6k; - - // Act: - const result = Crypto.passwordToPrivateKey(common, walletAccount, mainAlgo); - - // Assert: - expect(result).equal(false); - expect(common.privateKey).equal(''); - }); - - it('Decryption of pass:6k wallets return false if no encrypted data but iv', () => { - // Arrange: - const common = { - password: 'TestTest', - privateKey: '', - }; - const walletAccount = { - encrypted: '', - iv: 'dccffaa4883cda85d6b06714aabe6ec6', - }; - const mainAlgo = WalletAlgorithm.Pass_6k; - - // Act: - const result = Crypto.passwordToPrivateKey(common, walletAccount, mainAlgo); - - // Assert: - expect(result).equal(false); - expect(common.privateKey).equal(''); - }); - }); - it('Can encode and decode message', () => { const sender = KeyPair.createKeyPairFromPrivateKeyString('E1C8521608F4896CA26A0C2DE739310EA4B06861D126CF4D6922064678A1969B'); const recipient = KeyPair.createKeyPairFromPrivateKeyString('A22A4BBF126A2D7D7ECE823174DFD184C5DE0FDE4CB2075D30CFA409F7EF8908'); @@ -405,8 +87,8 @@ describe('crypto tests', () => { // Arrange: const senderPublic = '9291abb3c52134be9d20ef21a796743497df7776d2661237bda9cadade34e44c'; const recipientPriv = ''; - const message = 'NEM is awesome !'; - const encryptedMessage = 'dd31d6b4111c1023bae6533399e74f73a29c6e6b48ab550f8a7bea127e27ddd' + + const encryptedMessage = + 'dd31d6b4111c1023bae6533399e74f73a29c6e6b48ab550f8a7bea127e27ddd' + 'b4fd3fe4fad3c835307c0da52d9c268f56237d1810e07912e6a6568cba09d9a9176ee6b1ade9569c2e1e273e9675bd4ff'; // Act: @@ -420,8 +102,8 @@ describe('crypto tests', () => { // Arrange: const senderPublic = ''; const recipientPriv = '2618090794e9c9682f2ac6504369a2f4fb9fe7ee7746f9560aca228d355b1cb9'; - const message = 'NEM is awesome !'; - const encryptedMessage = 'dd31d6b4111c1023bae6533399e74f73a29c6e6b48ab550f8a7bea127e27ddd' + + const encryptedMessage = + 'dd31d6b4111c1023bae6533399e74f73a29c6e6b48ab550f8a7bea127e27ddd' + 'b4fd3fe4fad3c835307c0da52d9c268f56237d1810e07912e6a6568cba09d9a9176ee6b1ade9569c2e1e273e9675bd4ff'; // Act: @@ -435,7 +117,6 @@ describe('crypto tests', () => { // Arrange: const senderPublic = '9291abb3c52134be9d20ef21a796743497df7776d2661237bda9cadade34e44c'; const recipientPriv = '2618090794e9c9682f2ac6504369a2f4fb9fe7ee7746f9560aca228d355b1cb9'; - const message = 'NEM is awesome !'; const encryptedMessage = ''; // Act: @@ -446,38 +127,6 @@ describe('crypto tests', () => { }); }); - it('Can encrypt and decrypt private key for mobile', () => { - // Arrange: - const privateKey = '2a91e1d5c110a8d0105aad4683f962c2a56663a3cad46666b16d243174673d90'; - const password = 'TestTest'; - - // Act: - const result = Crypto.toMobileKey(password, privateKey); - const encrypted = result.encrypted; - const salt = CryptoJS.enc.Hex.parse(result.salt); - - const key = CryptoJS.PBKDF2(password, salt, { - keySize: 256 / 32, - iterations: 2000, - }); - - const iv = encrypted.substring(0, 32); - const encryptedPrvKey = encrypted.substring(32, 128); - - const obj = { - ciphertext: CryptoJS.enc.Hex.parse(encryptedPrvKey), - iv: convert.hexToUint8(iv), - key: convert.hexToUint8(key.toString()), - }; - - const decrypted = Crypto.decrypt(obj); - - // Assert: - expect(encrypted.length).equal(128); - expect(salt.toString().length).equal(32 * 2); - expect(decrypted).equal(privateKey); - }); - /** * @see https://github.com/nemtech/test-vectors/blob/master/4.test-cipher.json */ @@ -523,4 +172,46 @@ describe('crypto tests', () => { } }); }); + + describe('AES Encryption', () => { + const cipher1 = Crypto.encrypt('a', 'password'); + const cipher2 = Crypto.encrypt('a', 'password'); + const knownPass = 'password'; + const knownValue = '987654321'; + const knownCipher = '9c3afe1b658403d7522886cda510a3714c389ce697128ab8d3877bbbb53c2ecdY+QgfP/KHmUl+wk7rPwmEQ=='; + + it('encrypt() should generate distinct values always', () => { + expect(cipher1 === cipher2).to.equal(false); + }); + + it('decrypt() should return value given valid ciphertext and password', () => { + const plain = Crypto.decrypt(knownCipher, knownPass); + expect(plain.length).to.equal(knownValue.length); + expect(plain).to.equal(knownValue); + }); + + it('decrypt() should return empty given invalid ciphertext', () => { + const cipher = '+QgfP/KHmUl+wk7rPwmEQ=='; // invalid ciphertext + const plain = Crypto.decrypt(cipher, knownPass); + expect(plain.length).to.equal(0); + expect(plain).to.equal(''); + }); + + it('decrypt() should return empty given invalid password', () => { + const plain = Crypto.decrypt(knownCipher, 'password1'); // invalid password + expect(plain.length).to.equal(0); + expect(plain).to.equal(''); + }); + + it('decrypt() should accept ciphertext given encrypt', () => { + const data = ['encrypt', 'this']; + + data.map((word: string) => { + const pw = '1234567a'; + const cipher = Crypto.encrypt(word, pw); + const plain = Crypto.decrypt(cipher, pw); + expect(plain).to.equal(word); + }); + }); + }); }); diff --git a/test/core/crypto/hkdf.spec.ts b/test/core/crypto/hkdf.spec.ts index fa6e42e42b..9bac5305cc 100644 --- a/test/core/crypto/hkdf.spec.ts +++ b/test/core/crypto/hkdf.spec.ts @@ -16,7 +16,7 @@ import { expect } from 'chai'; import { Convert } from '../../../src/core/format'; -// tslint:disable-next-line: no-var-requires +// eslint-disable-next-line @typescript-eslint/no-var-requires const hkdf = require('futoin-hkdf'); describe('hkdf', () => { @@ -25,7 +25,7 @@ describe('hkdf', () => { const sharedSecret = 'string-or-buffer'; const hash = 'SHA-256'; const info = 'catapult'; - const sharedKey = hkdf(sharedSecret, 32, {salt: new Uint8Array(32), info, hash}); + const sharedKey = hkdf(sharedSecret, 32, { salt: new Uint8Array(32), info, hash }); expect(Convert.uint8ToHex(sharedKey)).equal('E618ACB2558E1721492E4AE3BED3F4D86F26C2B0CE6AD939943A6A540855D23F'); }); }); diff --git a/test/core/crypto/keyPair.spec.ts b/test/core/crypto/keyPair.spec.ts index ba8d8477f6..36192634a0 100644 --- a/test/core/crypto/keyPair.spec.ts +++ b/test/core/crypto/keyPair.spec.ts @@ -17,11 +17,9 @@ import { expect } from 'chai'; import { Crypto, KeyPair } from '../../../src/core/crypto'; import * as Utility from '../../../src/core/crypto/Utilities'; import { Convert } from '../../../src/core/format/Convert'; -import { NetworkType } from '../../../src/model/network/NetworkType'; describe('key pair', () => { - const randomKeyPair = () => - KeyPair.createKeyPairFromPrivateKeyString(Convert.uint8ToHex(Crypto.randomBytes(32))); + const randomKeyPair = (): any => KeyPair.createKeyPairFromPrivateKeyString(Convert.uint8ToHex(Crypto.randomBytes(32))); const Private_Key_Size = 32; const Signature_Size = 64; @@ -32,9 +30,9 @@ describe('key pair', () => { 'e8bf9bc0f35c12d8c8bf94dd3a8b5b4034f1063948e3cc5304e55e31aa4b95a6'.toUpperCase(), 'c325ea529674396db5675939e7988883d59a5fc17a28ca977e3ba85370232a83'.toUpperCase(), ]; - /** - * @see https://github.com/nemtech/test-vectors/blob/master/1.test-keys.json - */ + /** + * @see https://github.com/nemtech/test-vectors/blob/master/1.test-keys.json + */ describe('construction', () => { it('can extract from private key test vectors', () => { // Arrange: @@ -76,9 +74,8 @@ describe('key pair', () => { invalidPrivateKeys.forEach((privateKey) => { // Assert: expect(() => { - KeyPair.createKeyPairFromPrivateKeyString(privateKey); - }, `from ${privateKey}`) - .to.throw('private key has unexpected size'); + KeyPair.createKeyPairFromPrivateKeyString(privateKey); + }, `from ${privateKey}`).to.throw('private key has unexpected size'); }); }); }); @@ -120,8 +117,9 @@ describe('key pair', () => { // Assert: const message = ` from ${Catapult_Private_Key[i]}`; - expect(Convert.uint8ToHex(signature).toUpperCase(), - `private ${message}`).to.deep.equal(Expected_Signature[i].toUpperCase()); + expect(Convert.uint8ToHex(signature).toUpperCase(), `private ${message}`).to.deep.equal( + Expected_Signature[i].toUpperCase(), + ); const isVerified = KeyPair.verify(keyPair.publicKey, payload, signature); expect(isVerified, `private ${message}`).to.equal(true); } @@ -169,7 +167,6 @@ describe('key pair', () => { // Assert: expect(signature2).to.not.deep.equal(signature1); }); - }); describe('verify', () => { @@ -207,7 +204,7 @@ describe('key pair', () => { for (let i = 0; i < Signature_Size; i += 4) { const signature = KeyPair.sign(keyPair, payload); - signature[i] ^= 0xFF; + signature[i] ^= 0xff; // Act: const isVerified = KeyPair.verify(keyPair.publicKey, payload, signature); @@ -224,7 +221,7 @@ describe('key pair', () => { for (let i = 0; i < payload.length; i += 4) { const signature = KeyPair.sign(keyPair, payload); - payload[i] ^= 0xFF; + payload[i] ^= 0xff; // Act: const isVerified = KeyPair.verify(keyPair.publicKey, payload, signature); @@ -257,7 +254,7 @@ describe('key pair', () => { const signature = KeyPair.sign(keyPair, payload); for (let i = 0; i < keyPair.publicKey.length; ++i) { - keyPair.publicKey[i] ^= 0xFF; + keyPair.publicKey[i] ^= 0xff; } // Act: @@ -283,18 +280,48 @@ describe('key pair', () => { }); it('cannot verify non canonical signature', () => { - function scalarAddGroupOrder(scalar) { + function scalarAddGroupOrder(scalar): void { // 2^252 + 27742317777372353535851937790883648493, little endian const Group_Order = [ - 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, + 0xed, + 0xd3, + 0xf5, + 0x5c, + 0x1a, + 0x63, + 0x12, + 0x58, + 0xd6, + 0x9c, + 0xf7, + 0xa2, + 0xde, + 0xf9, + 0xde, + 0x14, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x10, ]; let r = 0; for (let i = 0; i < scalar.length; ++i) { const t = scalar[i] + Group_Order[i]; scalar[i] += Group_Order[i] + r; - r = (t >> 8) & 0xFF; + r = (t >> 8) & 0xff; } } @@ -318,7 +345,6 @@ describe('key pair', () => { }); describe('derive shared key', () => { - it('derives same shared key for both partners', () => { // Arrange: const keyPair1 = randomKeyPair(); diff --git a/test/core/crypto/sha3Hasher.spec.ts b/test/core/crypto/sha3Hasher.spec.ts index 2bda1f1f87..40c61b8881 100644 --- a/test/core/crypto/sha3Hasher.spec.ts +++ b/test/core/crypto/sha3Hasher.spec.ts @@ -13,21 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import {SHA3Hasher as sha3Hasher} from '../../../src/core/crypto/SHA3Hasher'; -import {Convert as convert} from '../../../src/core/format'; +import { expect } from 'chai'; +import { SHA3Hasher as sha3Hasher } from '../../../src/core/crypto/SHA3Hasher'; +import { Convert as convert } from '../../../src/core/format'; describe('hasher', () => { - const inputs = [ - '', - 'CC', - '41FB', - '1F877C', - 'C1ECFDFC', - '9F2FCC7C90DE090D6B87CD7E9718C1EA6CB21118FC2D5DE9F97E5DB6AC1E9C10', - ]; - - function addSha3Tests(length, expectedOutputs) { + const inputs = ['', 'CC', '41FB', '1F877C', 'C1ECFDFC', '9F2FCC7C90DE090D6B87CD7E9718C1EA6CB21118FC2D5DE9F97E5DB6AC1E9C10']; + + function addSha3Tests(length, expectedOutputs): void { describe('func', () => { it('can hash test vectors', () => { // Sanity: @@ -138,17 +131,17 @@ describe('hasher', () => { describe('sha3 512', () => { addSha3Tests(64, [ 'A69F73CCA23A9AC5C8B567DC185A756E97C982164FE25859E0D1DCC1475C80A615' + - 'B2123AF1F5F94C11E3E9402C3AC558F500199D95B6D3E301758586281DCD26', + 'B2123AF1F5F94C11E3E9402C3AC558F500199D95B6D3E301758586281DCD26', '3939FCC8B57B63612542DA31A834E5DCC36E2EE0F652AC72E02624FA2E5ADEECC7' + - 'DD6BB3580224B4D6138706FC6E80597B528051230B00621CC2B22999EAA205', + 'DD6BB3580224B4D6138706FC6E80597B528051230B00621CC2B22999EAA205', 'AA092865A40694D91754DBC767B5202C546E226877147A95CB8B4C8F8709FE8CD69' + - '05256B089DA37896EA5CA19D2CD9AB94C7192FC39F7CD4D598975A3013C69', + '05256B089DA37896EA5CA19D2CD9AB94C7192FC39F7CD4D598975A3013C69', 'CB20DCF54955F8091111688BECCEF48C1A2F0D0608C3A575163751F002DB30F40F2' + - 'F671834B22D208591CFAF1F5ECFE43C49863A53B3225BDFD7C6591BA7658B', + 'F671834B22D208591CFAF1F5ECFE43C49863A53B3225BDFD7C6591BA7658B', 'D4B4BDFEF56B821D36F4F70AB0D231B8D0C9134638FD54C46309D14FADA92A28401' + - '86EED5415AD7CF3969BDFBF2DAF8CCA76ABFE549BE6578C6F4143617A4F1A', + '86EED5415AD7CF3969BDFBF2DAF8CCA76ABFE549BE6578C6F4143617A4F1A', 'B087C90421AEBF87911647DE9D465CBDA166B672EC47CCD4054A7135A1EF885E7903' + - 'B52C3F2C3FE722B1C169297A91B82428956A02C631A2240F12162C7BC726', + 'B52C3F2C3FE722B1C169297A91B82428956A02C631A2240F12162C7BC726', ]); }); }); diff --git a/test/core/crypto/utilities.spec.ts b/test/core/crypto/utilities.spec.ts index 06f9d5eb0f..26babcef90 100644 --- a/test/core/crypto/utilities.spec.ts +++ b/test/core/crypto/utilities.spec.ts @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import {words2ua} from '../../../src/core/crypto/Utilities'; -import {Convert} from '../../../src/core/format'; +import { expect } from 'chai'; +import { words2ua } from '../../../src/core/crypto/Utilities'; +import { Convert } from '../../../src/core/format'; describe('crypto utilities', () => { it('words2ua creates an ua from a word array', () => { // Arrange: - const key = '4344645752e57065f814b51713d05810' - const words = [ 1128555607, 1390768229, -132860649, 332421136 ]; + const key = '4344645752e57065f814b51713d05810'; + const words = [1128555607, 1390768229, -132860649, 332421136]; // Act: - const ua = words2ua(new Uint8Array(16), {words}) + const ua = words2ua(new Uint8Array(16), { words }); // Assert: expect(ua).deep.equal(Convert.hexToUint8(key)); diff --git a/test/core/format/Base32.spec.ts b/test/core/format/Base32.spec.ts index 066f14b96c..f09ab0cedf 100644 --- a/test/core/format/Base32.spec.ts +++ b/test/core/format/Base32.spec.ts @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import {Convert as convert} from '../../../src/core/format'; -import {Base32 as base32} from '../../../src/core/format/Base32'; +import { expect } from 'chai'; +import { Convert as convert } from '../../../src/core/format'; +import { Base32 as base32 } from '../../../src/core/format/Base32'; describe('base32', () => { - const Test_Vectors = [{ + const Test_Vectors = [ + { decoded: '68BA9E8D1AA4502E1F73DA19784B5D7DA16CA1E4AF895FAC12', encoded: 'NC5J5DI2URIC4H3T3IMXQS25PWQWZIPEV6EV7LAS', }, @@ -66,7 +67,7 @@ describe('base32', () => { // Arrange: const data: any = []; for (let i = 0; 260 > i; ++i) { - data.push(i & 0xFF); + data.push(i & 0xff); } // Act: diff --git a/test/core/format/Convert.spec.ts b/test/core/format/Convert.spec.ts index 75ae48ef65..7cb430f977 100644 --- a/test/core/format/Convert.spec.ts +++ b/test/core/format/Convert.spec.ts @@ -39,7 +39,7 @@ describe('convert', () => { const byte = convert.toByte(pair1[0], pair2[0]); // Assert: - const expected = (pair1[1] * 16) + pair2[1]; + const expected = pair1[1] * 16 + pair2[1]; expect(byte, `input: ${pair1[0]}${pair2[0]}`).to.equal(expected); ++numTests; }); @@ -72,11 +72,7 @@ describe('convert', () => { describe('isHexString', () => { it('returns true for valid hex strings', () => { // Arrange: - const inputs = [ - '', - '026ee415fc15', - 'abcdef0123456789ABCDEF', - ]; + const inputs = ['', '026ee415fc15', 'abcdef0123456789ABCDEF']; // Act: for (const input of inputs) { @@ -119,7 +115,7 @@ describe('convert', () => { const actual = convert.hexToUint8('026ee415fc15'); // Assert: - const expected = Uint8Array.of(0x02, 0x6E, 0xE4, 0x15, 0xFC, 0x15); + const expected = Uint8Array.of(0x02, 0x6e, 0xe4, 0x15, 0xfc, 0x15); expect(actual).to.deep.equal(expected); }); @@ -128,7 +124,7 @@ describe('convert', () => { const actual = convert.hexToUint8('abcdef0123456789ABCDEF'); // Assert: - const expected = Uint8Array.of(0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF); + const expected = Uint8Array.of(0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef); expect(actual).to.deep.equal(expected); }); @@ -162,7 +158,7 @@ describe('convert', () => { const actual = convert.hexToUint8Reverse('026ee415fc15'); // Assert: - const expected = Uint8Array.of(0x15, 0xFC, 0x15, 0xE4, 0x6E, 0x02); + const expected = Uint8Array.of(0x15, 0xfc, 0x15, 0xe4, 0x6e, 0x02); expect(actual).to.deep.equal(expected); }); @@ -171,7 +167,7 @@ describe('convert', () => { const actual = convert.hexToUint8Reverse('abcdef0123456789ABCDEF'); // Assert: - const expected = Uint8Array.of(0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB); + const expected = Uint8Array.of(0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab); expect(actual).to.deep.equal(expected); }); @@ -201,7 +197,7 @@ describe('convert', () => { it('can format single value array into hex string', () => { // Act: - const actual = convert.uint8ToHex(Uint8Array.of(0xD2)); + const actual = convert.uint8ToHex(Uint8Array.of(0xd2)); // Assert: expect(actual).to.equal('D2'); @@ -209,7 +205,7 @@ describe('convert', () => { it('can format multi value array into hex string', () => { // Act: - const actual = convert.uint8ToHex(Uint8Array.of(0x02, 0x6E, 0xE4, 0x15, 0xFC, 0x15)); + const actual = convert.uint8ToHex(Uint8Array.of(0x02, 0x6e, 0xe4, 0x15, 0xfc, 0x15)); // Assert: expect(actual).to.equal('026EE415FC15'); @@ -227,18 +223,17 @@ describe('convert', () => { it('uint8 array with length multiple of four can be converted to uint32 array', () => { // Act: - const actual = convert.uint8ToUint32(Uint8Array.of(0x02, 0x6E, 0x89, 0xAB, 0xCD, 0xEF, 0xE4, 0x15)); + const actual = convert.uint8ToUint32(Uint8Array.of(0x02, 0x6e, 0x89, 0xab, 0xcd, 0xef, 0xe4, 0x15)); // Assert: - expect(actual).to.deep.equal(Uint32Array.of(0xAB896E02, 0x15E4EFCD)); + expect(actual).to.deep.equal(Uint32Array.of(0xab896e02, 0x15e4efcd)); }); it('uint8 array with length not multiple of four cannot be converted to uint32 array', () => { // Assert: expect(() => { - convert.uint8ToUint32(Uint8Array.of(0x02, 0x6E, 0xE4, 0x15, 0x15)); - }) - .to.throw('byte length of Uint32Array should be a multiple of 4'); + convert.uint8ToUint32(Uint8Array.of(0x02, 0x6e, 0xe4, 0x15, 0x15)); + }).to.throw('byte length of Uint32Array should be a multiple of 4'); }); }); @@ -253,10 +248,10 @@ describe('convert', () => { it('uint32 array with nonzero length can be converted to uint8 array', () => { // Act: - const actual = convert.uint32ToUint8(Uint32Array.of(0xAB896E02, 0x15E4EFCD)); + const actual = convert.uint32ToUint8(Uint32Array.of(0xab896e02, 0x15e4efcd)); // Assert: - expect(actual).to.deep.equal(Uint8Array.of(0x02, 0x6E, 0x89, 0xAB, 0xCD, 0xEF, 0xE4, 0x15)); + expect(actual).to.deep.equal(Uint8Array.of(0x02, 0x6e, 0x89, 0xab, 0xcd, 0xef, 0xe4, 0x15)); }); }); @@ -287,11 +282,12 @@ describe('convert', () => { }); describe('signed <-> unsigned byte', () => { - const testCases = [{ - signed: -128, - unsigned: 0x80, - description: 'min negative', - }, + const testCases = [ + { + signed: -128, + unsigned: 0x80, + description: 'min negative', + }, { signed: -127, unsigned: 0x81, @@ -299,12 +295,12 @@ describe('convert', () => { }, { signed: -87, - unsigned: 0xA9, + unsigned: 0xa9, description: 'negative', }, { signed: -1, - unsigned: 0xFF, + unsigned: 0xff, description: 'negative one', }, { @@ -324,21 +320,22 @@ describe('convert', () => { }, { signed: 126, - unsigned: 0x7E, + unsigned: 0x7e, description: 'max positive minus one', }, { signed: 127, - unsigned: 0x7F, + unsigned: 0x7f, description: 'max positive', }, ]; describe('uint8ToInt8', () => { - const failureTestCases = [{ - input: 256, - description: 'one too large', - }, + const failureTestCases = [ + { + input: 256, + description: 'one too large', + }, { input: 1000, description: 'very large', @@ -364,10 +361,11 @@ describe('convert', () => { }); describe('int8ToUint8', () => { - const failureTestCases = [{ - input: -1000, - description: 'very small', - }, + const failureTestCases = [ + { + input: -1000, + description: 'very small', + }, { input: -129, description: 'one too small', @@ -468,5 +466,4 @@ describe('convert', () => { expect(input).to.be.equal(-123456789); }); }); - }); diff --git a/test/core/format/IdGenerator.spec.ts b/test/core/format/IdGenerator.spec.ts index 96d6a55ef6..88f3607e8d 100644 --- a/test/core/format/IdGenerator.spec.ts +++ b/test/core/format/IdGenerator.spec.ts @@ -13,31 +13,58 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import {sha3_256} from 'js-sha3'; -import { - Convert as convert, - IdGenerator as idGenerator, - RawUInt64 as uint64, -} from '../../../src/core/format'; +import { expect } from 'chai'; +import { sha3_256 } from 'js-sha3'; +import { Convert as convert, IdGenerator as idGenerator, RawUInt64 as uint64 } from '../../../src/core/format'; const constants = { - nem_id: [0x375FFA4B, 0x84B3552D], - xem_id: [0xD95FCF29, 0xD525AD41], + nem_id: [0x375ffa4b, 0x84b3552d], + xem_id: [0xd95fcf29, 0xd525ad41], namespace_base_id: [0, 0], }; const basicMosaicInfo = { - nonce: [0x78, 0xE3, 0x6F, 0xB7], + nonce: [0x78, 0xe3, 0x6f, 0xb7], publicId: [ - 0x4A, 0xFF, 0x7B, 0x4B, 0xA8, 0xC1, 0xC2, 0x6A, 0x79, 0x17, 0x57, 0x59, 0x93, 0x34, 0x66, 0x27, - 0xCB, 0x6C, 0x80, 0xDE, 0x62, 0xCD, 0x92, 0xF7, 0xF9, 0xAE, 0xDB, 0x70, 0x64, 0xA3, 0xDE, 0x62, + 0x4a, + 0xff, + 0x7b, + 0x4b, + 0xa8, + 0xc1, + 0xc2, + 0x6a, + 0x79, + 0x17, + 0x57, + 0x59, + 0x93, + 0x34, + 0x66, + 0x27, + 0xcb, + 0x6c, + 0x80, + 0xde, + 0x62, + 0xcd, + 0x92, + 0xf7, + 0xf9, + 0xae, + 0xdb, + 0x70, + 0x64, + 0xa3, + 0xde, + 0x62, ], - id: [0xC0AFC518, 0x3AD842A8], + id: [0xc0afc518, 0x3ad842a8], }; const mosaicTestVector = { - rows: [{ + rows: [ + { publicKey: '4AFF7B4BA8C1C26A7917575993346627CB6C80DE62CD92F7F9AEDB7064A3DE62', nonce: 'B76FE378', expectedMosaicId: '3AD842A8C0AFC518', @@ -141,38 +168,42 @@ const mosaicTestVector = { }; describe('id generator', () => { - function generateNamespaceId(parentId, name) { + function generateNamespaceId(parentId, name): number[] { const hash = sha3_256.create(); - hash.update(Uint32Array.from(parentId).buffer as any); + hash.update(Uint32Array.from(parentId).buffer); hash.update(name); const result = new Uint32Array(hash.arrayBuffer()); // right zero-filling required to keep unsigned number representation return [result[0], (result[1] | 0x80000000) >>> 0]; } - function addBasicTests(generator) { + function addBasicTests(generator): void { it('produces different results for different names', () => { // Assert: ['bloodyrookie.alice', 'nem.mex', 'bloodyrookie.xem', 'bloody_rookie.xem'].forEach((name) => - expect(generator(name), `nem.xem vs ${name}`).to.not.equal(generator('nem.xem'))); + expect(generator(name), `nem.xem vs ${name}`).to.not.equal(generator('nem.xem')), + ); }); it('rejects names with uppercase characters', () => { // Assert: ['NEM.xem', 'NEM.XEM', 'nem.XEM', 'nEm.XeM', 'NeM.xEm'].forEach((name) => - expect(() => generator(name), `name ${name}`).to.throw('invalid part name')); + expect(() => generator(name), `name ${name}`).to.throw('invalid part name'), + ); }); it('rejects improper qualified names', () => { // Assert: ['.', '..', '...', '.a', 'b.', 'a..b', '.a.b', 'b.a.'].forEach((name) => - expect(() => generator(name), `name ${name}`).to.throw('empty part')); + expect(() => generator(name), `name ${name}`).to.throw('empty part'), + ); }); it('rejects improper part names', () => { // Assert: ['alpha.bet@.zeta', 'a!pha.beta.zeta', 'alpha.beta.ze^a'].forEach((name) => - expect(() => generator(name), `name ${name}`).to.throw('invalid part name')); + expect(() => generator(name), `name ${name}`).to.throw('invalid part name'), + ); }); it('rejects empty string', () => { @@ -184,21 +215,19 @@ describe('id generator', () => { describe('generate mosaic id', () => { it('generates correct well known id', () => { // Assert: - expect(idGenerator.generateMosaicId(basicMosaicInfo.nonce, basicMosaicInfo.publicId)) - .to.deep.equal(basicMosaicInfo.id); + expect(idGenerator.generateMosaicId(basicMosaicInfo.nonce, basicMosaicInfo.publicId)).to.deep.equal(basicMosaicInfo.id); }); // @dataProvider mosaicTestVector it('generates correct mosaicId given nonce and public key', () => { - mosaicTestVector.rows.map((row, i) => { + mosaicTestVector.rows.map((row) => { const pubKey = convert.hexToUint8(row.publicKey); const nonce = convert.hexToUint8(row.nonce).reverse(); // Little-Endianness! const mosaicId = idGenerator.generateMosaicId(nonce, pubKey); const expectedId = uint64.fromHex(row.expectedMosaicId); // Assert: - expect(mosaicId) - .to.deep.equal(expectedId); + expect(mosaicId).to.deep.equal(expectedId); }); }); }); @@ -225,7 +254,7 @@ describe('id generator', () => { it('supports multi level namespaces', () => { // Arrange: - const expected: any = []; + const expected: number[][] = []; expected.push(generateNamespaceId(constants.namespace_base_id, 'foo')); expected.push(generateNamespaceId(expected[0], 'bar')); expected.push(generateNamespaceId(expected[1], 'baz')); @@ -237,7 +266,8 @@ describe('id generator', () => { it('rejects improper qualified names', () => { // Assert: ['a:b:c', 'a::b'].forEach((name) => - expect(() => idGenerator.generateNamespacePath(name), `name ${name}`).to.throw('invalid part name')); + expect(() => idGenerator.generateNamespacePath(name), `name ${name}`).to.throw('invalid part name'), + ); }); addBasicTests(idGenerator.generateNamespacePath); }); diff --git a/test/core/format/RawAddress.spec.ts b/test/core/format/RawAddress.spec.ts index b949067bad..6c521ede23 100644 --- a/test/core/format/RawAddress.spec.ts +++ b/test/core/format/RawAddress.spec.ts @@ -13,18 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import { - Convert as convert, - RawAddress as address, -} from '../../../src/core/format'; +import { expect } from 'chai'; +import { Convert as convert, RawAddress as address } from '../../../src/core/format'; import { NetworkType } from '../../../src/model/model'; const Address_Decoded_Size = 25; describe('address', () => { describe('stringToAddress', () => { - function assertCannotCreateAddress(encoded, message) { + function assertCannotCreateAddress(encoded, message): void { // Assert: expect(() => { address.stringToAddress(encoded); @@ -40,7 +37,7 @@ describe('address', () => { const decoded = address.stringToAddress(encoded); // Assert: - expect(address.isValidAddress(decoded, NetworkType.MIJIN_TEST)).to.equal(true); + expect(address.isValidAddress(decoded)).to.equal(true); expect(convert.uint8ToHex(decoded)).to.equal(expectedHex); }); @@ -72,6 +69,13 @@ describe('address', () => { // Assert: expect(encoded).to.equal(expected); }); + + it('can create encoded address from address to throw', () => { + // Arrange: + const decodedHex = '60000000C089D996585466380EDBDC19D4959184893E38CA6'; + // Assert: + expect(() => address.addressToString(convert.hexToUint8(decodedHex))).to.throw(); + }); }); describe('publicKeyToAddress', () => { @@ -85,7 +89,7 @@ describe('address', () => { // Assert: expect(decoded[0]).to.equal(NetworkType.MIJIN); - expect(address.isValidAddress(decoded, NetworkType.MIJIN)).to.equal(true); + expect(address.isValidAddress(decoded)).to.equal(true); expect(convert.uint8ToHex(decoded)).to.equal(expectedHex); }); @@ -99,7 +103,7 @@ describe('address', () => { // Assert: expect(decoded[0]).to.equal(NetworkType.MIJIN_TEST); - expect(address.isValidAddress(decoded, NetworkType.MIJIN_TEST)).to.equal(true); + expect(address.isValidAddress(decoded)).to.equal(true); expect(convert.uint8ToHex(decoded)).to.equal(expectedHex); }); @@ -112,7 +116,7 @@ describe('address', () => { const decoded2 = address.publicKeyToAddress(publicKey, NetworkType.MIJIN_TEST); // Assert: - expect(address.isValidAddress(decoded1, NetworkType.MIJIN_TEST)).to.equal(true); + expect(address.isValidAddress(decoded1)).to.equal(true); expect(decoded1).to.deep.equal(decoded2); }); @@ -126,8 +130,8 @@ describe('address', () => { const decoded2 = address.publicKeyToAddress(publicKey2, NetworkType.MIJIN_TEST); // Assert: - expect(address.isValidAddress(decoded1, NetworkType.MIJIN_TEST)).to.equal(true); - expect(address.isValidAddress(decoded2, NetworkType.MIJIN_TEST)).to.equal(true); + expect(address.isValidAddress(decoded1)).to.equal(true); + expect(address.isValidAddress(decoded2)).to.equal(true); expect(decoded1).to.not.deep.equal(decoded2); }); @@ -140,8 +144,8 @@ describe('address', () => { const decoded2 = address.publicKeyToAddress(publicKey, NetworkType.TEST_NET); // Assert: - expect(address.isValidAddress(decoded1, NetworkType.MIJIN_TEST)).to.equal(true); - expect(address.isValidAddress(decoded2, NetworkType.TEST_NET)).to.equal(true); + expect(address.isValidAddress(decoded1)).to.equal(true); + expect(address.isValidAddress(decoded2)).to.equal(true); expect(decoded1).to.not.deep.equal(decoded2); }); }); @@ -153,7 +157,7 @@ describe('address', () => { const decoded = convert.hexToUint8(validHex); // Assert: - expect(address.isValidAddress(decoded, NetworkType.MIJIN_TEST)).to.equal(true); + expect(address.isValidAddress(decoded)).to.equal(true); }); it('returns false for address with invalid checksum', () => { @@ -163,7 +167,7 @@ describe('address', () => { decoded[Address_Decoded_Size - 1] ^= 0xff; // ruin checksum // Assert: - expect(address.isValidAddress(decoded, NetworkType.MIJIN_TEST)).to.equal(false); + expect(address.isValidAddress(decoded)).to.equal(false); }); it('returns false for address with invalid hash', () => { @@ -173,7 +177,15 @@ describe('address', () => { decoded[5] ^= 0xff; // ruin ripemd160 hash // Assert: - expect(address.isValidAddress(decoded, NetworkType.MIJIN_TEST)).to.equal(false); + expect(address.isValidAddress(decoded)).to.equal(false); + }); + + it('returns false for address with invalid length', () => { + // Arrange: + const validHex = '6823BB7C3C089D996585466380EDBDC19D4959184893E38CA6AABB'; + const decoded = convert.hexToUint8(validHex); + // Assert: + expect(address.isValidAddress(decoded)).to.equal(false); }); }); @@ -208,8 +220,7 @@ describe('address', () => { const expectedAddress = Addresses[i]; // Act: - const result = address.addressToString( - address.publicKeyToAddress(convert.hexToUint8(publicKeyHex), NetworkType.MAIN_NET)); + const result = address.addressToString(address.publicKeyToAddress(convert.hexToUint8(publicKeyHex), NetworkType.MAIN_NET)); // Assert: const message = ` from ${publicKeyHex}`; @@ -249,8 +260,7 @@ describe('address', () => { const expectedAddress = Addresses[i]; // Act: - const result = address.addressToString( - address.publicKeyToAddress(convert.hexToUint8(publicKeyHex), NetworkType.TEST_NET)); + const result = address.addressToString(address.publicKeyToAddress(convert.hexToUint8(publicKeyHex), NetworkType.TEST_NET)); // Assert: const message = ` from ${publicKeyHex}`; @@ -290,8 +300,7 @@ describe('address', () => { const expectedAddress = Addresses[i]; // Act: - const result = address.addressToString( - address.publicKeyToAddress(convert.hexToUint8(publicKeyHex), NetworkType.MIJIN)); + const result = address.addressToString(address.publicKeyToAddress(convert.hexToUint8(publicKeyHex), NetworkType.MIJIN)); // Assert: const message = ` from ${publicKeyHex}`; @@ -332,7 +341,8 @@ describe('address', () => { // Act: const result = address.addressToString( - address.publicKeyToAddress(convert.hexToUint8(publicKeyHex), NetworkType.MIJIN_TEST)); + address.publicKeyToAddress(convert.hexToUint8(publicKeyHex), NetworkType.MIJIN_TEST), + ); // Assert: const message = ` from ${publicKeyHex}`; diff --git a/test/core/format/RawArray.spec.ts b/test/core/format/RawArray.spec.ts index dc8bfe1e9b..3d483afc4e 100644 --- a/test/core/format/RawArray.spec.ts +++ b/test/core/format/RawArray.spec.ts @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import { Convert as convert, RawArray as array} from '../../../src/core/format'; +import { expect } from 'chai'; +import { Convert as convert, RawArray as array } from '../../../src/core/format'; describe('array', () => { describe('uint8View', () => { @@ -108,7 +108,7 @@ describe('array', () => { expect(isZero).to.equal(true); }); - function assertIsNonZero(length, nonZeroOffset) { + function assertIsNonZero(length, nonZeroOffset): void { // Arrange: const src = new Uint16Array(length); src[nonZeroOffset] = 2; @@ -155,11 +155,11 @@ describe('array', () => { expect(isEqual2).to.equal(false); }); - function assertNotEqual(lhs, unequalOffset) { + function assertNotEqual(lhs, unequalOffset): void { // Arrange: const rhs = new Uint8Array(lhs.length); array.copy(rhs, lhs); - rhs[unequalOffset] ^= 0xFF; + rhs[unequalOffset] ^= 0xff; // Act const isEqual = array.deepEqual(lhs, rhs); diff --git a/test/core/format/RawUInt64.spec.ts b/test/core/format/RawUInt64.spec.ts index 5397d037fe..ce8c12fcc5 100644 --- a/test/core/format/RawUInt64.spec.ts +++ b/test/core/format/RawUInt64.spec.ts @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { - expect, -} from 'chai'; -import { Convert as convert, RawUInt64 as uint64} from '../../../src/core/format'; +import { expect } from 'chai'; +import { Convert as convert, RawUInt64 as uint64 } from '../../../src/core/format'; describe('uint64', () => { describe('compact', () => { @@ -30,18 +28,18 @@ describe('uint64', () => { it('can compact less than max safe integer', () => { // Act: - const result = uint64.compact([0x00ABCDEF, 0x000FDFFF]); + const result = uint64.compact([0x00abcdef, 0x000fdfff]); // Assert: - expect(result).to.equal(0xFDFFF00ABCDEF); + expect(result).to.equal(0xfdfff00abcdef); }); it('can compact max safe integer', () => { // Sanity: - expect(0x1FFFFFFFFFFFFF).to.equal(Number.MAX_SAFE_INTEGER); + expect(0x1fffffffffffff).to.equal(Number.MAX_SAFE_INTEGER); // Act: - const result = uint64.compact([0xFFFFFFFF, 0x001FFFFF]); + const result = uint64.compact([0xffffffff, 0x001fffff]); // Assert: expect(result).to.equal(Number.MAX_SAFE_INTEGER); @@ -60,10 +58,10 @@ describe('uint64', () => { it('cannot compact greater than min unsafe integer', () => { // Act: - const result = uint64.compact([0xF0000000, 0x01000D00]); + const result = uint64.compact([0xf0000000, 0x01000d00]); // Assert: - expect(result).to.deep.equal([0xF0000000, 0x01000D00]); + expect(result).to.deep.equal([0xf0000000, 0x01000d00]); }); }); @@ -82,14 +80,15 @@ describe('uint64', () => { // }); // }); - const successTestCases = [{ + const successTestCases = [ + { number: 0, uint64: [0, 0], description: '0', }, { - number: 0xA1B2, - uint64: [0xA1B2, 0], + number: 0xa1b2, + uint64: [0xa1b2, 0], description: '(0, 8)', }, { @@ -98,18 +97,18 @@ describe('uint64', () => { description: '8', }, { - number: 0xABCD12345678, - uint64: [0x12345678, 0xABCD], + number: 0xabcd12345678, + uint64: [0x12345678, 0xabcd], description: '(8, 16)', }, { - number: 0x0014567890ABCDEF, - uint64: [0x90ABCDEF, 0x00145678], + number: 0x0014567890abcdef, + uint64: [0x90abcdef, 0x00145678], description: '14', }, { number: Number.MAX_SAFE_INTEGER, - uint64: [0xFFFFFFFF, 0x001FFFFF], + uint64: [0xffffffff, 0x001fffff], description: '14 (max value)', }, ]; @@ -125,14 +124,15 @@ describe('uint64', () => { }); }); - const hexTestCases = [{ + const hexTestCases = [ + { str: '0000000000000000', value: [0, 0], description: '0', }, { str: '000000000000A1B2', - value: [0xA1B2, 0], + value: [0xa1b2, 0], description: '(0, 8)', }, { @@ -142,17 +142,17 @@ describe('uint64', () => { }, { str: '0000ABCD12345678', - value: [0x12345678, 0xABCD], + value: [0x12345678, 0xabcd], description: '(8, 16)', }, { str: '1234567890ABCDEF', - value: [0x90ABCDEF, 0x12345678], + value: [0x90abcdef, 0x12345678], description: '16', }, { str: 'FFFFFFFFFFFFFFFF', - value: [0xFFFFFFFF, 0xFFFFFFFF], + value: [0xffffffff, 0xffffffff], description: '16 (max value)', }, ]; @@ -185,14 +185,15 @@ describe('uint64', () => { }); describe('fromBytes32', () => { - const fromBytes32TestCases = [{ + const fromBytes32TestCases = [ + { str: '00000000', value: [0, 0], description: '0', }, { str: '0000A1B2', - value: [0xA1B2, 0], + value: [0xa1b2, 0], description: '(0, 8)', }, { @@ -202,7 +203,7 @@ describe('uint64', () => { }, { str: 'FFFFFFFF', - value: [0xFFFFFFFF, 0], + value: [0xffffffff, 0], description: '8 (max value)', }, ]; @@ -284,7 +285,8 @@ describe('uint64', () => { }); describe('isZero', () => { - const zeroTestCases = [{ + const zeroTestCases = [ + { description: 'low and high are zero', value: [0, 0], isZero: true, diff --git a/test/core/format/Utilities.spec.ts b/test/core/format/Utilities.spec.ts index 26fa600e4a..11378ba0a6 100644 --- a/test/core/format/Utilities.spec.ts +++ b/test/core/format/Utilities.spec.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; +import { expect } from 'chai'; import * as utilities from '../../../src/core/format/Utilities'; describe('Char Mapping', () => { @@ -107,7 +107,7 @@ describe('Char Mapping', () => { describe('Convert', () => { describe('tryParseUint', () => { - function addTryParseSuccessTest(name, str, expectedValue) { + function addTryParseSuccessTest(name, str, expectedValue): void { it(name, () => { // Act: const value = utilities.tryParseUint(str); @@ -123,7 +123,7 @@ describe('Convert', () => { addTryParseSuccessTest('can parse decimal string with zeros', '10002', 10002); addTryParseSuccessTest('can parse max safe integer decimal string', Number.MAX_SAFE_INTEGER.toString(), 9007199254740991); - function addTryParseFailureTest(name, str) { + function addTryParseFailureTest(name, str): void { it(name, () => { // Act: const value = utilities.tryParseUint(str); diff --git a/test/core/utils/Hashes.spec.ts b/test/core/utils/Hashes.spec.ts new file mode 100644 index 0000000000..82ae339190 --- /dev/null +++ b/test/core/utils/Hashes.spec.ts @@ -0,0 +1,131 @@ +/* + * Copyright 2019 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { expect } from 'chai'; +import { Crypto } from '../../../src/core/crypto'; +import { sha3_256 } from 'js-sha3'; +import { LockHashUtils } from '../../../src/core/utils/LockHashUtils'; +import { LockHashAlgorithm } from '../../../src/model/transaction/LockHashAlgorithm'; +import { Convert } from '../../../src/core/format/Convert'; + +describe('Hashes', () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const ripemd160 = require('ripemd160'); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const sha256 = require('js-sha256'); + + it('Op_Sha3_256', () => { + const secretSeed = Crypto.randomBytes(20); + const expected = sha3_256.create().update(secretSeed).hex(); + const hash = LockHashUtils.Op_Sha3_256(secretSeed); + expect(expected.toUpperCase()).to.be.equal(hash); + }); + + it('Op_Sha_256', () => { + const randomBytes = Crypto.randomBytes(32); + const secretSeed = randomBytes.toString('hex'); + const hash256 = sha256(Buffer.from(secretSeed, 'hex')); + const expected = sha256(Buffer.from(hash256, 'hex')); + const hash = LockHashUtils.Op_Hash_256(randomBytes); + expect(expected.toUpperCase()).to.be.equal(hash); + }); + + it('Op_Hash_160', () => { + const secretSeed = Crypto.randomBytes(20); + const hash256 = sha256(Buffer.from(secretSeed, 'hex')); + const expected = new ripemd160().update(Buffer.from(hash256, 'hex')).digest('hex'); + + const hash = LockHashUtils.Op_Hash_160(secretSeed); + expect(expected.toUpperCase()).to.be.equal(hash); + }); + + it('Hash', () => { + const secretSeed = Crypto.randomBytes(20); + + const expectedSHA3 = sha3_256.create().update(secretSeed).hex(); + const hashSHA3 = LockHashUtils.Hash(LockHashAlgorithm.Op_Sha3_256, secretSeed); + expect(expectedSHA3.toUpperCase()).to.be.equal(hashSHA3); + + const h256 = sha256(Buffer.from(secretSeed, 'hex')); + const expected256 = sha256(Buffer.from(h256, 'hex')); + const hash256 = LockHashUtils.Hash(LockHashAlgorithm.Op_Hash_256, secretSeed); + expect(expected256.toUpperCase()).to.be.equal(hash256); + + const expected160 = new ripemd160().update(Buffer.from(h256, 'hex')).digest('hex'); + const hash160 = LockHashUtils.Hash(LockHashAlgorithm.Op_Hash_160, secretSeed); + expect(expected160.toUpperCase()).to.be.equal(hash160); + }); + + it('Hash with error', () => { + expect(() => { + LockHashUtils.Hash(100, Crypto.randomBytes(20)); + }).to.throw(Error, 'HashAlgorithm is invalid.'); + }); +}); + +describe('Hashes - static vector', () => { + const inputs = [ + '', + 'CC', + '41FB', + '1F877C', + 'C1ECFDFC', + '9F2FCC7C90DE090D6B87CD7E9718C1EA6CB21118FC2D5DE9F97E5DB6AC1E9C10', + '414243442C31322C34353637', + ]; + + const expectedSHA3_256 = [ + 'A7FFC6F8BF1ED76651C14756A061D662F580FF4DE43B49FA82D80A4B80F8434A', + '677035391CD3701293D385F037BA32796252BB7CE180B00B582DD9B20AAAD7F0', + '39F31B6E653DFCD9CAED2602FD87F61B6254F581312FB6EEEC4D7148FA2E72AA', + 'BC22345E4BD3F792A341CF18AC0789F1C9C966712A501B19D1B6632CCD408EC5', + 'C5859BE82560CC8789133F7C834A6EE628E351E504E601E8059A0667FF62C124', + '2F1A5F7159E34EA19CDDC70EBF9B81F1A66DB40615D7EAD3CC1F1B954D82A3AF', + 'BBB389B70F13B89A0D544D87E9BF6AC981FC1744EB6AB808A7FF3ECF7FB6A3B9', + ]; + + const expectedHash_256 = [ + '5DF6E0E2761359D30A8275058E299FCC0381534545F55CF43E41983F5D4C9456', + '796A3E4EAC5A2BD225C147EE5F358B75255F9782E46DDDA286A2139398A23FB7', + '7664A1EA2BED912F7A1F8A9B8D760BDBD479BFE80B603F0ADACCFE124051D39F', + '67CC26E4B3534A4EC6E5973BF8A2FFA8C0DAAEFAEDB984A3B4A15930E0091418', + 'DEA31FB4B63E158E92037CE6C9696EEE4344FAAB22808A00FF5B94A7FDC1CFA0', + 'ABED1BA808548F4FD0D239C8BA4840C81F52F91C7D8E6543D40ADE934DC7D886', + 'E6173EF758919BEC5F9FA28A6C28133D791D3C17C0D79AB10E449D5B4CBB453A', + ]; + + const expectedHash_160 = [ + 'B472A266D0BD89C13706A4132CCFB16F7C3B9FCB', + '59CC35F8C8D91867717CE4290B40EA636E86CE5C', + 'BE254D2744329BBE20F9CF6DA61043B4CEF8C2BC', + '5ACCBEB2A17F9257E769D9636BB3FE21B9F98531', + 'C849C5A5F6BCA84EF1829B2A84C0BAC9D765383D', + 'C7B080DF005A269059B68DE318BE136396B02948', + '76A380402DE6B84B170AB433A96C6B1E0DE05AF0', + ]; + + it('Test', () => { + for (let i = 0; i < inputs.length; i++) { + const hashSHA3 = LockHashUtils.Hash(LockHashAlgorithm.Op_Sha3_256, Convert.hexToUint8(inputs[i])); + expect(hashSHA3).to.be.equal(expectedSHA3_256[i]); + + const hash256 = LockHashUtils.Hash(LockHashAlgorithm.Op_Hash_256, Convert.hexToUint8(inputs[i])); + expect(hash256).to.be.equal(expectedHash_256[i]); + + const hash160 = LockHashUtils.Hash(LockHashAlgorithm.Op_Hash_160, Convert.hexToUint8(inputs[i])); + expect(hash160).to.be.equal(expectedHash_160[i]); + } + }); +}); diff --git a/test/core/utils/TransactionMapping.spec.ts b/test/core/utils/TransactionMapping.spec.ts index e161b42e75..860ace4ca4 100644 --- a/test/core/utils/TransactionMapping.spec.ts +++ b/test/core/utils/TransactionMapping.spec.ts @@ -35,7 +35,6 @@ import { AliasAction } from '../../../src/model/namespace/AliasAction'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; import { NamespaceRegistrationType } from '../../../src/model/namespace/NamespaceRegistrationType'; import { NetworkType } from '../../../src/model/network/NetworkType'; -import { AccountRestrictionModificationAction } from '../../../src/model/restriction/AccountRestrictionModificationAction'; import { AccountRestrictionFlags } from '../../../src/model/restriction/AccountRestrictionType'; import { MosaicRestrictionType } from '../../../src/model/restriction/MosaicRestrictionType'; import { AccountAddressRestrictionTransaction } from '../../../src/model/transaction/AccountAddressRestrictionTransaction'; @@ -43,12 +42,11 @@ import { AccountLinkTransaction } from '../../../src/model/transaction/AccountLi import { AccountMetadataTransaction } from '../../../src/model/transaction/AccountMetadataTransaction'; import { AccountMosaicRestrictionTransaction } from '../../../src/model/transaction/AccountMosaicRestrictionTransaction'; import { AccountOperationRestrictionTransaction } from '../../../src/model/transaction/AccountOperationRestrictionTransaction'; -import { AccountRestrictionModification } from '../../../src/model/transaction/AccountRestrictionModification'; import { AccountRestrictionTransaction } from '../../../src/model/transaction/AccountRestrictionTransaction'; import { AddressAliasTransaction } from '../../../src/model/transaction/AddressAliasTransaction'; import { AggregateTransaction } from '../../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../../src/model/transaction/Deadline'; -import { HashType } from '../../../src/model/transaction/HashType'; +import { LockHashAlgorithm } from '../../../src/model/transaction/LockHashAlgorithm'; import { LinkAction } from '../../../src/model/transaction/LinkAction'; import { LockFundsTransaction } from '../../../src/model/transaction/LockFundsTransaction'; import { MosaicAddressRestrictionTransaction } from '../../../src/model/transaction/MosaicAddressRestrictionTransaction'; @@ -76,10 +74,6 @@ describe('TransactionMapping - createFromPayload', () => { it('should create AccountRestrictionAddressTransaction', () => { const address = Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); - const addressRestrictionFilter = AccountRestrictionModification.createForAddress( - AccountRestrictionModificationAction.Add, - address, - ); const addressRestrictionTransaction = AccountRestrictionTransaction.createAddressRestrictionModificationTransaction( Deadline.create(), AccountRestrictionFlags.AllowIncomingAddress, @@ -90,8 +84,7 @@ describe('TransactionMapping - createFromPayload', () => { const signedTransaction = addressRestrictionTransaction.signWith(account, generationHash); - const transaction = TransactionMapping - .createFromPayload(signedTransaction.payload) as AccountAddressRestrictionTransaction; + const transaction = TransactionMapping.createFromPayload(signedTransaction.payload) as AccountAddressRestrictionTransaction; expect(transaction.restrictionFlags).to.be.equal(AccountRestrictionFlags.AllowIncomingAddress); expect((transaction.restrictionAdditions[0] as Address).plain()).to.be.equal('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); @@ -110,8 +103,7 @@ describe('TransactionMapping - createFromPayload', () => { const signedTransaction = mosaicRestrictionTransaction.signWith(account, generationHash); - const transaction = TransactionMapping - .createFromPayload(signedTransaction.payload) as AccountMosaicRestrictionTransaction; + const transaction = TransactionMapping.createFromPayload(signedTransaction.payload) as AccountMosaicRestrictionTransaction; expect(transaction.restrictionFlags).to.be.equal(AccountRestrictionFlags.AllowMosaic); expect((transaction.restrictionAdditions[0] as MosaicId).toHex()).to.be.equal(mosaicId.toHex()); expect(transaction.restrictionDeletions.length).to.be.equal(0); @@ -129,8 +121,7 @@ describe('TransactionMapping - createFromPayload', () => { const signedTransaction = operationRestrictionTransaction.signWith(account, generationHash); - const transaction = TransactionMapping - .createFromPayload(signedTransaction.payload) as AccountOperationRestrictionTransaction; + const transaction = TransactionMapping.createFromPayload(signedTransaction.payload) as AccountOperationRestrictionTransaction; expect(transaction.restrictionFlags).to.be.equal(AccountRestrictionFlags.AllowIncomingTransactionType); expect(transaction.restrictionAdditions[0]).to.be.equal(operation); expect(transaction.restrictionDeletions.length).to.be.equal(0); @@ -167,22 +158,21 @@ describe('TransactionMapping - createFromPayload', () => { mosaicId, NetworkType.MIJIN_TEST, ); + const signedTransaction = mosaicAliasTransaction.signWith(account, generationHash); const transaction = TransactionMapping.createFromPayload(signedTransaction.payload) as MosaicAliasTransaction; - - expect(mosaicAliasTransaction.aliasAction).to.be.equal(AliasAction.Link); - expect(mosaicAliasTransaction.namespaceId.id.lower).to.be.equal(33347626); - expect(mosaicAliasTransaction.namespaceId.id.higher).to.be.equal(3779697293); - expect(mosaicAliasTransaction.mosaicId.id.lower).to.be.equal(2262289484); - expect(mosaicAliasTransaction.mosaicId.id.higher).to.be.equal(3405110546); - + expect(transaction.aliasAction).to.be.equal(AliasAction.Link); + expect(transaction.namespaceId.id.lower).to.be.equal(33347626); + expect(transaction.namespaceId.id.higher).to.be.equal(3779697293); + expect(transaction.mosaicId.id.lower).to.be.equal(2262289484); + expect(transaction.mosaicId.id.higher).to.be.equal(3405110546); }); it('should create MosaicDefinitionTransaction', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, @@ -200,13 +190,12 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.flags.supplyMutable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); expect(transaction.flags.restrictable).to.be.equal(false); - }); it('should create MosaicDefinitionTransaction - without duration', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, @@ -222,13 +211,12 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.flags.supplyMutable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); expect(transaction.flags.restrictable).to.be.equal(false); - }); it('should create MosaicDefinitionTransaction - without duration', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, @@ -244,13 +232,12 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.flags.supplyMutable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); - }); it('should create MosaicDefinitionTransaction - without duration', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, @@ -266,13 +253,12 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.flags.supplyMutable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); - }); it('should create MosaicDefinitionTransaction - without duration', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, @@ -288,7 +274,6 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.flags.supplyMutable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); - }); it('should create MosaicSupplyChangeTransaction', () => { @@ -310,16 +295,13 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.delta.higher).to.be.equal(0); expect(transaction.mosaicId.id.lower).to.be.equal(2262289484); expect(transaction.mosaicId.id.higher).to.be.equal(3405110546); - }); it('should create TransferTransaction', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); @@ -331,7 +313,6 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.message.payload).to.be.equal('test-message'); expect(transaction.mosaics.length).to.be.equal(1); expect(transaction.recipientToString()).to.be.equal('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); - }); it('should create SecretLockTransaction', () => { @@ -341,7 +322,7 @@ describe('TransactionMapping - createFromPayload', () => { Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, @@ -353,17 +334,16 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.mosaic.amount.equals(UInt64.fromUint(10))).to.be.equal(true); expect(transaction.duration.equals(UInt64.fromUint(100))).to.be.equal(true); - expect(transaction.hashType).to.be.equal(0); + expect(transaction.hashAlgorithm).to.be.equal(0); expect(transaction.secret).to.be.equal('9B3155B37159DA50AA52D5967C509B410F5A36A3B1E31ECB5AC76675D79B4A5E'); expect((transaction.recipientAddress as Address).plain()).to.be.equal(recipientAddress.plain()); - }); it('should create SecretProofTransaction', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Convert.hexToUint8(proof)).hex(), account.address, proof, @@ -371,13 +351,12 @@ describe('TransactionMapping - createFromPayload', () => { ); const signedTransaction = secretProofTransaction.signWith(account, generationHash); - const transaction = TransactionMapping.createFromPayload(signedTransaction.payload) as SecretProofTransaction; - - expect(secretProofTransaction.hashType).to.be.equal(0); - expect(secretProofTransaction.secret).to.be.equal('9b3155b37159da50aa52d5967c509b410f5a36a3b1e31ecb5ac76675d79b4a5e' ); - expect(secretProofTransaction.proof).to.be.equal(proof); - expect((secretProofTransaction.recipientAddress as Address).plain()).to.be.equal(account.address.plain()); + const transaction = TransactionMapping.createFromPayload(signedTransaction.payload) as SecretProofTransaction; + expect(transaction.hashAlgorithm).to.be.equal(0); + expect(transaction.secret).to.be.equal('9B3155B37159DA50AA52D5967C509B410F5A36A3B1E31ECB5AC76675D79B4A5E'); + expect(transaction.proof).to.be.equal(proof); + expect((transaction.recipientAddress as Address).plain()).to.be.equal(account.address.plain()); }); it('should create ModifyMultiSigTransaction', () => { @@ -385,8 +364,7 @@ describe('TransactionMapping - createFromPayload', () => { Deadline.create(), 2, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST)], + [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', NetworkType.MIJIN_TEST)], [], NetworkType.MIJIN_TEST, ); @@ -395,14 +373,10 @@ describe('TransactionMapping - createFromPayload', () => { const transaction = TransactionMapping.createFromPayload(signedTransaction.payload) as MultisigAccountModificationTransaction; - expect(transaction.minApprovalDelta) - .to.be.equal(2); - expect(transaction.minRemovalDelta) - .to.be.equal(1); - expect(transaction.publicKeyAdditions[0].publicKey) - .to.be.equal('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24'); - expect(transaction.publicKeyDeletions.length) - .to.be.equal(0); + expect(transaction.minApprovalDelta).to.be.equal(2); + expect(transaction.minRemovalDelta).to.be.equal(1); + expect(transaction.publicKeyAdditions[0].publicKey).to.be.equal('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24'); + expect(transaction.publicKeyDeletions.length).to.be.equal(0); }); it('should create AggregatedTransaction - Complete', () => { @@ -414,11 +388,98 @@ describe('TransactionMapping - createFromPayload', () => { NetworkType.MIJIN_TEST, ); + const accountLinkTransaction = AccountLinkTransaction.create( + Deadline.create(), + account.publicKey, + LinkAction.Link, + NetworkType.MIJIN_TEST, + ); + const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace( + Deadline.create(), + 'root-test-namespace', + UInt64.fromUint(1000), + NetworkType.MIJIN_TEST, + ); + const mosaicGlobalRestrictionTransaction = MosaicGlobalRestrictionTransaction.create( + Deadline.create(), + new MosaicId(UInt64.fromUint(1).toDTO()), + UInt64.fromUint(4444), + UInt64.fromUint(0), + MosaicRestrictionType.NONE, + UInt64.fromUint(0), + MosaicRestrictionType.GE, + NetworkType.MIJIN_TEST, + ); + const mosaicAddressRestrictionTransaction = MosaicAddressRestrictionTransaction.create( + Deadline.create(), + new NamespaceId('test'), + UInt64.fromUint(4444), + account.address, + UInt64.fromUint(0), + NetworkType.MIJIN_TEST, + UInt64.fromUint(0), + ); + const accountMetadataTransaction = AccountMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(1000), + 1, + Convert.uint8ToUtf8(new Uint8Array(10)), + NetworkType.MIJIN_TEST, + ); + const mosaicMetadataTransaction = MosaicMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(1000), + new MosaicId([2262289484, 3405110546]), + 1, + Convert.uint8ToUtf8(new Uint8Array(10)), + NetworkType.MIJIN_TEST, + ); + const namespaceMetadataTransaction = NamespaceMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(1000), + new NamespaceId([2262289484, 3405110546]), + 1, + Convert.uint8ToUtf8(new Uint8Array(10)), + NetworkType.MIJIN_TEST, + ); + + const mosaicAliasTransaction = MosaicAliasTransaction.create( + Deadline.create(), + AliasAction.Link, + new NamespaceId([2262289484, 3405110546]), + new MosaicId([2262289484, 3405110546]), + NetworkType.MIJIN_TEST, + ); + + const secretProofTransaction = SecretProofTransaction.create( + Deadline.create(), + LockHashAlgorithm.Op_Sha3_256, + sha3_256.create().update(Convert.hexToUint8('B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7')).hex(), + account.address, + 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7', + NetworkType.MIJIN_TEST, + ); + const aggregateTransaction = AggregateTransaction.createComplete( Deadline.create(), - [transferTransaction.toAggregate(account.publicAccount)], + [ + transferTransaction.toAggregate(account.publicAccount), + accountLinkTransaction.toAggregate(account.publicAccount), + registerNamespaceTransaction.toAggregate(account.publicAccount), + mosaicGlobalRestrictionTransaction.toAggregate(account.publicAccount), + mosaicAddressRestrictionTransaction.toAggregate(account.publicAccount), + mosaicMetadataTransaction.toAggregate(account.publicAccount), + namespaceMetadataTransaction.toAggregate(account.publicAccount), + accountMetadataTransaction.toAggregate(account.publicAccount), + mosaicAliasTransaction.toAggregate(account.publicAccount), + secretProofTransaction.toAggregate(account.publicAccount), + ], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); @@ -426,6 +487,7 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.type).to.be.equal(TransactionType.AGGREGATE_COMPLETE); expect(transaction.innerTransactions[0].type).to.be.equal(TransactionType.TRANSFER); + expect(transaction.innerTransactions.length).to.be.greaterThan(0); }); it('should create AggregatedTransaction - Bonded', () => { @@ -441,7 +503,8 @@ describe('TransactionMapping - createFromPayload', () => { Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); @@ -452,18 +515,15 @@ describe('TransactionMapping - createFromPayload', () => { }); it('should create LockFundTransaction', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockTransaction = LockFundsTransaction.create(Deadline.create(), + const lockTransaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, + ); const signedLockFundTransaction = lockTransaction.signWith(account, generationHash); @@ -503,7 +563,6 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.registrationType).to.be.equal(NamespaceRegistrationType.RootNamespace); expect(transaction.namespaceName).to.be.equal('root-test-namespace'); - }); it('should create NamespaceRegistrationTransaction - Sub', () => { @@ -660,6 +719,23 @@ describe('TransactionMapping - createFromPayload', () => { expect(transaction.targetNamespaceId.toHex()).to.be.equal(new NamespaceId([2262289484, 3405110546]).toHex()); expect(Convert.uint8ToHex(transaction.value)).to.be.equal(Convert.uint8ToHex(new Uint8Array(10))); }); + + it('should throw error with invalid type', () => { + const transferTransaction = TransferTransaction.create( + Deadline.create(), + Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), + [NetworkCurrencyLocal.createRelative(100)], + PlainMessage.create('test-message'), + NetworkType.MIJIN_TEST, + ); + + const signedTransaction = transferTransaction.signWith(account, generationHash); + const wrongType = signedTransaction.payload.substring(0, 219) + '0000' + signedTransaction.payload.substring(224); + + expect(() => { + TransactionMapping.createFromPayload(wrongType) as TransferTransaction; + }).to.throw(); + }); }); describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => { @@ -673,9 +749,7 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => const transferTransaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); @@ -690,16 +764,15 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => const transferTransaction = TransferTransaction.create( Deadline.create(), new NamespaceId([33347626, 3779697293]), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); const transaction = TransactionMapping.createFromDTO(transferTransaction.toJSON()) as TransferTransaction; - expect((transaction.recipientAddress as NamespaceId).id.toHex().toUpperCase()) - .to.be.equal(new UInt64([33347626, 3779697293]).toHex()); + expect((transaction.recipientAddress as NamespaceId).id.toHex().toUpperCase()).to.be.equal( + new UInt64([33347626, 3779697293]).toHex(), + ); expect(transaction.message.payload).to.be.equal('test-message'); }); @@ -707,9 +780,7 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => const transferTransaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], new EncryptedMessage('12324556'), NetworkType.MIJIN_TEST, ); @@ -744,8 +815,9 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(addressRestrictionTransaction.toJSON()) as AccountAddressRestrictionTransaction; + const transaction = TransactionMapping.createFromDTO( + addressRestrictionTransaction.toJSON(), + ) as AccountAddressRestrictionTransaction; expect((transaction.restrictionAdditions[0] as Address).plain()).to.be.equal('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); expect(transaction.restrictionFlags).to.be.equal(AccountRestrictionFlags.AllowIncomingAddress); @@ -762,8 +834,7 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(mosaicRestrictionTransaction.toJSON()) as AccountMosaicRestrictionTransaction; + const transaction = TransactionMapping.createFromDTO(mosaicRestrictionTransaction.toJSON()) as AccountMosaicRestrictionTransaction; expect(transaction.type).to.be.equal(TransactionType.ACCOUNT_MOSAIC_RESTRICTION); expect(transaction.restrictionFlags).to.be.equal(AccountRestrictionFlags.AllowMosaic); @@ -780,8 +851,9 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(operationRestrictionTransaction.toJSON()) as AccountMosaicRestrictionTransaction; + const transaction = TransactionMapping.createFromDTO( + operationRestrictionTransaction.toJSON(), + ) as AccountMosaicRestrictionTransaction; expect(transaction.type).to.be.equal(TransactionType.ACCOUNT_OPERATION_RESTRICTION); expect(transaction.restrictionFlags).to.be.equal(AccountRestrictionFlags.AllowIncomingTransactionType); @@ -799,8 +871,7 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(addressAliasTransaction.toJSON()) as AddressAliasTransaction; + const transaction = TransactionMapping.createFromDTO(addressAliasTransaction.toJSON()) as AddressAliasTransaction; expect(transaction.type).to.be.equal(TransactionType.ADDRESS_ALIAS); expect(transaction.aliasAction).to.be.equal(AliasAction.Link); @@ -816,18 +887,16 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => mosaicId, NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(mosaicAliasTransaction.toJSON()) as MosaicAliasTransaction; + const transaction = TransactionMapping.createFromDTO(mosaicAliasTransaction.toJSON()) as MosaicAliasTransaction; expect(transaction.type).to.be.equal(TransactionType.MOSAIC_ALIAS); expect(transaction.aliasAction).to.be.equal(AliasAction.Link); - }); it('should create MosaicDefinitionTransaction', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, @@ -835,15 +904,13 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(mosaicDefinitionTransaction.toJSON()) as MosaicDefinitionTransaction; + const transaction = TransactionMapping.createFromDTO(mosaicDefinitionTransaction.toJSON()) as MosaicDefinitionTransaction; expect(transaction.type).to.be.equal(TransactionType.MOSAIC_DEFINITION); expect(transaction.flags.supplyMutable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); expect(transaction.flags.transferable).to.be.equal(false); expect(transaction.divisibility).to.be.equal(3); - }); it('should create MosaicSupplyChangeTransaction', () => { @@ -856,12 +923,10 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(mosaicSupplyChangeTransaction.toJSON()) as MosaicSupplyChangeTransaction; + const transaction = TransactionMapping.createFromDTO(mosaicSupplyChangeTransaction.toJSON()) as MosaicSupplyChangeTransaction; expect(transaction.type).to.be.equal(TransactionType.MOSAIC_SUPPLY_CHANGE); expect(transaction.action).to.be.equal(MosaicSupplyChangeAction.Increase); - }); it('should create SecretLockTransaction', () => { @@ -871,18 +936,16 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(secretLockTransaction.toJSON()) as SecretLockTransaction; + const transaction = TransactionMapping.createFromDTO(secretLockTransaction.toJSON()) as SecretLockTransaction; expect(transaction.type).to.be.equal(TransactionType.SECRET_LOCK); - expect(transaction.hashType).to.be.equal(HashType.Op_Sha3_256); - + expect(transaction.hashAlgorithm).to.be.equal(LockHashAlgorithm.Op_Sha3_256); }); it('should create SecretLockTransaction - Address alias', () => { @@ -892,64 +955,57 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(secretLockTransaction.toJSON()) as SecretLockTransaction; + const transaction = TransactionMapping.createFromDTO(secretLockTransaction.toJSON()) as SecretLockTransaction; expect(transaction.type).to.be.equal(TransactionType.SECRET_LOCK); - expect(transaction.hashType).to.be.equal(HashType.Op_Sha3_256); + expect(transaction.hashAlgorithm).to.be.equal(LockHashAlgorithm.Op_Sha3_256); expect((transaction.recipientAddress as NamespaceId).id.toHex()).to.be.equal(recipientAddress.toHex()); - }); it('should create SecretLockTransaction - resolved Mosaic', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); - const mosaicId = new NamespaceId('test'); const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), new Mosaic(new MosaicId([1, 1]), UInt64.fromUint(10)), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(secretLockTransaction.toJSON()) as SecretLockTransaction; + const transaction = TransactionMapping.createFromDTO(secretLockTransaction.toJSON()) as SecretLockTransaction; expect(transaction.type).to.be.equal(TransactionType.SECRET_LOCK); - expect(transaction.hashType).to.be.equal(HashType.Op_Sha3_256); - expect(transaction.mosaic.id.toHex()).to.be.equal((new MosaicId([1, 1])).toHex()); - + expect(transaction.hashAlgorithm).to.be.equal(LockHashAlgorithm.Op_Sha3_256); + expect(transaction.mosaic.id.toHex()).to.be.equal(new MosaicId([1, 1]).toHex()); }); it('should create SecretProofTransaction', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Convert.hexToUint8(proof)).hex(), account.address, proof, NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(secretProofTransaction.toJSON()) as SecretProofTransaction; + const transaction = TransactionMapping.createFromDTO(secretProofTransaction.toJSON()) as SecretProofTransaction; expect(transaction.type).to.be.equal(TransactionType.SECRET_PROOF); - expect(transaction.hashType).to.be.equal(HashType.Op_Sha3_256); + expect(transaction.hashAlgorithm).to.be.equal(LockHashAlgorithm.Op_Sha3_256); expect(transaction.secret).to.be.equal(sha3_256.create().update(Convert.hexToUint8(proof)).hex()); deepEqual(transaction.recipientAddress, account.address); expect(transaction.proof).to.be.equal(proof); - }); it('should create SecretProofTransaction - Address alias', () => { @@ -957,22 +1013,20 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => const recipientAddress = new NamespaceId('test'); const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(Convert.hexToUint8(proof)).hex(), recipientAddress, proof, NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(secretProofTransaction.toJSON()) as SecretProofTransaction; + const transaction = TransactionMapping.createFromDTO(secretProofTransaction.toJSON()) as SecretProofTransaction; expect(transaction.type).to.be.equal(TransactionType.SECRET_PROOF); - expect(transaction.hashType).to.be.equal(HashType.Op_Sha3_256); + expect(transaction.hashAlgorithm).to.be.equal(LockHashAlgorithm.Op_Sha3_256); expect(transaction.secret).to.be.equal(sha3_256.create().update(Convert.hexToUint8(proof)).hex()); expect(transaction.proof).to.be.equal(proof); expect((transaction.recipientAddress as NamespaceId).id.toHex()).to.be.equal(recipientAddress.toHex()); - }); it('should create ModifyMultiSigTransaction', () => { @@ -980,14 +1034,14 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => Deadline.create(), 2, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST)], + [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', NetworkType.MIJIN_TEST)], [], NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(modifyMultisigAccountTransaction.toJSON()) as MultisigAccountModificationTransaction; + const transaction = TransactionMapping.createFromDTO( + modifyMultisigAccountTransaction.toJSON(), + ) as MultisigAccountModificationTransaction; expect(transaction.type).to.be.equal(TransactionType.MULTISIG_ACCOUNT_MODIFICATION); expect(transaction.minApprovalDelta).to.be.equal(2); @@ -1007,10 +1061,10 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); - const transaction = - TransactionMapping.createFromDTO(aggregateTransaction.toJSON()) as AggregateTransaction; + const transaction = TransactionMapping.createFromDTO(aggregateTransaction.toJSON()) as AggregateTransaction; expect(transaction.type).to.be.equal(TransactionType.AGGREGATE_COMPLETE); expect(transaction.innerTransactions.length).to.be.equal(1); @@ -1029,31 +1083,27 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); - const transaction = - TransactionMapping.createFromDTO(aggregateTransaction.toJSON()) as AggregateTransaction; + const transaction = TransactionMapping.createFromDTO(aggregateTransaction.toJSON()) as AggregateTransaction; expect(transaction.type).to.be.equal(TransactionType.AGGREGATE_BONDED); expect(transaction.innerTransactions.length).to.be.equal(1); }); it('should create LockFundTransaction', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockTransaction = LockFundsTransaction.create(Deadline.create(), + const lockTransaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, + ); - const transaction = - TransactionMapping.createFromDTO(lockTransaction.toJSON()) as LockFundsTransaction; + const transaction = TransactionMapping.createFromDTO(lockTransaction.toJSON()) as LockFundsTransaction; expect(transaction.type).to.be.equal(TransactionType.HASH_LOCK); expect(transaction.hash).to.be.equal(signedTransaction.hash); @@ -1067,11 +1117,9 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(registerNamespaceTransaction.toJSON()) as NamespaceRegistrationTransaction; + const transaction = TransactionMapping.createFromDTO(registerNamespaceTransaction.toJSON()) as NamespaceRegistrationTransaction; expect(transaction.type).to.be.equal(TransactionType.NAMESPACE_REGISTRATION); - }); it('should create NamespaceRegistrationTransaction - Sub', () => { @@ -1081,8 +1129,7 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => 'parent-test-namespace', NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(registerNamespaceTransaction.toJSON()) as NamespaceRegistrationTransaction; + const transaction = TransactionMapping.createFromDTO(registerNamespaceTransaction.toJSON()) as NamespaceRegistrationTransaction; expect(transaction.type).to.be.equal(TransactionType.NAMESPACE_REGISTRATION); }); @@ -1099,8 +1146,9 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(mosaicGlobalRestrictionTransaction.toJSON()) as MosaicGlobalRestrictionTransaction; + const transaction = TransactionMapping.createFromDTO( + mosaicGlobalRestrictionTransaction.toJSON(), + ) as MosaicGlobalRestrictionTransaction; expect(transaction.type).to.be.equal(TransactionType.MOSAIC_GLOBAL_RESTRICTION); expect(transaction.mosaicId.id.compact()).to.be.equal(1); @@ -1123,8 +1171,9 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => UInt64.fromUint(0), ); - const transaction = - TransactionMapping.createFromDTO(mosaicAddressRestrictionTransaction.toJSON()) as MosaicAddressRestrictionTransaction; + const transaction = TransactionMapping.createFromDTO( + mosaicAddressRestrictionTransaction.toJSON(), + ) as MosaicAddressRestrictionTransaction; expect(transaction.type).to.be.equal(TransactionType.MOSAIC_ADDRESS_RESTRICTION); expect(transaction.mosaicId.id.compact()).to.be.equal(1); @@ -1144,8 +1193,7 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(accountMetadataTransaction.toJSON()) as AccountMetadataTransaction; + const transaction = TransactionMapping.createFromDTO(accountMetadataTransaction.toJSON()) as AccountMetadataTransaction; expect(transaction.type).to.be.equal(TransactionType.ACCOUNT_METADATA); expect(transaction.targetPublicKey).to.be.equal(account.publicKey); @@ -1165,8 +1213,7 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(mosaicMetadataTransaction.toJSON()) as MosaicMetadataTransaction; + const transaction = TransactionMapping.createFromDTO(mosaicMetadataTransaction.toJSON()) as MosaicMetadataTransaction; expect(transaction.type).to.be.equal(TransactionType.MOSAIC_METADATA); expect(transaction.targetPublicKey).to.be.equal(account.publicKey); @@ -1187,8 +1234,7 @@ describe('TransactionMapping - createFromDTO (Transaction.toJSON() feed)', () => NetworkType.MIJIN_TEST, ); - const transaction = - TransactionMapping.createFromDTO(namespaceMetadataTransaction.toJSON()) as NamespaceMetadataTransaction; + const transaction = TransactionMapping.createFromDTO(namespaceMetadataTransaction.toJSON()) as NamespaceMetadataTransaction; expect(transaction.type).to.be.equal(TransactionType.NAMESPACE_METADATA); expect(transaction.targetPublicKey).to.be.equal(account.publicKey); diff --git a/test/core/utils/UnresolvedMapping.spec.ts b/test/core/utils/UnresolvedMapping.spec.ts index 1740d081d7..5831b190e3 100644 --- a/test/core/utils/UnresolvedMapping.spec.ts +++ b/test/core/utils/UnresolvedMapping.spec.ts @@ -54,8 +54,7 @@ describe('UnresolvedMapping', () => { describe('toUnresolvedAddress', () => { it('can map hex string to Address', () => { - const unresolved = UnresolvedMapping.toUnresolvedAddress( - Convert.uint8ToHex(RawAddress.stringToAddress(address.plain()))); + const unresolved = UnresolvedMapping.toUnresolvedAddress(Convert.uint8ToHex(RawAddress.stringToAddress(address.plain()))); expect(unresolved instanceof Address).to.be.true; expect(unresolved instanceof NamespaceId).to.be.false; }); diff --git a/test/health.spec.ts b/test/health.spec.ts index 0a51129168..fd6c83462d 100644 --- a/test/health.spec.ts +++ b/test/health.spec.ts @@ -14,11 +14,10 @@ * limitations under the License. */ -import {expect} from 'chai'; +import { expect } from 'chai'; describe('Health test', () => { - it('should success', () => { - expect(true).to.be.equal(true); + expect(true).to.be.equal(true); }); }); diff --git a/test/infrastructure/AccountHttp.spec.ts b/test/infrastructure/AccountHttp.spec.ts index af989d18e5..3b92bae776 100644 --- a/test/infrastructure/AccountHttp.spec.ts +++ b/test/infrastructure/AccountHttp.spec.ts @@ -38,7 +38,6 @@ import { Transaction } from '../../src/model/transaction/Transaction'; import { TransactionType } from '../../src/model/transaction/TransactionType'; describe('AccountHttp', () => { - const address = Address.createFromRawAddress('MCTVW23D2MN5VE4AQ4TZIDZENGNOZXPRPR72DYSX'); const mosaic = new Mosaic(); @@ -70,7 +69,9 @@ describe('AccountHttp', () => { const url = 'http://someHost'; const response: http.IncomingMessage = mock(); const accountRoutesApi: AccountRoutesApi = mock(); - const accountRepository: AccountRepository = DtoMapping.assign(new AccountHttp(url), {accountRoutesApi: instance(accountRoutesApi)}); + const accountRepository: AccountRepository = DtoMapping.assign(new AccountHttp(url), { + accountRoutesApi: instance(accountRoutesApi), + }); const transactionInfoDTO = { meta: { @@ -83,15 +84,15 @@ describe('AccountHttp', () => { transaction: { deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', minApprovalDelta: 1, minRemovalDelta: 1, modifications: [ { - cosignatoryPublicKey: '589B73FBC22063E9AE6FBAC67CB9C6EA865EF556E5' + - 'FB8B7310D45F77C1250B97', + cosignatoryPublicKey: '589B73FBC22063E9AE6FBAC67CB9C6EA865EF556E5' + 'FB8B7310D45F77C1250B97', modificationAction: 0, }, ], @@ -106,7 +107,7 @@ describe('AccountHttp', () => { reset(accountRoutesApi); }); - function assertAccountInfo(accountInfo: AccountInfo) { + function assertAccountInfo(accountInfo: AccountInfo): void { expect(accountInfo).to.be.not.null; expect(accountInfo.accountType).to.be.equals(AccountType.Main); expect(accountInfo.addressHeight.toString()).to.be.equals(accountDTO.addressHeight); @@ -126,14 +127,14 @@ describe('AccountHttp', () => { expect(accountInfo.activityBucket[0].totalFeesPaid).to.be.equals(activityBucketDTO.totalFeesPaid); } - function assertTransaction(transaction: Transaction) { + function assertTransaction(transaction: Transaction): void { expect(transaction).to.be.not.null; expect(transaction.type).to.be.equals(transactionInfoDTO.transaction.type); expect(transaction.deadline.toString()).to.be.equals(transactionInfoDTO.transaction.deadline); } it('getAccountInfo', async () => { - when(accountRoutesApi.getAccountInfo(address.plain())).thenReturn(Promise.resolve({response, body: accountInfoDto})); + when(accountRoutesApi.getAccountInfo(address.plain())).thenReturn(Promise.resolve({ response, body: accountInfoDto })); const accountInfo = await accountRepository.getAccountInfo(address).toPromise(); assertAccountInfo(accountInfo); }); @@ -141,97 +142,157 @@ describe('AccountHttp', () => { it('getAccountsInfo', async () => { const accountIds = new AccountIds(); accountIds.addresses = [address.plain()]; - when(accountRoutesApi.getAccountsInfo(deepEqual(accountIds))).thenReturn(Promise.resolve({response, body: [accountInfoDto]})); + when(accountRoutesApi.getAccountsInfo(deepEqual(accountIds))).thenReturn(Promise.resolve({ response, body: [accountInfoDto] })); const accountInfos = await accountRepository.getAccountsInfo([address]).toPromise(); assertAccountInfo(accountInfos[0]); }); it('getAccountTransactions', async () => { - when(accountRoutesApi.getAccountConfirmedTransactions(address.plain(), 1, 'a', '-id', - deepEqual([TransactionTypeEnum.NUMBER_16725]))).thenReturn(Promise.resolve({ - response, - body: [transactionInfoDTO], - })); - const transactions = await accountRepository.getAccountTransactions(address, new QueryParams({ - pageSize: 1, - id: 'a', - }), new TransactionFilter({types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION]})).toPromise(); + when( + accountRoutesApi.getAccountConfirmedTransactions(address.plain(), 1, 'a', '-id', deepEqual([TransactionTypeEnum.NUMBER_16725])), + ).thenReturn( + Promise.resolve({ + response, + body: [transactionInfoDTO], + }), + ); + const transactions = await accountRepository + .getAccountTransactions( + address, + new QueryParams({ + pageSize: 1, + id: 'a', + }), + new TransactionFilter({ types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION] }), + ) + .toPromise(); assertTransaction(transactions[0]); }); it('getAccountTransactions', async () => { - when(accountRoutesApi.getAccountConfirmedTransactions(address.plain(), undefined, undefined, - undefined, undefined)).thenReturn(Promise.resolve({ - response, - body: [transactionInfoDTO], - })); + when(accountRoutesApi.getAccountConfirmedTransactions(address.plain(), undefined, undefined, undefined, undefined)).thenReturn( + Promise.resolve({ + response, + body: [transactionInfoDTO], + }), + ); const transactions = await accountRepository.getAccountTransactions(address).toPromise(); assertTransaction(transactions[0]); }); it('getAccountIncomingTransactions', async () => { - when(accountRoutesApi.getAccountIncomingTransactions(address.plain(), 1, 'a', '-id', - deepEqual([TransactionTypeEnum.NUMBER_16725]))).thenReturn(Promise.resolve({ - response, - body: [transactionInfoDTO], - })); - const transactions = await accountRepository.getAccountIncomingTransactions(address, new QueryParams({ - pageSize: 1, - id: 'a', - }), new TransactionFilter({types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION]})).toPromise(); + when( + accountRoutesApi.getAccountIncomingTransactions(address.plain(), 1, 'a', '-id', deepEqual([TransactionTypeEnum.NUMBER_16725])), + ).thenReturn( + Promise.resolve({ + response, + body: [transactionInfoDTO], + }), + ); + const transactions = await accountRepository + .getAccountIncomingTransactions( + address, + new QueryParams({ + pageSize: 1, + id: 'a', + }), + new TransactionFilter({ types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION] }), + ) + .toPromise(); assertTransaction(transactions[0]); }); it('getAccountOutgoingTransactions', async () => { - when(accountRoutesApi.getAccountOutgoingTransactions(address.plain(), 1, 'a', '-id', - deepEqual([TransactionTypeEnum.NUMBER_16725]))).thenReturn(Promise.resolve({ - response, - body: [transactionInfoDTO], - })); - const transactions = await accountRepository.getAccountOutgoingTransactions(address, new QueryParams({ - pageSize: 1, - id: 'a', - }), new TransactionFilter({types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION]})).toPromise(); + when( + accountRoutesApi.getAccountOutgoingTransactions(address.plain(), 1, 'a', '-id', deepEqual([TransactionTypeEnum.NUMBER_16725])), + ).thenReturn( + Promise.resolve({ + response, + body: [transactionInfoDTO], + }), + ); + const transactions = await accountRepository + .getAccountOutgoingTransactions( + address, + new QueryParams({ + pageSize: 1, + id: 'a', + }), + new TransactionFilter({ types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION] }), + ) + .toPromise(); assertTransaction(transactions[0]); }); it('getAccountPartialTransactions', async () => { - when(accountRoutesApi.getAccountPartialTransactions(address.plain(), 1, 'a', '-id', - deepEqual([TransactionTypeEnum.NUMBER_16725]))).thenReturn(Promise.resolve({ - response, - body: [transactionInfoDTO], - })); - const transactions = await accountRepository.getAccountPartialTransactions(address, new QueryParams({ - pageSize: 1, - id: 'a', - }), new TransactionFilter({types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION]})).toPromise(); + when( + accountRoutesApi.getAccountPartialTransactions(address.plain(), 1, 'a', '-id', deepEqual([TransactionTypeEnum.NUMBER_16725])), + ).thenReturn( + Promise.resolve({ + response, + body: [transactionInfoDTO], + }), + ); + const transactions = await accountRepository + .getAccountPartialTransactions( + address, + new QueryParams({ + pageSize: 1, + id: 'a', + }), + new TransactionFilter({ types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION] }), + ) + .toPromise(); assertTransaction(transactions[0]); }); it('getAccountUnconfirmedTransactions', async () => { - when(accountRoutesApi.getAccountUnconfirmedTransactions(address.plain(), 2, 'b', '-id', - deepEqual([TransactionTypeEnum.NUMBER_16725]))).thenReturn(Promise.resolve({ - response, - body: [transactionInfoDTO], - })); - const transactions = await accountRepository.getAccountUnconfirmedTransactions(address, new QueryParams({ - pageSize: 2, - id: 'b', - }), new TransactionFilter({types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION]})).toPromise(); + when( + accountRoutesApi.getAccountUnconfirmedTransactions( + address.plain(), + 2, + 'b', + '-id', + deepEqual([TransactionTypeEnum.NUMBER_16725]), + ), + ).thenReturn( + Promise.resolve({ + response, + body: [transactionInfoDTO], + }), + ); + const transactions = await accountRepository + .getAccountUnconfirmedTransactions( + address, + new QueryParams({ + pageSize: 2, + id: 'b', + }), + new TransactionFilter({ types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION] }), + ) + .toPromise(); assertTransaction(transactions[0]); }); it('getAccountPartialTransactions', async () => { - when(accountRoutesApi.getAccountPartialTransactions(address.plain(), 1, 'a', '-id', - deepEqual([TransactionTypeEnum.NUMBER_16725]))).thenReturn(Promise.resolve({ - response, - body: [transactionInfoDTO], - })); - const transactions = await accountRepository.getAccountPartialTransactions(address, new QueryParams({ - pageSize: 1, - id: 'a', - }), new TransactionFilter({types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION]})).toPromise(); + when( + accountRoutesApi.getAccountPartialTransactions(address.plain(), 1, 'a', '-id', deepEqual([TransactionTypeEnum.NUMBER_16725])), + ).thenReturn( + Promise.resolve({ + response, + body: [transactionInfoDTO], + }), + ); + const transactions = await accountRepository + .getAccountPartialTransactions( + address, + new QueryParams({ + pageSize: 1, + id: 'a', + }), + new TransactionFilter({ types: [TransactionType.MULTISIG_ACCOUNT_MODIFICATION] }), + ) + .toPromise(); assertTransaction(transactions[0]); }); - }); diff --git a/test/infrastructure/BlockHttp.spec.ts b/test/infrastructure/BlockHttp.spec.ts index a0e8a8deef..2b07a275f1 100644 --- a/test/infrastructure/BlockHttp.spec.ts +++ b/test/infrastructure/BlockHttp.spec.ts @@ -35,7 +35,6 @@ import { Transaction } from '../../src/model/transaction/Transaction'; import { UInt64 } from '../../src/model/UInt64'; describe('BlockHttp', () => { - const blockDTO = new BlockDTO(); blockDTO.version = 1; blockDTO.network = NetworkTypeEnum.NUMBER_152; @@ -64,7 +63,9 @@ describe('BlockHttp', () => { const url = 'http://someHost'; const response: http.IncomingMessage = mock(); const blockRoutesApi: BlockRoutesApi = mock(); - const blockRepository: BlockRepository = DtoMapping.assign(new BlockHttp(url), {blockRoutesApi: instance(blockRoutesApi)}); + const blockRepository: BlockRepository = DtoMapping.assign(new BlockHttp(url), { + blockRoutesApi: instance(blockRoutesApi), + }); const transactionInfoDTO = { meta: { @@ -77,15 +78,15 @@ describe('BlockHttp', () => { transaction: { deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', minApprovalDelta: 1, minRemovalDelta: 1, modifications: [ { - cosignatoryPublicKey: '589B73FBC22063E9AE6FBAC67CB9C6EA865EF556E5' + - 'FB8B7310D45F77C1250B97', + cosignatoryPublicKey: '589B73FBC22063E9AE6FBAC67CB9C6EA865EF556E5' + 'FB8B7310D45F77C1250B97', modificationAction: 0, }, ], @@ -100,7 +101,7 @@ describe('BlockHttp', () => { reset(blockRoutesApi); }); - function assertBlockInfo(blockInfo: BlockInfo) { + function assertBlockInfo(blockInfo: BlockInfo): void { expect(blockInfo).to.be.not.null; expect(blockInfo.type).to.be.equals(blockInfoDto.block.type); expect(blockInfo.previousBlockHash).to.be.equals(blockInfoDto.block.previousBlockHash); @@ -121,32 +122,36 @@ describe('BlockHttp', () => { expect(blockInfo.totalFee.toString()).to.be.equals(blockInfoDto.meta.totalFee); } - function assertTransaction(transaction: Transaction) { + function assertTransaction(transaction: Transaction): void { expect(transaction).to.be.not.null; expect(transaction.type).to.be.equals(transactionInfoDTO.transaction.type); expect(transaction.deadline.toString()).to.be.equals(transactionInfoDTO.transaction.deadline); } it('getBlockInfo', async () => { - when(blockRoutesApi.getBlockByHeight('1')).thenReturn(Promise.resolve({response, body: blockInfoDto})); + when(blockRoutesApi.getBlockByHeight('1')).thenReturn(Promise.resolve({ response, body: blockInfoDto })); const blockInfo = await blockRepository.getBlockByHeight(UInt64.fromUint(1)).toPromise(); assertBlockInfo(blockInfo); }); it('getBlocksByHeightWithLimit', async () => { - when(blockRoutesApi.getBlocksByHeightWithLimit('2', 10)).thenReturn(Promise.resolve({ - response, - body: [blockInfoDto], - })); + when(blockRoutesApi.getBlocksByHeightWithLimit('2', 10)).thenReturn( + Promise.resolve({ + response, + body: [blockInfoDto], + }), + ); const blockInfos = await blockRepository.getBlocksByHeightWithLimit(UInt64.fromUint(2), 10).toPromise(); assertBlockInfo(blockInfos[0]); }); it('getBlockTransactions', async () => { - when(blockRoutesApi.getBlockTransactions('2', undefined, undefined, undefined)).thenReturn(Promise.resolve({ - response, - body: [transactionInfoDTO], - })); + when(blockRoutesApi.getBlockTransactions('2', undefined, undefined, undefined)).thenReturn( + Promise.resolve({ + response, + body: [transactionInfoDTO], + }), + ); const transactions = await blockRepository.getBlockTransactions(UInt64.fromUint(2)).toPromise(); assertTransaction(transactions[0]); }); @@ -158,13 +163,14 @@ describe('BlockHttp', () => { merklePathItemDTO.position = PositionEnum.Left; merkleProofInfoDTO.merklePath = [merklePathItemDTO]; - when(blockRoutesApi.getMerkleTransaction('2', 'abc')).thenReturn(Promise.resolve({ - response, - body: merkleProofInfoDTO, - })); + when(blockRoutesApi.getMerkleTransaction('2', 'abc')).thenReturn( + Promise.resolve({ + response, + body: merkleProofInfoDTO, + }), + ); const merkleProofInfo = await blockRepository.getMerkleTransaction(UInt64.fromUint(2), 'abc').toPromise(); expect(merkleProofInfo).to.be.not.null; expect(merkleProofInfo.merklePath).to.deep.equals([new MerklePathItem(PositionEnum.Left, 'bbb')]); }); - }); diff --git a/test/infrastructure/ChainHttp.spec.ts b/test/infrastructure/ChainHttp.spec.ts index 502e39869b..d26938e744 100644 --- a/test/infrastructure/ChainHttp.spec.ts +++ b/test/infrastructure/ChainHttp.spec.ts @@ -15,18 +15,19 @@ */ import { expect } from 'chai'; import * as http from 'http'; -import { ChainRoutesApi, ChainScoreDTO, HeightInfoDTO, } from 'symbol-openapi-typescript-node-client'; +import { ChainRoutesApi, ChainScoreDTO, HeightInfoDTO } from 'symbol-openapi-typescript-node-client'; import { instance, mock, reset, when } from 'ts-mockito'; import { DtoMapping } from '../../src/core/utils/DtoMapping'; import { ChainHttp } from '../../src/infrastructure/ChainHttp'; import { ChainRepository } from '../../src/infrastructure/ChainRepository'; describe('ChainHttp', () => { - const url = 'http://someHost'; const response: http.IncomingMessage = mock(); const chainRoutesApi: ChainRoutesApi = mock(); - const chainRepository: ChainRepository = DtoMapping.assign(new ChainHttp(url), {chainRoutesApi: instance(chainRoutesApi)}); + const chainRepository: ChainRepository = DtoMapping.assign(new ChainHttp(url), { + chainRoutesApi: instance(chainRoutesApi), + }); before(() => { reset(response); @@ -36,7 +37,7 @@ describe('ChainHttp', () => { it('getBlockchainHeight', async () => { const heightInfoDTO = new HeightInfoDTO(); heightInfoDTO.height = '3'; - when(chainRoutesApi.getChainHeight()).thenReturn(Promise.resolve({response, body: heightInfoDTO})); + when(chainRoutesApi.getChainHeight()).thenReturn(Promise.resolve({ response, body: heightInfoDTO })); const heightInfo = await chainRepository.getBlockchainHeight().toPromise(); expect(heightInfo).to.be.not.null; expect(heightInfo.toString()).to.be.equals('3'); @@ -46,11 +47,10 @@ describe('ChainHttp', () => { const chainScoreDTO = new ChainScoreDTO(); chainScoreDTO.scoreLow = '2'; chainScoreDTO.scoreHigh = '3'; - when(chainRoutesApi.getChainScore()).thenReturn(Promise.resolve({response, body: chainScoreDTO})); + when(chainRoutesApi.getChainScore()).thenReturn(Promise.resolve({ response, body: chainScoreDTO })); const chainScore = await chainRepository.getChainScore().toPromise(); expect(chainScore).to.be.not.null; expect(chainScore.scoreLow.toString()).to.be.equals('2'); expect(chainScore.scoreHigh.toString()).to.be.equals('3'); }); - }); diff --git a/test/infrastructure/Listener.spec.ts b/test/infrastructure/Listener.spec.ts index 71dfbf46cd..b69b226699 100644 --- a/test/infrastructure/Listener.spec.ts +++ b/test/infrastructure/Listener.spec.ts @@ -38,16 +38,14 @@ describe('Listener', () => { describe('onStatusWhenAddressIsTheSame', () => { it('Should forward status', () => { - const errorEncodedAddress = '906415867F121D037AF447E711B0F5E4D52EBBF066D96860EB'; const errorAddress = Address.createFromEncoded(errorEncodedAddress); class WebSocketMock { - constructor(public readonly url: string) { - } + constructor(public readonly url: string) {} - send(payload: string) { + send(payload: string): void { expect(payload).to.be.eq(`{"subscribe":"status/${errorAddress.plain()}"}`); } } @@ -77,23 +75,19 @@ describe('Listener', () => { expect(transactionStatusError.hash).to.be.equal(statusInfoErrorDTO.hash); expect(transactionStatusError.code).to.be.equal(statusInfoErrorDTO.code); deepEqual(transactionStatusError.deadline.toDTO(), UInt64.fromNumericString(statusInfoErrorDTO.deadline).toDTO()); - }); }); describe('onStatusWhenAddressIsDifferentAddress', () => { it('Should not forward status', () => { - const errorEncodedAddress = '906415867F121D037AF447E711B0F5E4D52EBBF066D96860EB'; const subscribedEncodedAddress = '906415867F121D037AF447E711B0F5E4D52EBBF066D96AAAAA'; const subscribedAddress = Address.createFromEncoded(subscribedEncodedAddress); - // tslint:disable-next-line: max-classes-per-file class WebSocketMock { - constructor(public readonly url: string) { - } - send(payload: string) { + constructor(public readonly url: string) {} + send(payload: string): void { expect(payload).to.be.eq(`{"subscribe":"status/${subscribedAddress.plain()}"}`); } } @@ -118,20 +112,20 @@ describe('Listener', () => { listener.handleMessage(statusInfoErrorDTO, null); expect(reportedStatus.length).to.be.equal(0); - }); }); describe('onerror', () => { it('should reject because of wrong server url', async () => { const listener = new Listener('https://notcorrecturl:0000'); - await listener.open() - .then(() => { - throw new Error('This should not be called when expecting error'); - }) - .catch((error) => { - expect(error.message.toString()).not.to.be.equal(''); - }); + await listener + .open() + .then(() => { + throw new Error('This should not be called when expecting error'); + }) + .catch((error) => { + expect(error.message.toString()).not.to.be.equal(''); + }); }); }); }); diff --git a/test/infrastructure/MetadataHttp.spec.ts b/test/infrastructure/MetadataHttp.spec.ts index 7ad4c82437..1fd24cd4f0 100644 --- a/test/infrastructure/MetadataHttp.spec.ts +++ b/test/infrastructure/MetadataHttp.spec.ts @@ -34,7 +34,6 @@ import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../src/model/namespace/NamespaceId'; describe('MetadataHttp', () => { - const address = Address.createFromRawAddress('MCTVW23D2MN5VE4AQ4TZIDZENGNOZXPRPR72DYSX'); const mosaicId = new MosaicId('941299B2B7E1291C'); const namespaceId = new NamespaceId('some.address'); @@ -84,14 +83,15 @@ describe('MetadataHttp', () => { const url = 'http://someHost'; const response: http.IncomingMessage = mock(); const metadataRoutesApi: MetadataRoutesApi = mock(); - const metadataRepository: MetadataRepository = DtoMapping.assign( - new MetadataHttp(url), {metadataRoutesApi: instance(metadataRoutesApi)}); + const metadataRepository: MetadataRepository = DtoMapping.assign(new MetadataHttp(url), { + metadataRoutesApi: instance(metadataRoutesApi), + }); before(() => { reset(response); reset(metadataRoutesApi); }); - function assertMetadataInfo(metadataInfo: Metadata, dto: MetadataDTO) { + function assertMetadataInfo(metadataInfo: Metadata, dto: MetadataDTO): void { expect(metadataInfo).to.be.not.null; expect(metadataInfo.id).to.be.equals(dto.id); if (metadataInfo.metadataEntry.metadataType === MetadataType.Mosaic) { @@ -109,14 +109,21 @@ describe('MetadataHttp', () => { } it('getAccountMetadata', async () => { - when(metadataRoutesApi.getAccountMetadata(address.plain(), 1, 'a', '-id')).thenReturn(Promise.resolve({ - response, - body: metadataEntriesDTO, - })); - const metadatas = await metadataRepository.getAccountMetadata(address, new QueryParams({ - pageSize: 1, - id: 'a', - })).toPromise(); + when(metadataRoutesApi.getAccountMetadata(address.plain(), 1, 'a', '-id')).thenReturn( + Promise.resolve({ + response, + body: metadataEntriesDTO, + }), + ); + const metadatas = await metadataRepository + .getAccountMetadata( + address, + new QueryParams({ + pageSize: 1, + id: 'a', + }), + ) + .toPromise(); expect(metadatas.length).to.be.equals(3); assertMetadataInfo(metadatas[0], metadataDTOMosaic); assertMetadataInfo(metadatas[1], metadataDTOAddress); @@ -124,10 +131,12 @@ describe('MetadataHttp', () => { }); it('getAccountMetadataByKey', async () => { - when(metadataRoutesApi.getAccountMetadataByKey(address.plain(), 'aaa')).thenReturn(Promise.resolve({ - response, - body: metadataEntriesDTO, - })); + when(metadataRoutesApi.getAccountMetadataByKey(address.plain(), 'aaa')).thenReturn( + Promise.resolve({ + response, + body: metadataEntriesDTO, + }), + ); const metadatas = await metadataRepository.getAccountMetadataByKey(address, 'aaa').toPromise(); assertMetadataInfo(metadatas[0], metadataDTOMosaic); assertMetadataInfo(metadatas[1], metadataDTOAddress); @@ -135,23 +144,32 @@ describe('MetadataHttp', () => { }); it('getAccountMetadataByKeyAndSender', async () => { - when(metadataRoutesApi.getAccountMetadataByKeyAndSender(address.plain(), 'aaa', 'sender')).thenReturn(Promise.resolve({ - response, - body: metadataDTOMosaic, - })); + when(metadataRoutesApi.getAccountMetadataByKeyAndSender(address.plain(), 'aaa', 'sender')).thenReturn( + Promise.resolve({ + response, + body: metadataDTOMosaic, + }), + ); const metadata = await metadataRepository.getAccountMetadataByKeyAndSender(address, 'aaa', 'sender').toPromise(); assertMetadataInfo(metadata, metadataDTOMosaic); }); it('getMosaicMetadata', async () => { - when(metadataRoutesApi.getMosaicMetadata(mosaicId.toHex(), 1, 'a', '-id')).thenReturn(Promise.resolve({ - response, - body: metadataEntriesDTO, - })); - const metadatas = await metadataRepository.getMosaicMetadata(mosaicId, new QueryParams({ - pageSize: 1, - id: 'a', - })).toPromise(); + when(metadataRoutesApi.getMosaicMetadata(mosaicId.toHex(), 1, 'a', '-id')).thenReturn( + Promise.resolve({ + response, + body: metadataEntriesDTO, + }), + ); + const metadatas = await metadataRepository + .getMosaicMetadata( + mosaicId, + new QueryParams({ + pageSize: 1, + id: 'a', + }), + ) + .toPromise(); expect(metadatas.length).to.be.equals(3); assertMetadataInfo(metadatas[0], metadataDTOMosaic); assertMetadataInfo(metadatas[1], metadataDTOAddress); @@ -159,10 +177,12 @@ describe('MetadataHttp', () => { }); it('getMosaicMetadataByKey', async () => { - when(metadataRoutesApi.getMosaicMetadataByKey(mosaicId.toHex(), 'aaa')).thenReturn(Promise.resolve({ - response, - body: metadataEntriesDTO, - })); + when(metadataRoutesApi.getMosaicMetadataByKey(mosaicId.toHex(), 'aaa')).thenReturn( + Promise.resolve({ + response, + body: metadataEntriesDTO, + }), + ); const metadatas = await metadataRepository.getMosaicMetadataByKey(mosaicId, 'aaa').toPromise(); assertMetadataInfo(metadatas[0], metadataDTOMosaic); assertMetadataInfo(metadatas[1], metadataDTOAddress); @@ -170,23 +190,32 @@ describe('MetadataHttp', () => { }); it('getMosaicMetadataByKeyAndSender', async () => { - when(metadataRoutesApi.getMosaicMetadataByKeyAndSender(mosaicId.toHex(), 'aaa', 'sender')).thenReturn(Promise.resolve({ - response, - body: metadataDTOMosaic, - })); + when(metadataRoutesApi.getMosaicMetadataByKeyAndSender(mosaicId.toHex(), 'aaa', 'sender')).thenReturn( + Promise.resolve({ + response, + body: metadataDTOMosaic, + }), + ); const metadata = await metadataRepository.getMosaicMetadataByKeyAndSender(mosaicId, 'aaa', 'sender').toPromise(); assertMetadataInfo(metadata, metadataDTOMosaic); }); it('getNamespaceMetadata', async () => { - when(metadataRoutesApi.getNamespaceMetadata(namespaceId.toHex(), 2, 'a', '-id')).thenReturn(Promise.resolve({ - response, - body: metadataEntriesDTO, - })); - const metadatas = await metadataRepository.getNamespaceMetadata(namespaceId, new QueryParams({ - pageSize: 2, - id: 'a', - })).toPromise(); + when(metadataRoutesApi.getNamespaceMetadata(namespaceId.toHex(), 2, 'a', '-id')).thenReturn( + Promise.resolve({ + response, + body: metadataEntriesDTO, + }), + ); + const metadatas = await metadataRepository + .getNamespaceMetadata( + namespaceId, + new QueryParams({ + pageSize: 2, + id: 'a', + }), + ) + .toPromise(); expect(metadatas.length).to.be.equals(3); assertMetadataInfo(metadatas[0], metadataDTOMosaic); assertMetadataInfo(metadatas[1], metadataDTOAddress); @@ -194,10 +223,12 @@ describe('MetadataHttp', () => { }); it('getNamespaceMetadataByKey', async () => { - when(metadataRoutesApi.getNamespaceMetadataByKey(namespaceId.toHex(), 'bbb')).thenReturn(Promise.resolve({ - response, - body: metadataEntriesDTO, - })); + when(metadataRoutesApi.getNamespaceMetadataByKey(namespaceId.toHex(), 'bbb')).thenReturn( + Promise.resolve({ + response, + body: metadataEntriesDTO, + }), + ); const metadatas = await metadataRepository.getNamespaceMetadataByKey(namespaceId, 'bbb').toPromise(); assertMetadataInfo(metadatas[0], metadataDTOMosaic); assertMetadataInfo(metadatas[1], metadataDTOAddress); @@ -205,12 +236,13 @@ describe('MetadataHttp', () => { }); it('getNamespaceMetadataByKeyAndSender', async () => { - when(metadataRoutesApi.getNamespaceMetadataByKeyAndSender(namespaceId.toHex(), 'cccc', 'sender1')).thenReturn(Promise.resolve({ - response, - body: metadataDTOMosaic, - })); + when(metadataRoutesApi.getNamespaceMetadataByKeyAndSender(namespaceId.toHex(), 'cccc', 'sender1')).thenReturn( + Promise.resolve({ + response, + body: metadataDTOMosaic, + }), + ); const metadata = await metadataRepository.getNamespaceMetadataByKeyAndSender(namespaceId, 'cccc', 'sender1').toPromise(); assertMetadataInfo(metadata, metadataDTOMosaic); }); - }); diff --git a/test/infrastructure/MosaicHttp.spec.ts b/test/infrastructure/MosaicHttp.spec.ts index 715095e28d..bd68ff9ccc 100644 --- a/test/infrastructure/MosaicHttp.spec.ts +++ b/test/infrastructure/MosaicHttp.spec.ts @@ -15,14 +15,7 @@ */ import { expect } from 'chai'; import * as http from 'http'; -import { - Mosaic, - MosaicRoutesApi, - MosaicInfoDTO, - MosaicDTO, - MosaicsInfoDTO, - MosaicIds, -} from 'symbol-openapi-typescript-node-client'; +import { Mosaic, MosaicRoutesApi, MosaicInfoDTO, MosaicDTO, MosaicsInfoDTO, MosaicIds } from 'symbol-openapi-typescript-node-client'; import { instance, mock, reset, when, deepEqual } from 'ts-mockito'; import { DtoMapping } from '../../src/core/utils/DtoMapping'; import { MosaicRepository } from '../../src/infrastructure/MosaicRepository'; @@ -32,12 +25,12 @@ import { MosaicId } from '../../src/model/mosaic/MosaicId'; import { MosaicInfo } from '../../src/model/mosaic/MosaicInfo'; import { PublicAccount } from '../../src/model/account/PublicAccount'; import { AccountIds } from 'symbol-openapi-typescript-node-client'; -import { assert } from 'chai'; describe('MosaicHttp', () => { - - const publicAccount = - PublicAccount.createFromPublicKey('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B6', NetworkType.MIJIN_TEST); + const publicAccount = PublicAccount.createFromPublicKey( + '9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B6', + NetworkType.MIJIN_TEST, + ); const address = publicAccount.address; const mosaicId = new MosaicId('941299B2B7E1291C'); const mosaic = new Mosaic(); @@ -63,15 +56,16 @@ describe('MosaicHttp', () => { const url = 'http://someHost'; const response: http.IncomingMessage = mock(); const mosaicRoutesApi: MosaicRoutesApi = mock(); - const mosaicRepository: MosaicRepository = DtoMapping.assign(new MosaicHttp(url, NetworkType.MIJIN_TEST), - {mosaicRoutesApi: instance(mosaicRoutesApi)}); + const mosaicRepository: MosaicRepository = DtoMapping.assign(new MosaicHttp(url, NetworkType.MIJIN_TEST), { + mosaicRoutesApi: instance(mosaicRoutesApi), + }); before(() => { reset(response); reset(mosaicRoutesApi); }); - function assertMosaicInfo(mosaicInfo: MosaicInfo) { + function assertMosaicInfo(mosaicInfo: MosaicInfo): void { expect(mosaicInfo).to.be.not.null; expect(mosaicInfo.divisibility).to.be.equals(6); expect(mosaicInfo.duration.toString()).to.be.equals(mosaicDto.duration); @@ -85,7 +79,7 @@ describe('MosaicHttp', () => { } it('getMosaic', async () => { - when(mosaicRoutesApi.getMosaic(mosaicId.toHex())).thenReturn(Promise.resolve({response, body: mosaicInfoDto})); + when(mosaicRoutesApi.getMosaic(mosaicId.toHex())).thenReturn(Promise.resolve({ response, body: mosaicInfoDto })); const mosaicInfo = await mosaicRepository.getMosaic(mosaicId).toPromise(); assertMosaicInfo(mosaicInfo); }); @@ -93,13 +87,13 @@ describe('MosaicHttp', () => { it('getMosaics', async () => { const mosaicIds = new MosaicIds(); mosaicIds.mosaicIds = [mosaicId.toHex()]; - when(mosaicRoutesApi.getMosaics(deepEqual(mosaicIds))).thenReturn(Promise.resolve({response, body: [mosaicInfoDto]})); + when(mosaicRoutesApi.getMosaics(deepEqual(mosaicIds))).thenReturn(Promise.resolve({ response, body: [mosaicInfoDto] })); const mosaicInfos = await mosaicRepository.getMosaics([mosaicId]).toPromise(); assertMosaicInfo(mosaicInfos[0]); }); it('getMosaicsFromAccount', async () => { - when(mosaicRoutesApi.getMosaicsFromAccount(address.plain())).thenReturn(Promise.resolve({response, body: mosaicsInfoDto})); + when(mosaicRoutesApi.getMosaicsFromAccount(address.plain())).thenReturn(Promise.resolve({ response, body: mosaicsInfoDto })); const mosaicsInfo = await mosaicRepository.getMosaicsFromAccount(address).toPromise(); assertMosaicInfo(mosaicsInfo[0]); }); @@ -107,37 +101,44 @@ describe('MosaicHttp', () => { it('getMosaicsFromAccounts', async () => { const accountIds = new AccountIds(); accountIds.addresses = [address.plain()]; - when(mosaicRoutesApi.getMosaicsFromAccounts(deepEqual(accountIds))) - .thenReturn(Promise.resolve({response, body: mosaicsInfoDto})); + when(mosaicRoutesApi.getMosaicsFromAccounts(deepEqual(accountIds))).thenReturn(Promise.resolve({ response, body: mosaicsInfoDto })); const mosaicsInfo = await mosaicRepository.getMosaicsFromAccounts([address]).toPromise(); - assertMosaicInfo(mosaicsInfo[0]); + assertMosaicInfo(mosaicsInfo[0]); }); it('getMosaic - Error', async () => { when(mosaicRoutesApi.getMosaic(mosaicId.toHex())).thenThrow(new Error('Mocked Error')); - await mosaicRepository.getMosaic(mosaicId).toPromise().catch((error) => - expect(error).not.to.be.undefined); + await mosaicRepository + .getMosaic(mosaicId) + .toPromise() + .catch((error) => expect(error).not.to.be.undefined); }); it('getMosaics - Error', async () => { const mosaicIds = new MosaicIds(); mosaicIds.mosaicIds = [mosaicId.toHex()]; when(mosaicRoutesApi.getMosaics(deepEqual(mosaicIds))).thenThrow(new Error('Mocked Error')); - await mosaicRepository.getMosaics([mosaicId]).toPromise().catch((error) => - expect(error).not.to.be.undefined); + await mosaicRepository + .getMosaics([mosaicId]) + .toPromise() + .catch((error) => expect(error).not.to.be.undefined); }); it('getMosaicsFromAccount - Error', async () => { when(mosaicRoutesApi.getMosaicsFromAccount(address.plain())).thenThrow(new Error('Mocked Error')); - await mosaicRepository.getMosaicsFromAccount(address).toPromise().catch((error) => - expect(error).not.to.be.undefined); + await mosaicRepository + .getMosaicsFromAccount(address) + .toPromise() + .catch((error) => expect(error).not.to.be.undefined); }); it('getMosaicsFromAccounts - Error', async () => { const accountIds = new AccountIds(); accountIds.addresses = [address.plain()]; when(mosaicRoutesApi.getMosaicsFromAccounts(deepEqual(accountIds))).thenThrow(new Error('Mocked Error')); - await mosaicRepository.getMosaicsFromAccounts([address]).toPromise().catch((error) => - expect(error).not.to.be.undefined); + await mosaicRepository + .getMosaicsFromAccounts([address]) + .toPromise() + .catch((error) => expect(error).not.to.be.undefined); }); }); diff --git a/test/infrastructure/MultisigHttp.spec.ts b/test/infrastructure/MultisigHttp.spec.ts new file mode 100644 index 0000000000..35ef5f9637 --- /dev/null +++ b/test/infrastructure/MultisigHttp.spec.ts @@ -0,0 +1,98 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { expect } from 'chai'; +import * as http from 'http'; +import { MultisigAccountGraphInfoDTO, MultisigAccountInfoDTO, MultisigDTO, MultisigRoutesApi } from 'symbol-openapi-typescript-node-client'; +import { instance, mock, reset, when } from 'ts-mockito'; +import { DtoMapping } from '../../src/core/utils/DtoMapping'; +import { MultisigHttp } from '../../src/infrastructure/MultisigHttp'; +import { MultisigRepository } from '../../src/infrastructure/MultisigRepository'; +import { Account } from '../../src/model/account/Account'; +import { MultisigAccountInfo } from '../../src/model/account/MultisigAccountInfo'; +import { NetworkType } from '../../src/model/network/NetworkType'; + +describe('MultisigHttp', () => { + const networkType = NetworkType.MIJIN_TEST; + const account = Account.generateNewAccount(networkType); + const address = account.address; + const accountInfoDto = new MultisigAccountInfoDTO(); + const multisigDTO = new MultisigDTO(); + + const account1 = Account.generateNewAccount(networkType); + const account2 = Account.generateNewAccount(networkType); + const account3 = Account.generateNewAccount(networkType); + const account4 = Account.generateNewAccount(networkType); + + multisigDTO.accountAddress = account.address.plain(); + multisigDTO.accountPublicKey = account.publicKey; + multisigDTO.cosignatoryPublicKeys = [account1.publicKey, account2.publicKey]; + multisigDTO.minApproval = 2; + multisigDTO.minRemoval = 3; + multisigDTO.multisigPublicKeys = [account3.publicKey, account4.publicKey]; + + accountInfoDto.multisig = multisigDTO; + + const url = 'http://someHost'; + const response: http.IncomingMessage = mock(); + const multisigRoutesApi: MultisigRoutesApi = mock(); + const accountRepository: MultisigRepository = DtoMapping.assign(new MultisigHttp(url, networkType), { + multisigRoutesApi: instance(multisigRoutesApi), + }); + + before(() => { + reset(response); + reset(multisigRoutesApi); + }); + + function assertMultisigInfo(accountInfo: MultisigAccountInfo): void { + expect(accountInfo).to.be.not.null; + expect(accountInfo.isMultisig()).to.be.equals(true); + expect(accountInfo.account).to.be.deep.equals(account.publicAccount); + expect(accountInfo.cosignatories).to.deep.equals([account1.publicAccount, account2.publicAccount]); + expect(accountInfo.minApproval).to.be.equals(multisigDTO.minApproval); + expect(accountInfo.minRemoval).to.be.equals(multisigDTO.minRemoval); + expect(accountInfo.multisigAccounts).to.deep.equals([account3.publicAccount, account4.publicAccount]); + } + + it('getMultisigAccountInfo', async () => { + when(multisigRoutesApi.getAccountMultisig(address.plain())).thenReturn(Promise.resolve({ response, body: accountInfoDto })); + const accountInfo = await accountRepository.getMultisigAccountInfo(address).toPromise(); + assertMultisigInfo(accountInfo); + }); + + it('getMultisigAccountGraphInfo', async () => { + const body = new MultisigAccountGraphInfoDTO(); + body.level = 10; + body.multisigEntries = [accountInfoDto, accountInfoDto, accountInfoDto]; + + const body2 = new MultisigAccountGraphInfoDTO(); + body2.level = 20; + body2.multisigEntries = [accountInfoDto, accountInfoDto]; + when(multisigRoutesApi.getAccountMultisigGraph(address.plain())).thenReturn(Promise.resolve({ response, body: [body, body2] })); + const graphInfo = await accountRepository.getMultisigAccountGraphInfo(address).toPromise(); + expect(graphInfo.multisigAccounts.size).to.be.eq(2); + const list10: MultisigAccountInfo[] = graphInfo.multisigAccounts.get(10) as MultisigAccountInfo[]; + expect(list10.length).to.be.eq(3); + assertMultisigInfo(list10[0]); + assertMultisigInfo(list10[1]); + assertMultisigInfo(list10[2]); + + const list20: MultisigAccountInfo[] = graphInfo.multisigAccounts.get(20) as MultisigAccountInfo[]; + expect(list20.length).to.be.eq(2); + assertMultisigInfo(list20[0]); + assertMultisigInfo(list20[1]); + }); +}); diff --git a/test/infrastructure/NetworkHttp.spec.ts b/test/infrastructure/NetworkHttp.spec.ts index 9e61d08b54..51edf8ed3a 100644 --- a/test/infrastructure/NetworkHttp.spec.ts +++ b/test/infrastructure/NetworkHttp.spec.ts @@ -15,28 +15,30 @@ */ import { expect } from 'chai'; import * as http from 'http'; -import { NetworkRoutesApi, - NetworkTypeDTO, - NodeInfoDTO, - NodeRoutesApi, - TransactionFeesDTO, - RentalFeesDTO, - NetworkConfigurationDTO, - NetworkPropertiesDTO, - NodeIdentityEqualityStrategy, - ChainPropertiesDTO, - PluginsPropertiesDTO, - AccountLinkNetworkPropertiesDTO, - AggregateNetworkPropertiesDTO, - HashLockNetworkPropertiesDTO, - SecretLockNetworkPropertiesDTO, - MetadataNetworkPropertiesDTO, - MosaicNetworkPropertiesDTO, - MultisigNetworkPropertiesDTO, - NamespaceNetworkPropertiesDTO, - AccountRestrictionNetworkPropertiesDTO, - MosaicRestrictionNetworkPropertiesDTO, - TransferNetworkPropertiesDTO } from 'symbol-openapi-typescript-node-client'; +import { + NetworkRoutesApi, + NetworkTypeDTO, + NodeInfoDTO, + NodeRoutesApi, + TransactionFeesDTO, + RentalFeesDTO, + NetworkConfigurationDTO, + NetworkPropertiesDTO, + NodeIdentityEqualityStrategy, + ChainPropertiesDTO, + PluginsPropertiesDTO, + AccountLinkNetworkPropertiesDTO, + AggregateNetworkPropertiesDTO, + HashLockNetworkPropertiesDTO, + SecretLockNetworkPropertiesDTO, + MetadataNetworkPropertiesDTO, + MosaicNetworkPropertiesDTO, + MultisigNetworkPropertiesDTO, + NamespaceNetworkPropertiesDTO, + AccountRestrictionNetworkPropertiesDTO, + MosaicRestrictionNetworkPropertiesDTO, + TransferNetworkPropertiesDTO, +} from 'symbol-openapi-typescript-node-client'; import { instance, mock, reset, when } from 'ts-mockito'; import { DtoMapping } from '../../src/core/utils/DtoMapping'; import { NetworkHttp } from '../../src/infrastructure/NetworkHttp'; @@ -51,7 +53,7 @@ describe('NetworkHttp', () => { const response: http.IncomingMessage = mock(); const nodeRoutesApi: NodeRoutesApi = mock(); const networkRoutesApi: NetworkRoutesApi = mock(); - const nodeHttp = DtoMapping.assign(new NodeHttp(url), {nodeRoutesApi: instance(nodeRoutesApi)}); + const nodeHttp = DtoMapping.assign(new NodeHttp(url), { nodeRoutesApi: instance(nodeRoutesApi) }); const networkRepository = DtoMapping.assign(new NetworkHttp(url), { networkRoutesApi: instance(networkRoutesApi), nodeHttp, @@ -64,14 +66,13 @@ describe('NetworkHttp', () => { }); it('getTransactionFees', async () => { - const body = new TransactionFeesDTO(); body.averageFeeMultiplier = 1; body.highestFeeMultiplier = 2; body.lowestFeeMultiplier = 3; body.medianFeeMultiplier = 4; - when(networkRoutesApi.getTransactionFees()).thenReturn(Promise.resolve({response, body})); + when(networkRoutesApi.getTransactionFees()).thenReturn(Promise.resolve({ response, body })); const networkFees = await networkRepository.getTransactionFees().toPromise(); expect(networkFees).to.be.not.null; @@ -82,13 +83,12 @@ describe('NetworkHttp', () => { }); it('getRentalFees', async () => { - const body = new RentalFeesDTO(); body.effectiveChildNamespaceRentalFee = '1'; body.effectiveMosaicRentalFee = '2'; body.effectiveRootNamespaceRentalFeePerBlock = '3'; - when(networkRoutesApi.getRentalFees()).thenReturn(Promise.resolve({response, body})); + when(networkRoutesApi.getRentalFees()).thenReturn(Promise.resolve({ response, body })); const rentalFees = await networkRepository.getRentalFees().toPromise(); expect(rentalFees).to.be.not.null; @@ -98,23 +98,21 @@ describe('NetworkHttp', () => { }); it('getNetworkType', async () => { - const body = new NodeInfoDTO(); body.networkIdentifier = NetworkType.MIJIN_TEST; - when(nodeRoutesApi.getNodeInfo()).thenReturn(Promise.resolve({response, body})); + when(nodeRoutesApi.getNodeInfo()).thenReturn(Promise.resolve({ response, body })); const networkType = await networkRepository.getNetworkType().toPromise(); expect(networkType).to.be.equals(NetworkType.MIJIN_TEST); }); it('getNetworkName', async () => { - const body = new NetworkTypeDTO(); body.name = 'Some Name'; body.description = 'Some Description'; - when(networkRoutesApi.getNetworkType()).thenReturn(Promise.resolve({response, body})); + when(networkRoutesApi.getNetworkType()).thenReturn(Promise.resolve({ response, body })); const networkName = await networkRepository.getNetworkName().toPromise(); expect(networkName.description).to.be.equals(body.description); @@ -122,7 +120,6 @@ describe('NetworkHttp', () => { }); it('getNetworkProperties', async () => { - const body = new NetworkConfigurationDTO(); const network = new NetworkPropertiesDTO(); @@ -215,7 +212,7 @@ describe('NetworkHttp', () => { body.network = network; body.plugins = plugin; - when(networkRoutesApi.getNetworkProperties()).thenReturn(Promise.resolve({response, body})); + when(networkRoutesApi.getNetworkProperties()).thenReturn(Promise.resolve({ response, body })); const networkProperties = await networkRepository.getNetworkProperties().toPromise(); deepEqual(networkProperties.network, body.network); @@ -225,7 +222,7 @@ describe('NetworkHttp', () => { it('getNetworkProperties - using rest json payload', async () => { const body = testResources.getDummyNetworkProperties(); - when(networkRoutesApi.getNetworkProperties()).thenReturn(Promise.resolve({response, body})); + when(networkRoutesApi.getNetworkProperties()).thenReturn(Promise.resolve({ response, body })); const networkProperties = await networkRepository.getNetworkProperties().toPromise(); deepEqual(networkProperties.network, body.network); deepEqual(networkProperties.chain, body.chain); diff --git a/test/infrastructure/NodeHttp.spec.ts b/test/infrastructure/NodeHttp.spec.ts index 52ce4dbc82..e715ee1ae2 100644 --- a/test/infrastructure/NodeHttp.spec.ts +++ b/test/infrastructure/NodeHttp.spec.ts @@ -34,11 +34,10 @@ import { NodeHttp } from '../../src/infrastructure/NodeHttp'; import { NetworkType } from '../../src/model/network/NetworkType'; describe('NodeHttp', () => { - const url = 'http://someHost'; const response: http.IncomingMessage = mock(); const nodeRoutesApi: NodeRoutesApi = mock(); - const nodeRepository = DtoMapping.assign(new NodeHttp(url), {nodeRoutesApi: instance(nodeRoutesApi)}); + const nodeRepository = DtoMapping.assign(new NodeHttp(url), { nodeRoutesApi: instance(nodeRoutesApi) }); before(() => { reset(response); @@ -46,13 +45,12 @@ describe('NodeHttp', () => { }); it('getNodeHealth', async () => { - const body = new NodeHealthInfoDTO(); body.status = new NodeHealthDTO(); body.status.apiNode = NodeStatusEnum.Down; body.status.db = NodeStatusEnum.Up; - when(nodeRoutesApi.getNodeHealth()).thenReturn(Promise.resolve({response, body})); + when(nodeRoutesApi.getNodeHealth()).thenReturn(Promise.resolve({ response, body })); const nodeHealth = await nodeRepository.getNodeHealth().toPromise(); expect(nodeHealth).to.be.not.null; @@ -61,13 +59,12 @@ describe('NodeHttp', () => { }); it('getServerInfo', async () => { - const body = new ServerInfoDTO(); body.serverInfo = new ServerDTO(); body.serverInfo.restVersion = 'Some Rest Version'; body.serverInfo.sdkVersion = 'Some SDK Version'; - when(nodeRoutesApi.getServerInfo()).thenReturn(Promise.resolve({response, body})); + when(nodeRoutesApi.getServerInfo()).thenReturn(Promise.resolve({ response, body })); const serverInfo = await nodeRepository.getServerInfo().toPromise(); expect(serverInfo).to.be.not.null; @@ -76,7 +73,6 @@ describe('NodeHttp', () => { }); it('getNodeInfo', async () => { - const body = new NodeInfoDTO(); body.networkIdentifier = NetworkType.TEST_NET; body.friendlyName = 'Some Friendly name'; @@ -87,7 +83,7 @@ describe('NodeHttp', () => { body.roles = RolesTypeEnum.NUMBER_1; body.version = 4567; - when(nodeRoutesApi.getNodeInfo()).thenReturn(Promise.resolve({response, body})); + when(nodeRoutesApi.getNodeInfo()).thenReturn(Promise.resolve({ response, body })); const nodeInfo = await nodeRepository.getNodeInfo().toPromise(); expect(nodeInfo).to.be.not.null; @@ -95,7 +91,6 @@ describe('NodeHttp', () => { }); it('getNodePeers', async () => { - const body = new NodeInfoDTO(); body.networkIdentifier = NetworkType.TEST_NET; body.friendlyName = 'Some Friendly name'; @@ -106,7 +101,7 @@ describe('NodeHttp', () => { body.roles = RolesTypeEnum.NUMBER_1; body.version = 4567; - when(nodeRoutesApi.getNodePeers()).thenReturn(Promise.resolve({response, body: [body]})); + when(nodeRoutesApi.getNodePeers()).thenReturn(Promise.resolve({ response, body: [body] })); const nodeInfoList = await nodeRepository.getNodePeers().toPromise(); const nodeInfo = nodeInfoList[0]; @@ -115,13 +110,12 @@ describe('NodeHttp', () => { }); it('getNodeTime', async () => { - const body = new NodeTimeDTO(); body.communicationTimestamps = new CommunicationTimestampsDTO(); body.communicationTimestamps.receiveTimestamp = '1111'; body.communicationTimestamps.sendTimestamp = '2222'; - when(nodeRoutesApi.getNodeTime()).thenReturn(Promise.resolve({response, body})); + when(nodeRoutesApi.getNodeTime()).thenReturn(Promise.resolve({ response, body })); const nodeTime = await nodeRepository.getNodeTime().toPromise(); expect(nodeTime).to.be.not.null; @@ -132,12 +126,11 @@ describe('NodeHttp', () => { }); it('getNodeTim When No Timestamp', async () => { - const body = new NodeTimeDTO(); body.communicationTimestamps = new CommunicationTimestampsDTO(); body.communicationTimestamps.receiveTimestamp = '1111'; - when(nodeRoutesApi.getNodeTime()).thenReturn(Promise.resolve({response, body})); + when(nodeRoutesApi.getNodeTime()).thenReturn(Promise.resolve({ response, body })); try { await nodeRepository.getNodeTime().toPromise(); @@ -147,28 +140,29 @@ describe('NodeHttp', () => { }); it('getStorageInfo', async () => { - const body = new StorageInfoDTO(); body.numAccounts = 1; body.numBlocks = 2; body.numTransactions = 3; - when(nodeRoutesApi.getNodeStorage()).thenReturn(Promise.resolve({response, body})); + when(nodeRoutesApi.getNodeStorage()).thenReturn(Promise.resolve({ response, body })); const storageInfo = await nodeRepository.getStorageInfo().toPromise(); expect(storageInfo).to.deep.equals(body); }); it('getStorageInfo on Exception', async () => { - - when(nodeRoutesApi.getNodeStorage()).thenReturn(Promise.reject({ - response: {statusCode: 500, statusMessage: 'Some Error', body: 'The Body'}, - })); + when(nodeRoutesApi.getNodeStorage()).thenReturn( + Promise.reject({ + response: { statusCode: 500, statusMessage: 'Some Error', body: 'The Body' }, + }), + ); try { await nodeRepository.getStorageInfo().toPromise(); } catch (e) { - expect(e.message).to.deep.equals('{"statusCode":500,"errorDetails":{"statusCode":500,"statusMessage":"Some Error"},"body":"The Body"}'); + expect(e.message).to.deep.equals( + '{"statusCode":500,"errorDetails":{"statusCode":500,"statusMessage":"Some Error"},"body":"The Body"}', + ); } - }); }); diff --git a/test/infrastructure/QueryParams.spec.ts b/test/infrastructure/QueryParams.spec.ts new file mode 100644 index 0000000000..b5ab7b2f7d --- /dev/null +++ b/test/infrastructure/QueryParams.spec.ts @@ -0,0 +1,38 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { QueryParams, Order } from '../../src/infrastructure/QueryParams'; +import { expect } from 'chai'; + +describe('QueryParams', () => { + it('should create QueryParams', () => { + const queryParam = new QueryParams(); + expect(queryParam.id).to.be.undefined; + expect(queryParam.order.toString()).to.be.equal('-id'); + expect(queryParam.pageSize).to.be.equal(10); + }); + + it('should create QueryParams with arg', () => { + const queryParam = new QueryParams({ id: '1', order: Order.ASC, pageSize: 25 }); + expect(queryParam.id).to.be.equal('1'); + expect(queryParam.order.toString()).to.be.equal('id'); + expect(queryParam.pageSize).to.be.equal(25); + }); + + it('should not set pageSize > 100', () => { + expect(() => new QueryParams({ id: '1', order: Order.ASC, pageSize: 200 })).to.throw(); + }); +}); diff --git a/test/infrastructure/RepositoryFactory.spec.ts b/test/infrastructure/RepositoryFactory.spec.ts index 269960b59a..7041880d53 100644 --- a/test/infrastructure/RepositoryFactory.spec.ts +++ b/test/infrastructure/RepositoryFactory.spec.ts @@ -41,21 +41,20 @@ describe('RepositoryFactory', () => { expect(repositoryFactory.createRestrictionAccountRepository()).to.be.not.null; expect(repositoryFactory.createRestrictionMosaicRepository()).to.be.not.null; expect(repositoryFactory.createTransactionRepository()).to.be.not.null; - }); it('Should get GenerationHash from cache', (done) => { - let counter = 0; const repositoryMock: BlockRepository = mock(); - const observableOfBlockInfo = observableOf({generationHash: 'aaaa'} as BlockInfo).pipe(map((v) => { - counter++; - return v; - })); + const observableOfBlockInfo = observableOf({ generationHash: 'aaaa' } as BlockInfo).pipe( + map((v) => { + counter++; + return v; + }), + ); when(repositoryMock.getBlockByHeight(deepEqual(UInt64.fromUint(1)))).thenReturn(observableOfBlockInfo); expect(observableOfBlockInfo).to.be.equals(observableOfBlockInfo); const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { - createBlockRepository(): BlockRepository { return instance(repositoryMock); } @@ -78,19 +77,19 @@ describe('RepositoryFactory', () => { }); it('Should get NetworkType from cache', (done) => { - let counter = 0; const repositoryMock: NetworkRepository = mock(); const expectedNetworkType = NetworkType.MIJIN_TEST; - const observableOfBlockInfo = observableOf(expectedNetworkType).pipe(map((v) => { - counter++; - return v; - })); + const observableOfBlockInfo = observableOf(expectedNetworkType).pipe( + map((v) => { + counter++; + return v; + }), + ); when(repositoryMock.getNetworkType()).thenReturn(observableOfBlockInfo); expect(observableOfBlockInfo).to.be.equals(observableOfBlockInfo); - // tslint:disable-next-line: max-classes-per-file const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNetworkRepository(): NetworkRepository { return instance(repositoryMock); @@ -107,25 +106,24 @@ describe('RepositoryFactory', () => { done(); }); }); - }); it('Should get NetworkType from memory', (done) => { - let counter = 0; const repositoryMock: NetworkRepository = mock(); const expectedNetworkType = NetworkType.MIJIN_TEST; - const observableOfBlockInfo = observableOf(expectedNetworkType).pipe(map((v) => { - counter++; - return v; - })); + const observableOfBlockInfo = observableOf(expectedNetworkType).pipe( + map((v) => { + counter++; + return v; + }), + ); when(repositoryMock.getNetworkType()).thenReturn(observableOfBlockInfo); expect(observableOfBlockInfo).to.be.equals(observableOfBlockInfo); - // tslint:disable-next-line: max-classes-per-file const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNetworkRepository(): NetworkRepository { return instance(repositoryMock); @@ -142,7 +140,5 @@ describe('RepositoryFactory', () => { done(); }); }); - }); - }); diff --git a/test/infrastructure/SerializeTransactionToJSON.spec.ts b/test/infrastructure/SerializeTransactionToJSON.spec.ts index e94620a4e8..e30003ef8a 100644 --- a/test/infrastructure/SerializeTransactionToJSON.spec.ts +++ b/test/infrastructure/SerializeTransactionToJSON.spec.ts @@ -35,7 +35,7 @@ import { AccountRestrictionTransaction } from '../../src/model/transaction/Accou import { AddressAliasTransaction } from '../../src/model/transaction/AddressAliasTransaction'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; -import { HashType } from '../../src/model/transaction/HashType'; +import { LockHashAlgorithm } from '../../src/model/transaction/LockHashAlgorithm'; import { LinkAction } from '../../src/model/transaction/LinkAction'; import { LockFundsTransaction } from '../../src/model/transaction/LockFundsTransaction'; import { MosaicAliasTransaction } from '../../src/model/transaction/MosaicAliasTransaction'; @@ -153,13 +153,12 @@ describe('SerializeTransactionToJSON', () => { expect(json.transaction.type).to.be.equal(TransactionType.MOSAIC_ALIAS); expect(json.transaction.aliasAction).to.be.equal(AliasAction.Link); - }); it('should create MosaicDefinitionTransaction', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(true, true, true), 5, @@ -173,13 +172,12 @@ describe('SerializeTransactionToJSON', () => { expect(json.transaction.flags).to.be.equal(7); expect(json.transaction.divisibility).to.be.equal(5); expect(json.transaction.duration).to.be.equal('1000'); - }); it('should create MosaicDefinitionTransaction without duration', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(true, false), 3, @@ -192,7 +190,6 @@ describe('SerializeTransactionToJSON', () => { expect(json.transaction.type).to.be.equal(TransactionType.MOSAIC_DEFINITION); expect(json.transaction.divisibility).to.be.equal(3); expect(json.transaction.flags).to.be.equal(1); - }); it('should create MosaicSupplyChangeTransaction', () => { @@ -209,16 +206,13 @@ describe('SerializeTransactionToJSON', () => { expect(json.transaction.type).to.be.equal(TransactionType.MOSAIC_SUPPLY_CHANGE); expect(json.transaction.action).to.be.equal(MosaicSupplyChangeAction.Increase); - }); it('should create TransferTransaction', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); @@ -228,7 +222,6 @@ describe('SerializeTransactionToJSON', () => { expect(json.transaction.type).to.be.equal(TransactionType.TRANSFER); expect(json.transaction.message.payload).to.be.equal('test-message'); expect(json.transaction.message.type).to.be.equal(0); - }); it('should create SecretLockTransaction', () => { @@ -238,7 +231,7 @@ describe('SerializeTransactionToJSON', () => { Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, @@ -247,15 +240,14 @@ describe('SerializeTransactionToJSON', () => { const json = secretLockTransaction.toJSON(); expect(json.transaction.type).to.be.equal(TransactionType.SECRET_LOCK); - expect(json.transaction.hashAlgorithm).to.be.equal(HashType.Op_Sha3_256); - + expect(json.transaction.hashAlgorithm).to.be.equal(LockHashAlgorithm.Op_Sha3_256); }); it('should create SecretProofTransaction', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), account.address, proof, @@ -265,10 +257,9 @@ describe('SerializeTransactionToJSON', () => { const json = secretProofTransaction.toJSON(); expect(json.transaction.type).to.be.equal(TransactionType.SECRET_PROOF); - expect(json.transaction.hashAlgorithm).to.be.equal(HashType.Op_Sha3_256); + expect(json.transaction.hashAlgorithm).to.be.equal(LockHashAlgorithm.Op_Sha3_256); expect(json.transaction.secret).to.be.equal(sha3_256.create().update(convert.hexToUint8(proof)).hex()); expect(json.transaction.proof).to.be.equal(proof); - }); it('should create ModifyMultiSigTransaction', () => { @@ -276,8 +267,7 @@ describe('SerializeTransactionToJSON', () => { Deadline.create(), 2, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST)], + [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', NetworkType.MIJIN_TEST)], [], NetworkType.MIJIN_TEST, ); @@ -302,7 +292,8 @@ describe('SerializeTransactionToJSON', () => { Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const json = aggregateTransaction.toJSON(); @@ -323,7 +314,8 @@ describe('SerializeTransactionToJSON', () => { Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const json = aggregateTransaction.toJSON(); @@ -333,18 +325,15 @@ describe('SerializeTransactionToJSON', () => { it('should create LockFundTransaction', () => { const generationHash = '57F7DA205008026C776CB6AED843393F04CD458E0AA2D9F1D5F31A402072B2D6'; - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockTransaction = LockFundsTransaction.create(Deadline.create(), + const lockTransaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, + ); const json = lockTransaction.toJSON(); @@ -363,7 +352,6 @@ describe('SerializeTransactionToJSON', () => { const json = registerNamespaceTransaction.toJSON(); expect(json.transaction.type).to.be.equal(TransactionType.NAMESPACE_REGISTRATION); - }); it('should create NamespaceRegistrationTransaction - Sub', () => { diff --git a/test/infrastructure/TransactionHttp.spec.ts b/test/infrastructure/TransactionHttp.spec.ts index dcee18bdfa..daf8af3625 100644 --- a/test/infrastructure/TransactionHttp.spec.ts +++ b/test/infrastructure/TransactionHttp.spec.ts @@ -47,9 +47,7 @@ describe('TransactionHttp', () => { ); const aggTx = AggregateTransaction.createComplete( Deadline.create(), - [ - tx.toAggregate(account.publicAccount), - ], + [tx.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, [], ); @@ -57,9 +55,7 @@ describe('TransactionHttp', () => { const signedTx = account.sign(aggTx, generationHash); const trnsHttp = new TransactionHttp(NIS2_URL); expect(() => { - trnsHttp.announceAggregateBonded(signedTx) - .toPromise() - .then(); + trnsHttp.announceAggregateBonded(signedTx).toPromise().then(); }).to.throw(Error, 'Only Transaction Type 0x4241 is allowed for announce aggregate bonded'); }); @@ -86,8 +82,9 @@ describe('TransactionHttp', () => { transactionStatusDTO.group = TransactionStateTypeEnum.Failed; transactionStatusDTO.height = '567'; - when(transactionRoutesApi.getTransactionStatus(deepEqual(hash))) - .thenReturn(Promise.resolve({response: instance(clientResponse), body: transactionStatusDTO})); + when(transactionRoutesApi.getTransactionStatus(deepEqual(hash))).thenReturn( + Promise.resolve({ response: instance(clientResponse), body: transactionStatusDTO }), + ); const transactionStatus = await transactionHttp.getTransactionStatus(hash).toPromise(); @@ -105,8 +102,9 @@ describe('TransactionHttp', () => { transactionStatusDTO.hash = hash; transactionStatusDTO.group = TransactionStateTypeEnum.Failed; transactionStatusDTO.height = '567'; - when(transactionRoutesApi.getTransactionsStatuses(deepEqual({hashes: [hash]}))) - .thenReturn(Promise.resolve({response: instance(clientResponse), body: [transactionStatusDTO]})); + when(transactionRoutesApi.getTransactionsStatuses(deepEqual({ hashes: [hash] }))).thenReturn( + Promise.resolve({ response: instance(clientResponse), body: [transactionStatusDTO] }), + ); const transactionStatuses = await transactionHttp.getTransactionsStatuses([hash]).toPromise(); expect(transactionStatuses.length).to.be.equal(1); @@ -116,6 +114,5 @@ describe('TransactionHttp', () => { expect(transactionStatus.hash).to.be.equal(hash); expect(transactionStatus.code).to.be.equal('Failure_AccountLink_Invalid_Action'); expect(transactionStatus.group).to.be.equal('failed'); - }); }); diff --git a/test/infrastructure/receipt/CreateReceiptFromDTO.spec.ts b/test/infrastructure/receipt/CreateReceiptFromDTO.spec.ts index 20f4047ed1..8158349ee5 100644 --- a/test/infrastructure/receipt/CreateReceiptFromDTO.spec.ts +++ b/test/infrastructure/receipt/CreateReceiptFromDTO.spec.ts @@ -17,7 +17,7 @@ import { deepEqual } from 'assert'; import { expect } from 'chai'; import { CreateStatementFromDTO } from '../../../src/infrastructure/receipt/CreateReceiptFromDTO'; -import {Account} from '../../../src/model/account/Account'; +import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; @@ -27,97 +27,97 @@ import { UInt64 } from '../../../src/model/UInt64'; describe('Receipt - CreateStatementFromDTO', () => { let account: Account; - let account2: Account; let statementDto; const netWorkType = NetworkType.MIJIN_TEST; before(() => { account = Account.createFromPrivateKey('D242FB34C2C4DD36E995B9C865F93940065E326661BA5A4A247331D211FE3A3D', NetworkType.MIJIN_TEST); - account2 = Account.createFromPrivateKey('E5DCCEBDB01A8B03A7DB7BA5888E2E33FD4617B5F6FED48C4C09C0780F422713', NetworkType.MIJIN_TEST); - statementDto = {transactionStatements: [ - { - statement: { - height: '52', - source: { - primaryId: 0, - secondaryId: 0, - }, - receipts: [ - { - version: 1, - type: 8515, - targetPublicKey: account.publicKey, - mosaicId: '85BBEA6CC462B244', - amount: '1000', + statementDto = { + transactionStatements: [ + { + statement: { + height: '52', + source: { + primaryId: 0, + secondaryId: 0, + }, + receipts: [ + { + version: 1, + type: 8515, + targetPublicKey: account.publicKey, + mosaicId: '85BBEA6CC462B244', + amount: '1000', + }, + ], }, - ], - }, - }, - ], - addressResolutionStatements: [ - { - statement: { - height: '1488', - unresolved: '9103B60AAF2762688300000000000000000000000000000000', - resolutionEntries: [ + }, + ], + addressResolutionStatements: [ { - source: { - primaryId: 4, - secondaryId: 0, + statement: { + height: '1488', + unresolved: '9103B60AAF2762688300000000000000000000000000000000', + resolutionEntries: [ + { + source: { + primaryId: 4, + secondaryId: 0, + }, + resolved: '917E7E29A01014C2F300000000000000000000000000000000', + }, + ], }, - resolved: '917E7E29A01014C2F300000000000000000000000000000000', }, - ], - }, - }, - { - statement: { - height: '1488', - unresolved: '917E7E29A01014C2F300000000000000000000000000000000', - resolutionEntries: [ { - source: { - primaryId: 2, - secondaryId: 0, + statement: { + height: '1488', + unresolved: '917E7E29A01014C2F300000000000000000000000000000000', + resolutionEntries: [ + { + source: { + primaryId: 2, + secondaryId: 0, + }, + resolved: '9103B60AAF2762688300000000000000000000000000000000', + }, + ], }, - resolved: '9103B60AAF2762688300000000000000000000000000000000', }, - ], - }, - }, - ], - mosaicResolutionStatements: [ - { - statement: { - height: '1506', - unresolved: '85BBEA6CC462B244', - resolutionEntries: [ + ], + mosaicResolutionStatements: [ { - source: { - primaryId: 1, - secondaryId: 0, + statement: { + height: '1506', + unresolved: '85BBEA6CC462B244', + resolutionEntries: [ + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '941299B2B7E1291C', + }, + ], }, - resolved: '941299B2B7E1291C', }, - ], - }, - }, - { - statement: { - height: '1506', - unresolved: '85BBEA6CC462B244', - resolutionEntries: [ { - source: { - primaryId: 5, - secondaryId: 0, + statement: { + height: '1506', + unresolved: '85BBEA6CC462B244', + resolutionEntries: [ + { + source: { + primaryId: 5, + secondaryId: 0, + }, + resolved: '941299B2B7E1291C', + }, + ], }, - resolved: '941299B2B7E1291C', }, - ], - }, - }, - ]}; + ], + }; }); it('should create Statement', () => { const statement = CreateStatementFromDTO(statementDto, netWorkType); @@ -137,13 +137,13 @@ describe('Receipt - CreateStatementFromDTO', () => { deepEqual(statement.addressResolutionStatements[0].height, UInt64.fromNumericString('1488')); deepEqual(unresolvedAddress.toHex(), '83686227AF0AB603'); expect(statement.addressResolutionStatements[0].resolutionEntries.length).to.be.equal(1); - expect((statement.addressResolutionStatements[0].resolutionEntries[0].resolved as Address).plain()) - .to.be.equal(Address.createFromEncoded('917E7E29A01014C2F300000000000000000000000000000000').plain()); + expect((statement.addressResolutionStatements[0].resolutionEntries[0].resolved as Address).plain()).to.be.equal( + Address.createFromEncoded('917E7E29A01014C2F300000000000000000000000000000000').plain(), + ); deepEqual(statement.mosaicResolutionStatements[0].height, UInt64.fromNumericString('1506')); deepEqual(unresolvedMosaicId.toHex(), '85BBEA6CC462B244'); expect(statement.mosaicResolutionStatements[0].resolutionEntries.length).to.be.equal(1); - deepEqual((statement.mosaicResolutionStatements[0].resolutionEntries[0].resolved as MosaicId) - .toHex(), '941299B2B7E1291C'); + deepEqual((statement.mosaicResolutionStatements[0].resolutionEntries[0].resolved as MosaicId).toHex(), '941299B2B7E1291C'); }); }); diff --git a/test/infrastructure/transaction/CreateTransactionFromDTO.spec.ts b/test/infrastructure/transaction/CreateTransactionFromDTO.spec.ts index 6b0a855f42..27c805ebc3 100644 --- a/test/infrastructure/transaction/CreateTransactionFromDTO.spec.ts +++ b/test/infrastructure/transaction/CreateTransactionFromDTO.spec.ts @@ -22,7 +22,6 @@ import ValidateTransaction from './ValidateTransaction'; describe('CreateTransactionFromDTO', () => { describe('TransferTransaction', () => { - it('standalone', () => { const transferTransactionDTO = { meta: { @@ -33,8 +32,8 @@ describe('CreateTransactionFromDTO', () => { id: '5CD2B76B2B3F0F0001751380', }, transaction: { - // tslint:disable-next-line:max-line-length - signature: '7442156D839A3AC900BC0299E8701ECDABA674DCF91283223450953B005DE72C538EA54236F5E089530074CE78067CD3325CF53750B9118154C08B20A5CDC00D', + signature: + '7442156D839A3AC900BC0299E8701ECDABA674DCF91283223450953B005DE72C538EA54236F5E089530074CE78067CD3325CF53750B9118154C08B20A5CDC00D', signerPublicKey: '2FC3872A792933617D70E02AFF8FBDE152821A0DF0CA5FB04CB56FC3D21C8863', version: 1, network: 144, @@ -70,8 +69,8 @@ describe('CreateTransactionFromDTO', () => { id: '5CD2B76B2B3F0F0001751380', }, transaction: { - // tslint:disable-next-line:max-line-length - signature: '7442156D839A3AC900BC0299E8701ECDABA674DCF91283223450953B005DE72C538EA54236F5E089530074CE78067CD3325CF53750B9118154C08B20A5CDC00D', + signature: + '7442156D839A3AC900BC0299E8701ECDABA674DCF91283223450953B005DE72C538EA54236F5E089530074CE78067CD3325CF53750B9118154C08B20A5CDC00D', signerPublicKey: '2FC3872A792933617D70E02AFF8FBDE152821A0DF0CA5FB04CB56FC3D21C8863', version: 1, network: 144, @@ -105,15 +104,17 @@ describe('CreateTransactionFromDTO', () => { transaction: { cosignatures: [ { - signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + - 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', + signature: + '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + - '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { @@ -139,7 +140,7 @@ describe('CreateTransactionFromDTO', () => { signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16724, version: 1, - network: 144, + network: 144, }, }, ], @@ -173,12 +174,13 @@ describe('CreateTransactionFromDTO', () => { name: 'a2p1mg', id: '85BBEA6CC462B244', registrationType: 0, - signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + - '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', + signature: + '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + + '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16718, version: 1, - network: 144, + network: 144, }, }; @@ -199,15 +201,17 @@ describe('CreateTransactionFromDTO', () => { transaction: { cosignatures: [ { - signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + - 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', + signature: + '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + - '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { @@ -226,22 +230,22 @@ describe('CreateTransactionFromDTO', () => { signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16718, version: 1, - network: 144, + network: 144, }, }, ], type: 16705, version: 1, - network: 144, + network: 144, }, }; - const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO( - aggregateNamespaceRegistrationTransactionDTO, - ); + const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO(aggregateNamespaceRegistrationTransactionDTO); ValidateTransaction.validateAggregateTx( - aggregateNamespaceRegistrationTransaction, aggregateNamespaceRegistrationTransactionDTO); + aggregateNamespaceRegistrationTransaction, + aggregateNamespaceRegistrationTransactionDTO, + ); }); }); @@ -262,12 +266,13 @@ describe('CreateTransactionFromDTO', () => { id: '99BBEA6CC462B244', registrationType: 1, parentId: '85BBEA6CC462B244', - signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9' + - 'E02F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', + signature: + '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9' + + 'E02F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16718, version: 1, - network: 144, + network: 144, }, }; const transferTransaction = CreateTransactionFromDTO(registerNamespaceTransactionDTO); @@ -287,15 +292,17 @@ describe('CreateTransactionFromDTO', () => { transaction: { cosignatures: [ { - signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + - 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', + signature: + '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + - '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { @@ -314,21 +321,22 @@ describe('CreateTransactionFromDTO', () => { signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16718, version: 1, - network: 144, + network: 144, }, }, ], type: 16705, version: 1, - network: 144, + network: 144, }, }; - const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO( - aggregateNamespaceRegistrationTransactionDTO); + const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO(aggregateNamespaceRegistrationTransactionDTO); ValidateTransaction.validateAggregateTx( - aggregateNamespaceRegistrationTransaction, aggregateNamespaceRegistrationTransactionDTO); + aggregateNamespaceRegistrationTransaction, + aggregateNamespaceRegistrationTransactionDTO, + ); }); }); }); @@ -351,8 +359,9 @@ describe('CreateTransactionFromDTO', () => { flags: 7, diversibility: 6, duration: '1000', - signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E02F6EE63025FE' + - 'EBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', + signature: + '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E02F6EE63025FE' + + 'EBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16717, version: 1, @@ -377,15 +386,17 @@ describe('CreateTransactionFromDTO', () => { transaction: { cosignatures: [ { - signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + - 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', + signature: + '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + - '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { @@ -405,7 +416,7 @@ describe('CreateTransactionFromDTO', () => { signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16717, version: 1, - network: 144, + network: 144, }, }, ], @@ -415,11 +426,9 @@ describe('CreateTransactionFromDTO', () => { }, }; - const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO( - aggregateMosaicDefinitionTransactionDTO); + const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO(aggregateMosaicDefinitionTransactionDTO); - ValidateTransaction.validateAggregateTx( - aggregateNamespaceRegistrationTransaction, aggregateMosaicDefinitionTransactionDTO); + ValidateTransaction.validateAggregateTx(aggregateNamespaceRegistrationTransaction, aggregateMosaicDefinitionTransactionDTO); }); }); @@ -439,8 +448,9 @@ describe('CreateTransactionFromDTO', () => { action: 1, maxFee: '0', mosaicId: '85BBEA6CC462B244', - signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + - '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', + signature: + '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + + '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16973, version: 1, @@ -465,15 +475,17 @@ describe('CreateTransactionFromDTO', () => { transaction: { cosignatures: [ { - signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + - 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', + signature: + '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + - '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { @@ -491,7 +503,7 @@ describe('CreateTransactionFromDTO', () => { signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16973, version: 1, - network: 144, + network: 144, }, }, ], @@ -501,11 +513,9 @@ describe('CreateTransactionFromDTO', () => { }, }; - const aggregateMosaicSupplyChangeTransaction = CreateTransactionFromDTO( - aggregateMosaicSupplyChangeTransactionDTO); + const aggregateMosaicSupplyChangeTransaction = CreateTransactionFromDTO(aggregateMosaicSupplyChangeTransactionDTO); - ValidateTransaction.validateAggregateTx( - aggregateMosaicSupplyChangeTransaction, aggregateMosaicSupplyChangeTransactionDTO); + ValidateTransaction.validateAggregateTx(aggregateMosaicSupplyChangeTransaction, aggregateMosaicSupplyChangeTransactionDTO); }); }); @@ -526,8 +536,9 @@ describe('CreateTransactionFromDTO', () => { minRemovalDelta: 1, publicKeyAdditions: ['76C1622C7FB58986E500228E8FFB30C606CAAFC1CD78E770E82C73DAB7BD7C9F'], publicKeyDeletions: [], - signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + - '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', + signature: + '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + + '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16725, version: 1, @@ -537,8 +548,7 @@ describe('CreateTransactionFromDTO', () => { const modifyMultisigAccountTransaction = CreateTransactionFromDTO(modifyMultisigAccountTransactionDTO); - ValidateTransaction.validateStandaloneTx( - modifyMultisigAccountTransaction, modifyMultisigAccountTransactionDTO); + ValidateTransaction.validateStandaloneTx(modifyMultisigAccountTransaction, modifyMultisigAccountTransactionDTO); }); it('aggregate', () => { @@ -553,15 +563,17 @@ describe('CreateTransactionFromDTO', () => { transaction: { cosignatures: [ { - signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + - 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', + signature: + '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + - '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { @@ -580,7 +592,7 @@ describe('CreateTransactionFromDTO', () => { signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16725, version: 1, - network: 144, + network: 144, }, }, ], @@ -591,10 +603,13 @@ describe('CreateTransactionFromDTO', () => { }; const aggregateMultisigAccountModificationTransaction = CreateTransactionFromDTO( - aggregateMultisigAccountModificationTransactionDTO); + aggregateMultisigAccountModificationTransactionDTO, + ); ValidateTransaction.validateAggregateTx( - aggregateMultisigAccountModificationTransaction, aggregateMultisigAccountModificationTransactionDTO); + aggregateMultisigAccountModificationTransaction, + aggregateMultisigAccountModificationTransactionDTO, + ); }); }); }); diff --git a/test/infrastructure/transaction/ValidateTransaction.ts b/test/infrastructure/transaction/ValidateTransaction.ts index 344423922c..b236d61561 100644 --- a/test/infrastructure/transaction/ValidateTransaction.ts +++ b/test/infrastructure/transaction/ValidateTransaction.ts @@ -23,32 +23,20 @@ import { TransactionType } from '../../../src/model/transaction/TransactionType' import { UInt64 } from '../../../src/model/UInt64'; const ValidateTransaction = { - validateStandaloneTx: (transaction, transactionDTO) => { - deepEqual(transaction.transactionInfo.height, - UInt64.fromNumericString(transactionDTO.meta.height)); - expect(transaction.transactionInfo.hash) - .to.be.equal(transactionDTO.meta.hash); - expect(transaction.transactionInfo.merkleComponentHash) - .to.be.equal(transactionDTO.meta.merkleComponentHash); - expect(transaction.transactionInfo.index) - .to.be.equal(transactionDTO.meta.index); - expect(transaction.transactionInfo.id) - .to.be.equal(transactionDTO.meta.id); + validateStandaloneTx: (transaction: any, transactionDTO: any): void => { + deepEqual(transaction.transactionInfo.height, UInt64.fromNumericString(transactionDTO.meta.height)); + expect(transaction.transactionInfo.hash).to.be.equal(transactionDTO.meta.hash); + expect(transaction.transactionInfo.merkleComponentHash).to.be.equal(transactionDTO.meta.merkleComponentHash); + expect(transaction.transactionInfo.index).to.be.equal(transactionDTO.meta.index); + expect(transaction.transactionInfo.id).to.be.equal(transactionDTO.meta.id); - expect(transaction.signature) - .to.be.equal(transactionDTO.transaction.signature); - expect(transaction.signer.publicKey) - .to.be.equal(transactionDTO.transaction.signerPublicKey); - expect(transaction.networkType) - .to.be.equal(transactionDTO.transaction.network); - expect(transaction.version) - .to.be.equal(transactionDTO.transaction.version); - expect(transaction.type) - .to.be.equal(transactionDTO.transaction.type); - deepEqual(transaction.maxFee, - UInt64.fromNumericString(transactionDTO.transaction.maxFee)); - deepEqual(transaction.deadline.toString(), - transactionDTO.transaction.deadline); + expect(transaction.signature).to.be.equal(transactionDTO.transaction.signature); + expect(transaction.signer.publicKey).to.be.equal(transactionDTO.transaction.signerPublicKey); + expect(transaction.networkType).to.be.equal(transactionDTO.transaction.network); + expect(transaction.version).to.be.equal(transactionDTO.transaction.version); + expect(transaction.type).to.be.equal(transactionDTO.transaction.type); + deepEqual(transaction.maxFee, UInt64.fromNumericString(transactionDTO.transaction.maxFee)); + deepEqual(transaction.deadline.toString(), transactionDTO.transaction.deadline); if (transaction.type === TransactionType.TRANSFER) { ValidateTransaction.validateTransferTx(transaction, transactionDTO); @@ -62,87 +50,69 @@ const ValidateTransaction = { ValidateTransaction.validateMultisigModificationTx(transaction, transactionDTO); } }, - validateAggregateTx: (aggregateTransaction, aggregateTransactionDTO) => { - deepEqual(aggregateTransaction.transactionInfo.height, - UInt64.fromNumericString(aggregateTransactionDTO.meta.height)); - expect(aggregateTransaction.transactionInfo.hash) - .to.be.equal(aggregateTransactionDTO.meta.hash); - expect(aggregateTransaction.transactionInfo.merkleComponentHash) - .to.be.equal(aggregateTransactionDTO.meta.merkleComponentHash); - expect(aggregateTransaction.transactionInfo.index) - .to.be.equal(aggregateTransactionDTO.meta.index); - expect(aggregateTransaction.transactionInfo.id) - .to.be.equal(aggregateTransactionDTO.meta.id); + validateAggregateTx: (aggregateTransaction: any, aggregateTransactionDTO: any): void => { + deepEqual(aggregateTransaction.transactionInfo.height, UInt64.fromNumericString(aggregateTransactionDTO.meta.height)); + expect(aggregateTransaction.transactionInfo.hash).to.be.equal(aggregateTransactionDTO.meta.hash); + expect(aggregateTransaction.transactionInfo.merkleComponentHash).to.be.equal(aggregateTransactionDTO.meta.merkleComponentHash); + expect(aggregateTransaction.transactionInfo.index).to.be.equal(aggregateTransactionDTO.meta.index); + expect(aggregateTransaction.transactionInfo.id).to.be.equal(aggregateTransactionDTO.meta.id); - expect(aggregateTransaction.signature) - .to.be.equal(aggregateTransactionDTO.transaction.signature); - expect(aggregateTransaction.signer.publicKey) - .to.be.equal(aggregateTransactionDTO.transaction.signerPublicKey); - expect(aggregateTransaction.networkType) - .to.be.equal(aggregateTransactionDTO.transaction.network); - expect(aggregateTransaction.version) - .to.be.equal(aggregateTransactionDTO.transaction.version); - expect(aggregateTransaction.type) - .to.be.equal(aggregateTransactionDTO.transaction.type); - deepEqual(aggregateTransaction.maxFee, - UInt64.fromNumericString(aggregateTransactionDTO.transaction.maxFee)); - deepEqual(aggregateTransaction.deadline.toString(), - aggregateTransactionDTO.transaction.deadline); + expect(aggregateTransaction.signature).to.be.equal(aggregateTransactionDTO.transaction.signature); + expect(aggregateTransaction.signer.publicKey).to.be.equal(aggregateTransactionDTO.transaction.signerPublicKey); + expect(aggregateTransaction.networkType).to.be.equal(aggregateTransactionDTO.transaction.network); + expect(aggregateTransaction.version).to.be.equal(aggregateTransactionDTO.transaction.version); + expect(aggregateTransaction.type).to.be.equal(aggregateTransactionDTO.transaction.type); + deepEqual(aggregateTransaction.maxFee, UInt64.fromNumericString(aggregateTransactionDTO.transaction.maxFee)); + deepEqual(aggregateTransaction.deadline.toString(), aggregateTransactionDTO.transaction.deadline); - ValidateTransaction.validateStandaloneTx(aggregateTransaction.innerTransactions[0], - aggregateTransactionDTO.transaction.transactions[0]); + ValidateTransaction.validateStandaloneTx( + aggregateTransaction.innerTransactions[0], + aggregateTransactionDTO.transaction.transactions[0], + ); }, - validateMosaicCreationTx: (mosaicDefinitionTransaction, mosaicDefinitionTransactionDTO) => { + validateMosaicCreationTx: (mosaicDefinitionTransaction: any, mosaicDefinitionTransactionDTO: any): void => { + deepEqual(mosaicDefinitionTransaction.mosaicId, new MosaicId(mosaicDefinitionTransactionDTO.transaction.id)); + expect(mosaicDefinitionTransaction.divisibility).to.be.equal(mosaicDefinitionTransactionDTO.transaction.divisibility); + deepEqual(mosaicDefinitionTransaction.duration, UInt64.fromNumericString(mosaicDefinitionTransactionDTO.transaction.duration)); - deepEqual(mosaicDefinitionTransaction.mosaicId, - new MosaicId(mosaicDefinitionTransactionDTO.transaction.id)); - expect(mosaicDefinitionTransaction.divisibility) - .to.be.equal(mosaicDefinitionTransactionDTO.transaction.divisibility); - deepEqual(mosaicDefinitionTransaction.duration, - UInt64.fromNumericString(mosaicDefinitionTransactionDTO.transaction.duration)); - - expect(mosaicDefinitionTransaction.flags.supplyMutable) - .to.be.equal(true); - expect(mosaicDefinitionTransaction.flags.transferable) - .to.be.equal(true); + expect(mosaicDefinitionTransaction.flags.supplyMutable).to.be.equal(true); + expect(mosaicDefinitionTransaction.flags.transferable).to.be.equal(true); }, - validateMosaicSupplyChangeTx: (mosaicSupplyChangeTransaction, mosaicSupplyChangeTransactionDTO) => { - deepEqual(mosaicSupplyChangeTransaction.mosaicId, - new MosaicId(mosaicSupplyChangeTransactionDTO.transaction.mosaicId)); - expect(mosaicSupplyChangeTransaction.action) - .to.be.equal(mosaicSupplyChangeTransactionDTO.transaction.action); - deepEqual(mosaicSupplyChangeTransaction.delta, - UInt64.fromNumericString(mosaicSupplyChangeTransactionDTO.transaction.delta)); + validateMosaicSupplyChangeTx: (mosaicSupplyChangeTransaction: any, mosaicSupplyChangeTransactionDTO: any): void => { + deepEqual(mosaicSupplyChangeTransaction.mosaicId, new MosaicId(mosaicSupplyChangeTransactionDTO.transaction.mosaicId)); + expect(mosaicSupplyChangeTransaction.action).to.be.equal(mosaicSupplyChangeTransactionDTO.transaction.action); + deepEqual(mosaicSupplyChangeTransaction.delta, UInt64.fromNumericString(mosaicSupplyChangeTransactionDTO.transaction.delta)); }, - validateMultisigModificationTx: (modifyMultisigAccountTransaction, modifyMultisigAccountTransactionDTO) => { - expect(modifyMultisigAccountTransaction.minApprovalDelta) - .to.be.equal(modifyMultisigAccountTransactionDTO.transaction.minApprovalDelta); - expect(modifyMultisigAccountTransaction.minRemovalDelta) - .to.be.equal(modifyMultisigAccountTransactionDTO.transaction.minRemovalDelta); + validateMultisigModificationTx: (modifyMultisigAccountTransaction: any, modifyMultisigAccountTransactionDTO: any): void => { + expect(modifyMultisigAccountTransaction.minApprovalDelta).to.be.equal( + modifyMultisigAccountTransactionDTO.transaction.minApprovalDelta, + ); + expect(modifyMultisigAccountTransaction.minRemovalDelta).to.be.equal( + modifyMultisigAccountTransactionDTO.transaction.minRemovalDelta, + ); expect(modifyMultisigAccountTransaction.publicKeyAdditions.length).to.be.equal(1); expect(modifyMultisigAccountTransaction.publicKeyDeletions.length).to.be.equal(0); }, - validateNamespaceCreationTx: (registerNamespaceTransaction, registerNamespaceTransactionDTO) => { - expect(registerNamespaceTransaction.registrationType) - .to.be.equal(registerNamespaceTransactionDTO.transaction.registrationType); - expect(registerNamespaceTransaction.namespaceName) - .to.be.equal(registerNamespaceTransactionDTO.transaction.name); - deepEqual(registerNamespaceTransaction.namespaceId, - NamespaceId.createFromEncoded(registerNamespaceTransactionDTO.transaction.id)); + validateNamespaceCreationTx: (registerNamespaceTransaction: any, registerNamespaceTransactionDTO: any): void => { + expect(registerNamespaceTransaction.registrationType).to.be.equal(registerNamespaceTransactionDTO.transaction.registrationType); + expect(registerNamespaceTransaction.namespaceName).to.be.equal(registerNamespaceTransactionDTO.transaction.name); + deepEqual(registerNamespaceTransaction.namespaceId, NamespaceId.createFromEncoded(registerNamespaceTransactionDTO.transaction.id)); if (registerNamespaceTransaction.registrationType === 0) { - deepEqual(registerNamespaceTransaction.duration, - UInt64.fromNumericString(registerNamespaceTransactionDTO.transaction.duration)); + deepEqual( + registerNamespaceTransaction.duration, + UInt64.fromNumericString(registerNamespaceTransactionDTO.transaction.duration), + ); } else { - deepEqual(registerNamespaceTransaction.parentId, - NamespaceId.createFromEncoded(registerNamespaceTransactionDTO.transaction.parentId)); + deepEqual( + registerNamespaceTransaction.parentId, + NamespaceId.createFromEncoded(registerNamespaceTransactionDTO.transaction.parentId), + ); } }, - validateTransferTx: (transferTransaction, transferTransactionDTO) => { - deepEqual(transferTransaction.recipientAddress, - Address.createFromEncoded(transferTransactionDTO.transaction.recipientAddress)); - expect(transferTransaction.message.payload) - .to.be.equal('test-message'); + validateTransferTx: (transferTransaction: any, transferTransactionDTO: any): void => { + deepEqual(transferTransaction.recipientAddress, Address.createFromEncoded(transferTransactionDTO.transaction.recipientAddress)); + expect(transferTransaction.message.payload).to.be.equal('test-message'); }, }; diff --git a/test/model/Id.spec.ts b/test/model/Id.spec.ts index 06a15c5ef5..0965fde57c 100644 --- a/test/model/Id.spec.ts +++ b/test/model/Id.spec.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Id} from '../../src/model/Id'; +import { expect } from 'chai'; +import { Id } from '../../src/model/Id'; describe('Id', () => { describe('toHex()', () => { diff --git a/test/model/UInt64.spec.ts b/test/model/UInt64.spec.ts index b9b70a0490..d91fe652de 100644 --- a/test/model/UInt64.spec.ts +++ b/test/model/UInt64.spec.ts @@ -14,35 +14,28 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {UInt64} from '../../src/model/UInt64'; +import { expect } from 'chai'; +import { UInt64 } from '../../src/model/UInt64'; const hexTestCases = [ { str: '0000000000000000', value: [0, 0], description: '0' }, - { str: '000000000000A1B2', value: [0xA1B2, 0], description: '(0, 8)' }, + { str: '000000000000A1B2', value: [0xa1b2, 0], description: '(0, 8)' }, { str: '0000000012345678', value: [0x12345678, 0], description: '8' }, - { str: '0000ABCD12345678', value: [0x12345678, 0xABCD], description: '(8, 16)' }, - { str: '1234567890ABCDEF', value: [0x90ABCDEF, 0x12345678], description: '16' }, - { str: 'FFFFFFFFFFFFFFFF', value: [0xFFFFFFFF, 0xFFFFFFFF], description: '16 (max value)' }, + { str: '0000ABCD12345678', value: [0x12345678, 0xabcd], description: '(8, 16)' }, + { str: '1234567890ABCDEF', value: [0x90abcdef, 0x12345678], description: '16' }, + { str: 'FFFFFFFFFFFFFFFF', value: [0xffffffff, 0xffffffff], description: '16 (max value)' }, ]; describe('Uint64', () => { - it('should createComplete Uint64 object [0,0]', () => { - const uintArray = [ - 0, - 0, - ]; + const uintArray = [0, 0]; const uint64 = new UInt64(uintArray); expect(uint64.lower).to.be.equal(uintArray[0]); expect(uint64.higher).to.be.equal(uintArray[1]); }); it('should createComplete Uint64 object [20,30]', () => { - const uintArray = [ - 20, - 30, - ]; + const uintArray = [20, 30]; const uint64 = new UInt64(uintArray); expect(uint64.lower).to.be.equal(uintArray[0]); expect(uint64.higher).to.be.equal(uintArray[1]); @@ -73,6 +66,12 @@ describe('Uint64', () => { expect(uint64Compact).to.be.equal(51110867862); }); + it('should compact UInt64 number', () => { + expect(() => { + new UInt64([3866227606, 0x00200000 + 1]).compact(); + }).to.throw(Error, 'Compacted value is greater than Number.Max_Value.'); + }); + it('should fromUint throw exception with negative uint value', () => { expect(() => { UInt64.fromUint(-1); @@ -127,7 +126,9 @@ describe('Uint64', () => { it('cannot parse hex string with invalid characters into uint64', () => { // Assert: - expect(() => { UInt64.fromHex('0000000012345G78'); }).to.throw('unrecognized hex char'); // contains 'G' + expect(() => { + UInt64.fromHex('0000000012345G78'); + }).to.throw('unrecognized hex char'); // contains 'G' }); it('cannot parse hex string with invalid size into uint64', () => { @@ -135,10 +136,18 @@ describe('Uint64', () => { const errorMessage = 'hex string has unexpected size'; // Assert: - expect(() => { UInt64.fromHex(''); }).to.throw(errorMessage); // empty string - expect(() => { UInt64.fromHex('1'); }).to.throw(errorMessage); // odd number of chars - expect(() => { UInt64.fromHex('ABCDEF12'); }).to.throw(errorMessage); // too short - expect(() => { UInt64.fromHex('1234567890ABCDEF12'); }).to.throw(errorMessage); // too long + expect(() => { + UInt64.fromHex(''); + }).to.throw(errorMessage); // empty string + expect(() => { + UInt64.fromHex('1'); + }).to.throw(errorMessage); // odd number of chars + expect(() => { + UInt64.fromHex('ABCDEF12'); + }).to.throw(errorMessage); // too short + expect(() => { + UInt64.fromHex('1234567890ABCDEF12'); + }).to.throw(errorMessage); // too long }); }); }); @@ -156,8 +165,12 @@ describe('Uint64', () => { expect(uint64_2.higher).to.be.equal(11); }); it('should throw exception when creating Uint64 object from string', () => { - expect(() => { UInt64.fromNumericString('000012345678'); }).to.throw('Input string is not a valid numeric string'); - expect(() => { UInt64.fromNumericString('ABC12345678'); }).to.throw('Input string is not a valid numeric string'); + expect(() => { + UInt64.fromNumericString('000012345678'); + }).to.throw('Input string is not a valid numeric string'); + expect(() => { + UInt64.fromNumericString('ABC12345678'); + }).to.throw('Input string is not a valid numeric string'); }); }); diff --git a/test/model/account/Account.spec.ts b/test/model/account/Account.spec.ts index 183a366393..7cd414ac86 100644 --- a/test/model/account/Account.spec.ts +++ b/test/model/account/Account.spec.ts @@ -14,10 +14,17 @@ * limitations under the License. */ -import {expect} from 'chai'; -import { Convert } from '../../../src/core/format/Convert'; -import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { expect } from 'chai'; +import { Account } from '../../../src/model/account/Account'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyLocal'; +import { TransferTransaction } from '../../../src/model/transaction/TransferTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { PlainMessage } from '../../../src/model/message/PlainMessage'; +import { AggregateTransaction } from '../../../src/model/transaction/AggregateTransaction'; +import { CosignatureTransaction } from '../../../src/model/transaction/CosignatureTransaction'; +import { CosignatureSignedTransaction } from '../../../src/model/transaction/CosignatureSignedTransaction'; +import { TransactionMapping } from '../../../src/core/utils/TransactionMapping'; describe('Account', () => { const accountInformation = { @@ -53,6 +60,57 @@ describe('Account', () => { expect(account.address).to.not.be.equal(undefined); }); + it('should return networkType', () => { + const account = Account.generateNewAccount(NetworkType.TEST_NET); + expect(account.networkType).to.be.equal(NetworkType.TEST_NET); + }); + + it('should sign tranaction with given signature', () => { + const sendAmount = NetworkCurrencyLocal.createAbsolute(1000); + const backAmount = NetworkCurrencyLocal.createAbsolute(1); + const account = Account.generateNewAccount(NetworkType.TEST_NET); + const account2 = Account.generateNewAccount(NetworkType.TEST_NET); + const generationHash = 'C422CC3C9257A1568036E1726E64EB5923C8363A13D4344F9E66CD89C8789BC7'; + const aliceTransferTransaction = TransferTransaction.create( + Deadline.create(), + account2.address, + [sendAmount], + PlainMessage.create('payout'), + NetworkType.TEST_NET, + ); + const bobTransferTransaction = TransferTransaction.create( + Deadline.create(), + account.address, + [backAmount], + PlainMessage.create('payout'), + NetworkType.TEST_NET, + ); + + // 01. Alice creates the aggregated tx and sign it. Then payload send to Bob + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), + [aliceTransferTransaction.toAggregate(account.publicAccount), bobTransferTransaction.toAggregate(account2.publicAccount)], + NetworkType.TEST_NET, + [], + ); + + const aliceSignedTransaction = aggregateTransaction.signWith(account, generationHash); + + // 02 Bob cosigns the tx and sends it back to Alice + const signedTxBob = CosignatureTransaction.signTransactionPayload(account2, aliceSignedTransaction.payload, generationHash); + + // 03. Alice collects the cosignatures, recreate, sign, and announces the transaction + const cosignatureSignedTransactions = [ + new CosignatureSignedTransaction(signedTxBob.parentHash, signedTxBob.signature, signedTxBob.signerPublicKey), + ]; + const recreatedTx = TransactionMapping.createFromPayload(aliceSignedTransaction.payload) as AggregateTransaction; + + const signedTransaction = account.signTransactionGivenSignatures(recreatedTx, cosignatureSignedTransactions, generationHash); + + expect(signedTransaction.payload).not.to.be.undefined; + expect(signedTransaction.payload.length).to.be.greaterThan(0); + }); + describe('signData', () => { it('utf-8', () => { const account = Account.createFromPrivateKey( @@ -61,8 +119,7 @@ describe('Account', () => { ); const publicAccount = account.publicAccount; const signed = account.signData('catapult rocks!'); - expect(publicAccount.verifySignature('catapult rocks!', signed)) - .to.be.true; + expect(publicAccount.verifySignature('catapult rocks!', signed)).to.be.true; }); it('hexa', () => { @@ -72,8 +129,7 @@ describe('Account', () => { ); const publicAccount = account.publicAccount; const signed = account.signData('0xAA'); - expect(publicAccount.verifySignature('0xAA', signed)) - .to.be.true; + expect(publicAccount.verifySignature('0xAA', signed)).to.be.true; }); it('utf-8 - NIS1', () => { @@ -83,8 +139,7 @@ describe('Account', () => { ); const publicAccount = account.publicAccount; const signed = account.signData('catapult rocks!'); - expect(publicAccount.verifySignature('catapult rocks!', signed)) - .to.be.true; + expect(publicAccount.verifySignature('catapult rocks!', signed)).to.be.true; }); it('hexa - NIS1', () => { @@ -94,8 +149,60 @@ describe('Account', () => { ); const publicAccount = account.publicAccount; const signed = account.signData('0xAA'); - expect(publicAccount.verifySignature('0xAA', signed)) - .to.be.true; + expect(publicAccount.verifySignature('0xAA', signed)).to.be.true; + }); + + it('hexa without 0x previx', () => { + const account = Account.createFromPrivateKey( + 'AB860ED1FE7C91C02F79C02225DAC708D7BD13369877C1F59E678CC587658C47', + NetworkType.MIJIN_TEST, + ); + const publicAccount = account.publicAccount; + const signed = account.signData('66128B29E8197352A2FEB51B50CF5D02F1D05B20D44B3F7953B98ACD2BCA15D4'); + expect(publicAccount.verifySignature('66128B29E8197352A2FEB51B50CF5D02F1D05B20D44B3F7953B98ACD2BCA15D4', signed)).to.be.true; + }); + + it('hexa without 0x previx should be the same as with 0x', () => { + const account = Account.createFromPrivateKey( + 'AB860ED1FE7C91C02F79C02225DAC708D7BD13369877C1F59E678CC587658C47', + NetworkType.MIJIN_TEST, + ); + const publicAccount = account.publicAccount; + const signed = account.signData('AA'); + const signedWith0x = account.signData('0xAA'); + expect(publicAccount.verifySignature('AA', signed)).to.be.true; + expect(publicAccount.verifySignature('0xAA', signedWith0x)).to.be.true; + }); + + it('hexa without 0x previx should be the same as with 0x', () => { + const account = Account.createFromPrivateKey( + 'AB860ED1FE7C91C02F79C02225DAC708D7BD13369877C1F59E678CC587658C47', + NetworkType.MIJIN_TEST, + ); + const publicAccount = account.publicAccount; + const signed = account.signData('ff60983e0c5d21d2fb83c67598d560f3cf0e28ae667b5616aaa58a059666cd8cf826b026243c92cf'); + const signedWith0x = account.signData('0xff60983e0c5d21d2fb83c67598d560f3cf0e28ae667b5616aaa58a059666cd8cf826b026243c92cf'); + expect( + publicAccount.verifySignature('ff60983e0c5d21d2fb83c67598d560f3cf0e28ae667b5616aaa58a059666cd8cf826b026243c92cf', signed), + ).to.be.true; + expect( + publicAccount.verifySignature( + '0xff60983e0c5d21d2fb83c67598d560f3cf0e28ae667b5616aaa58a059666cd8cf826b026243c92cf', + signedWith0x, + ), + ).to.be.true; + }); + + it('sign empty', () => { + const account = Account.createFromPrivateKey( + 'AB860ED1FE7C91C02F79C02225DAC708D7BD13369877C1F59E678CC587658C47', + NetworkType.MIJIN_TEST, + ); + const publicAccount = account.publicAccount; + const signed = account.signData(''); + const signedWith0x = account.signData('0x'); + expect(publicAccount.verifySignature('', signed)).to.be.true; + expect(publicAccount.verifySignature('0x', signedWith0x)).to.be.true; }); }); }); diff --git a/test/model/account/AccountInfo.spec.ts b/test/model/account/AccountInfo.spec.ts index 775fa89194..f013969e59 100644 --- a/test/model/account/AccountInfo.spec.ts +++ b/test/model/account/AccountInfo.spec.ts @@ -14,19 +14,18 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {AccountInfo} from '../../../src/model/account/AccountInfo'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { AccountInfo } from '../../../src/model/account/AccountInfo'; import { ActivityBucket } from '../../../src/model/account/ActivityBucket'; -import {Address} from '../../../src/model/account/Address'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {Mosaic} from '../../../src/model/mosaic/Mosaic'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {UInt64} from '../../../src/model/UInt64'; +import { Address } from '../../../src/model/account/Address'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { Mosaic } from '../../../src/model/mosaic/Mosaic'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { UInt64 } from '../../../src/model/UInt64'; describe('AccountInfo', () => { - it('should createComplete an AccountInfo object', () => { const accountInfoDTO = { account: { @@ -36,16 +35,20 @@ describe('AccountInfo', () => { importanceHeight: new UInt64([6462, 0]), accountType: 0, linkedAccountKey: '9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142', - activityBucket: [{ - startHeight: '1000', - totalFeesPaid: 100, - beneficiaryCount: 1, - rawScore: 20, - }], - mosaics: [{ - amount: new UInt64([1830592442, 94387]), - id: new MosaicId([3646934825, 3576016193]), - }], + activityBucket: [ + { + startHeight: '1000', + totalFeesPaid: 100, + beneficiaryCount: 1, + rawScore: 20, + }, + ], + mosaics: [ + { + amount: new UInt64([1830592442, 94387]), + id: new MosaicId([3646934825, 3576016193]), + }, + ], publicKey: '846B4439154579A5903B1459C9CF69CB8153F6D0110A7A0ED61DE29AE4810BF2', publicKeyHeight: new UInt64([13, 0]), }, @@ -58,12 +61,9 @@ describe('AccountInfo', () => { accountInfoDTO.account.publicKeyHeight, accountInfoDTO.account.accountType, accountInfoDTO.account.linkedAccountKey, - accountInfoDTO.account.activityBucket.map((bucket) => new ActivityBucket( - bucket.startHeight, - bucket.totalFeesPaid, - bucket.beneficiaryCount, - bucket.rawScore, - )), + accountInfoDTO.account.activityBucket.map( + (bucket) => new ActivityBucket(bucket.startHeight, bucket.totalFeesPaid, bucket.beneficiaryCount, bucket.rawScore), + ), accountInfoDTO.account.mosaics.map((mosaicDTO) => new Mosaic(mosaicDTO.id, mosaicDTO.amount)), accountInfoDTO.account.importance, accountInfoDTO.account.importanceHeight, @@ -75,6 +75,5 @@ describe('AccountInfo', () => { deepEqual(accountInfo.importance, accountInfoDTO.account.importance); deepEqual(accountInfo.importanceHeight, accountInfoDTO.account.importanceHeight); deepEqual(accountInfo.publicAccount, PublicAccount.createFromPublicKey(accountInfoDTO.account.publicKey, NetworkType.MIJIN_TEST)); - }); }); diff --git a/test/model/account/Address.spec.ts b/test/model/account/Address.spec.ts index ca7db5c9bd..19e49a43d7 100644 --- a/test/model/account/Address.spec.ts +++ b/test/model/account/Address.spec.ts @@ -19,11 +19,8 @@ import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; import { NetworkType } from '../../../src/model/network/NetworkType'; -const Address_Decoded_Size = 25; - describe('Address', () => { const publicKey = 'c2f93346e27ce6ad1a9f8f5e3066f8326593a406bdf357acb041e2f9ab402efe'.toUpperCase(); - const NIS_PublicKey = 'c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844'; it('createComplete an address given publicKey + NetworkType.MIJIN_TEST', () => { const address = Address.createFromPublicKey(publicKey, NetworkType.MIJIN_TEST); expect(address.plain()).to.be.equal('SCTVW23D2MN5VE4AQ4TZIDZENGNOZXPRPRLIKCF2'); @@ -115,17 +112,12 @@ describe('Address', () => { }); describe('isValidRawAddress', () => { - it('returns true for valid address when generated', () => { // Assert: - expect(Address.isValidRawAddress( - Account.generateNewAccount(NetworkType.MIJIN_TEST).address.plain(), NetworkType.MIJIN_TEST)).to.equal(true); - expect(Address.isValidRawAddress( - Account.generateNewAccount(NetworkType.MAIN_NET).address.plain(), NetworkType.MAIN_NET)).to.equal(true); - expect(Address.isValidRawAddress( - Account.generateNewAccount(NetworkType.MIJIN).address.plain(), NetworkType.MIJIN)).to.equal(true); - expect(Address.isValidRawAddress( - Account.generateNewAccount(NetworkType.TEST_NET).address.plain(), NetworkType.TEST_NET)).to.equal(true); + expect(Address.isValidRawAddress(Account.generateNewAccount(NetworkType.MIJIN_TEST).address.plain())).to.equal(true); + expect(Address.isValidRawAddress(Account.generateNewAccount(NetworkType.MAIN_NET).address.plain())).to.equal(true); + expect(Address.isValidRawAddress(Account.generateNewAccount(NetworkType.MIJIN).address.plain())).to.equal(true); + expect(Address.isValidRawAddress(Account.generateNewAccount(NetworkType.TEST_NET).address.plain())).to.equal(true); }); it('returns true for valid address', () => { @@ -133,7 +125,7 @@ describe('Address', () => { const rawAddress = 'SCHCZBZ6QVJAHGJTKYVPW5FBSO2IXXJQBPV5XE6P'; // Assert: - expect(Address.isValidRawAddress(rawAddress, NetworkType.MIJIN_TEST)).to.equal(true); + expect(Address.isValidRawAddress(rawAddress)).to.equal(true); }); it('returns false for address with invalid checksum', () => { @@ -141,7 +133,7 @@ describe('Address', () => { const rawAddress = 'SCHCZBZ6QVJAHGJTKYAPW5FBSO2IXXJQBPV5XE6P'; // Assert: - expect(Address.isValidRawAddress(rawAddress, NetworkType.MIJIN_TEST)).to.equal(false); + expect(Address.isValidRawAddress(rawAddress)).to.equal(false); }); it('returns false for address with invalid hash', () => { @@ -149,7 +141,7 @@ describe('Address', () => { const rawAddress = 'SCHCZBZ6QVJAHGJTKYVPW5FBSO2IXXJQBPV5XE7P'; // Assert: - expect(Address.isValidRawAddress(rawAddress, NetworkType.MIJIN_TEST)).to.equal(false); + expect(Address.isValidRawAddress(rawAddress)).to.equal(false); }); it('returns false for address with invalid prefix', () => { @@ -157,22 +149,17 @@ describe('Address', () => { const rawAddress = 'ACHCZBZ6QVJAHGJTKYVPW5FBSO2IXXJQBPV5XE6P'; // Assert: - expect(Address.isValidRawAddress(rawAddress, NetworkType.MIJIN_TEST)).to.equal(false); + expect(Address.isValidRawAddress(rawAddress)).to.equal(false); }); }); describe('isValidEncodedAddress', () => { - it('returns true for valid address when generated', () => { // Assert: - expect(Address.isValidEncodedAddress( - Account.generateNewAccount(NetworkType.MIJIN_TEST).address.encoded(), NetworkType.MIJIN_TEST)).to.equal(true); - expect(Address.isValidEncodedAddress( - Account.generateNewAccount(NetworkType.MAIN_NET).address.encoded(), NetworkType.MAIN_NET)).to.equal(true); - expect(Address.isValidEncodedAddress( - Account.generateNewAccount(NetworkType.MIJIN).address.encoded(), NetworkType.MIJIN)).to.equal(true); - expect(Address.isValidEncodedAddress( - Account.generateNewAccount(NetworkType.TEST_NET).address.encoded(), NetworkType.TEST_NET)).to.equal(true); + expect(Address.isValidEncodedAddress(Account.generateNewAccount(NetworkType.MIJIN_TEST).address.encoded())).to.equal(true); + expect(Address.isValidEncodedAddress(Account.generateNewAccount(NetworkType.MAIN_NET).address.encoded())).to.equal(true); + expect(Address.isValidEncodedAddress(Account.generateNewAccount(NetworkType.MIJIN).address.encoded())).to.equal(true); + expect(Address.isValidEncodedAddress(Account.generateNewAccount(NetworkType.TEST_NET).address.encoded())).to.equal(true); }); it('returns true for valid encoded address', () => { @@ -180,7 +167,7 @@ describe('Address', () => { const encoded = '9085215E4620D383C2DF70235B9EF7507F6A28EF6D16FD7B9C'; // Assert: - expect(Address.isValidEncodedAddress(encoded, NetworkType.MIJIN_TEST)).to.equal(true); + expect(Address.isValidEncodedAddress(encoded)).to.equal(true); }); it('returns false for invalid hex encoded address', () => { @@ -188,7 +175,7 @@ describe('Address', () => { const encoded = 'Z085215E4620D383C2DF70235B9EF7507F6A28EF6D16FD7B9C'; // Assert: - expect(Address.isValidEncodedAddress(encoded, NetworkType.MIJIN_TEST)).to.equal(false); + expect(Address.isValidEncodedAddress(encoded)).to.equal(false); }); it('returns false for invalid encoded address', () => { @@ -196,7 +183,7 @@ describe('Address', () => { const encoded = '9085215E4620D383C2DF70235B9EF7507F6A28EF6D16FD7B9D'; // Assert: - expect(Address.isValidEncodedAddress(encoded, NetworkType.MIJIN_TEST)).to.equal(false); + expect(Address.isValidEncodedAddress(encoded)).to.equal(false); }); it('returns false for encoded address with wrong length', () => { @@ -204,7 +191,7 @@ describe('Address', () => { const encoded = '9085215E4620D383C2DF70235B9EF7607F6A28EF6D16FD7B9C'; // Assert: - expect(Address.isValidEncodedAddress(encoded, NetworkType.MIJIN_TEST)).to.equal(false); + expect(Address.isValidEncodedAddress(encoded)).to.equal(false); }); it('adding leading or trailing white space invalidates encoded address', () => { @@ -212,9 +199,9 @@ describe('Address', () => { const encoded = '9085215E4620D383C2DF70235B9EF7507F6A28EF6D16FD7B9C'; // Assert: - expect(Address.isValidEncodedAddress(` \t ${encoded}`, NetworkType.MIJIN_TEST)).to.equal(false); - expect(Address.isValidEncodedAddress(`${encoded} \t `, NetworkType.MIJIN_TEST)).to.equal(false); - expect(Address.isValidEncodedAddress(` \t ${encoded} \t `, NetworkType.MIJIN_TEST)).to.equal(false); + expect(Address.isValidEncodedAddress(` \t ${encoded}`)).to.equal(false); + expect(Address.isValidEncodedAddress(`${encoded} \t `)).to.equal(false); + expect(Address.isValidEncodedAddress(` \t ${encoded} \t `)).to.equal(false); }); }); }); diff --git a/test/model/account/MultisigAccountGraphInfo.spec.ts b/test/model/account/MultisigAccountGraphInfo.spec.ts index 45df95e7cd..754e1df419 100644 --- a/test/model/account/MultisigAccountGraphInfo.spec.ts +++ b/test/model/account/MultisigAccountGraphInfo.spec.ts @@ -14,36 +14,45 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {MultisigAccountGraphInfo} from '../../../src/model/account/MultisigAccountGraphInfo'; -import {MultisigAccountInfo} from '../../../src/model/account/MultisigAccountInfo'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { MultisigAccountGraphInfo } from '../../../src/model/account/MultisigAccountGraphInfo'; +import { MultisigAccountInfo } from '../../../src/model/account/MultisigAccountInfo'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { NetworkType } from '../../../src/model/network/NetworkType'; describe('MultisigAccountGraphInfo', () => { - it('should createComplete an MultisigAccountGraphInfo object', () => { const multisigAccountGraphInfoDTO = { level: 2, multisigEntries: [ { multisig: { - account: PublicAccount.createFromPublicKey('B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D', - NetworkType.MIJIN_TEST), + account: PublicAccount.createFromPublicKey( + 'B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D', + NetworkType.MIJIN_TEST, + ), cosignatories: [ - PublicAccount.createFromPublicKey('CF893FFCC47C33E7F68AB1DB56365C156B0736824A0C1E273F9E00B8DF8F01EB', - NetworkType.MIJIN_TEST), - PublicAccount.createFromPublicKey('68B3FBB18729C1FDE225C57F8CE080FA828F0067E451A3FD81FA628842B0B763', - NetworkType.MIJIN_TEST), - PublicAccount.createFromPublicKey('DAB1C38C3E1642494FCCB33138B95E81867B5FB59FC4277A1D53761C8B9F6D14', - NetworkType.MIJIN_TEST), + PublicAccount.createFromPublicKey( + 'CF893FFCC47C33E7F68AB1DB56365C156B0736824A0C1E273F9E00B8DF8F01EB', + NetworkType.MIJIN_TEST, + ), + PublicAccount.createFromPublicKey( + '68B3FBB18729C1FDE225C57F8CE080FA828F0067E451A3FD81FA628842B0B763', + NetworkType.MIJIN_TEST, + ), + PublicAccount.createFromPublicKey( + 'DAB1C38C3E1642494FCCB33138B95E81867B5FB59FC4277A1D53761C8B9F6D14', + NetworkType.MIJIN_TEST, + ), ], minApproval: 3, minRemoval: 3, multisigAccounts: [ - PublicAccount.createFromPublicKey('1674016C27FE2C2EB5DFA73996FA54A183B38AED0AA64F756A3918BAF08E061B', - NetworkType.MIJIN_TEST), + PublicAccount.createFromPublicKey( + '1674016C27FE2C2EB5DFA73996FA54A183B38AED0AA64F756A3918BAF08E061B', + NetworkType.MIJIN_TEST, + ), ], }, }, @@ -68,35 +77,39 @@ describe('MultisigAccountGraphInfo', () => { expect(multisigAccountInfoGraph.multisigAccounts.get(2)).to.not.be.equal(undefined); expect(multisigAccountInfoGraph.multisigAccounts.get(1)).to.be.equal(undefined); - expect(multisigAccountInfoGraph.multisigAccounts.get(2)![0].account) - .to.be.equal(multisigAccountGraphInfoDTO.multisigEntries[0].multisig.account); - expect(multisigAccountInfoGraph.multisigAccounts.get(2)![0].minApproval) - .to.be.equal(multisigAccountGraphInfoDTO.multisigEntries[0].multisig.minApproval); - expect(multisigAccountInfoGraph.multisigAccounts.get(2)![0].minRemoval) - .to.be.equal(multisigAccountGraphInfoDTO.multisigEntries[0].multisig.minRemoval); - deepEqual(multisigAccountInfoGraph.multisigAccounts.get(2)![0].cosignatories, - multisigAccountGraphInfoDTO.multisigEntries[0].multisig.cosignatories); - deepEqual(multisigAccountInfoGraph.multisigAccounts.get(2)![0].multisigAccounts, - multisigAccountGraphInfoDTO.multisigEntries[0].multisig.multisigAccounts); + expect(multisigAccountInfoGraph.multisigAccounts.get(2)![0].account).to.be.equal( + multisigAccountGraphInfoDTO.multisigEntries[0].multisig.account, + ); + expect(multisigAccountInfoGraph.multisigAccounts.get(2)![0].minApproval).to.be.equal( + multisigAccountGraphInfoDTO.multisigEntries[0].multisig.minApproval, + ); + expect(multisigAccountInfoGraph.multisigAccounts.get(2)![0].minRemoval).to.be.equal( + multisigAccountGraphInfoDTO.multisigEntries[0].multisig.minRemoval, + ); + deepEqual( + multisigAccountInfoGraph.multisigAccounts.get(2)![0].cosignatories, + multisigAccountGraphInfoDTO.multisigEntries[0].multisig.cosignatories, + ); + deepEqual( + multisigAccountInfoGraph.multisigAccounts.get(2)![0].multisigAccounts, + multisigAccountGraphInfoDTO.multisigEntries[0].multisig.multisigAccounts, + ); }); + //TODO finish tests! describe('hasCosigner', () => { - it('should return true when account is in the cosignatories list', () => { - - }); - - it('should return false when account is not in the cosignatories list', () => { + // eslint-disable-next-line @typescript-eslint/no-empty-function + it('should return true when account is in the cosignatories list', () => {}); - }); + // eslint-disable-next-line @typescript-eslint/no-empty-function + it('should return false when account is not in the cosignatories list', () => {}); }); describe('isCosignerOfMultisigAccount', () => { - it('should return true when account is in the multisig account list', () => { - - }); - - it('should return false when account is not in the multisig account list', () => { + // eslint-disable-next-line @typescript-eslint/no-empty-function + it('should return true when account is in the multisig account list', () => {}); - }); + // eslint-disable-next-line @typescript-eslint/no-empty-function + it('should return false when account is not in the multisig account list', () => {}); }); }); diff --git a/test/model/account/MultisigAccountInfo.spec.ts b/test/model/account/MultisigAccountInfo.spec.ts index 54f27d5ede..06231d57ca 100644 --- a/test/model/account/MultisigAccountInfo.spec.ts +++ b/test/model/account/MultisigAccountInfo.spec.ts @@ -14,29 +14,39 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {MultisigAccountInfo} from '../../../src/model/account/MultisigAccountInfo'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { expect } from 'chai'; +import { MultisigAccountInfo } from '../../../src/model/account/MultisigAccountInfo'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { NetworkType } from '../../../src/model/network/NetworkType'; describe('MultisigAccountInfo', () => { const multisigAccountInfoDTO = { multisig: { - account: PublicAccount.createFromPublicKey('B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D', - NetworkType.MIJIN_TEST), + account: PublicAccount.createFromPublicKey( + 'B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D', + NetworkType.MIJIN_TEST, + ), cosignatories: [ - PublicAccount.createFromPublicKey('CF893FFCC47C33E7F68AB1DB56365C156B0736824A0C1E273F9E00B8DF8F01EB', - NetworkType.MIJIN_TEST), - PublicAccount.createFromPublicKey('68B3FBB18729C1FDE225C57F8CE080FA828F0067E451A3FD81FA628842B0B763', - NetworkType.MIJIN_TEST), - PublicAccount.createFromPublicKey('DAB1C38C3E1642494FCCB33138B95E81867B5FB59FC4277A1D53761C8B9F6D14', - NetworkType.MIJIN_TEST), + PublicAccount.createFromPublicKey( + 'CF893FFCC47C33E7F68AB1DB56365C156B0736824A0C1E273F9E00B8DF8F01EB', + NetworkType.MIJIN_TEST, + ), + PublicAccount.createFromPublicKey( + '68B3FBB18729C1FDE225C57F8CE080FA828F0067E451A3FD81FA628842B0B763', + NetworkType.MIJIN_TEST, + ), + PublicAccount.createFromPublicKey( + 'DAB1C38C3E1642494FCCB33138B95E81867B5FB59FC4277A1D53761C8B9F6D14', + NetworkType.MIJIN_TEST, + ), ], minApproval: 3, minRemoval: 3, multisigAccounts: [ - PublicAccount.createFromPublicKey('1674016C27FE2C2EB5DFA73996FA54A183B38AED0AA64F756A3918BAF08E061B', - NetworkType.MIJIN_TEST), + PublicAccount.createFromPublicKey( + '1674016C27FE2C2EB5DFA73996FA54A183B38AED0AA64F756A3918BAF08E061B', + NetworkType.MIJIN_TEST, + ), ], }, }; @@ -102,9 +112,14 @@ describe('MultisigAccountInfo', () => { multisigAccountInfoDTO.multisig.multisigAccounts, ); - expect(multisigAccountInfo.hasCosigner( - PublicAccount.createFromPublicKey('CF893FFCC47C33E7F68AB1DB56365C156B0736824A0C1E273F9E00B8DF8F01EB', - NetworkType.MIJIN_TEST))).to.be.equal(true); + expect( + multisigAccountInfo.hasCosigner( + PublicAccount.createFromPublicKey( + 'CF893FFCC47C33E7F68AB1DB56365C156B0736824A0C1E273F9E00B8DF8F01EB', + NetworkType.MIJIN_TEST, + ), + ), + ).to.be.equal(true); }); it('should return false when account is not in the cosignatories list', () => { @@ -116,9 +131,14 @@ describe('MultisigAccountInfo', () => { multisigAccountInfoDTO.multisig.multisigAccounts, ); - expect(multisigAccountInfo.hasCosigner( - PublicAccount.createFromPublicKey('B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D', - NetworkType.MIJIN_TEST))).to.be.equal(false); + expect( + multisigAccountInfo.hasCosigner( + PublicAccount.createFromPublicKey( + 'B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D', + NetworkType.MIJIN_TEST, + ), + ), + ).to.be.equal(false); }); }); @@ -132,9 +152,14 @@ describe('MultisigAccountInfo', () => { multisigAccountInfoDTO.multisig.multisigAccounts, ); - expect(multisigAccountInfo.isCosignerOfMultisigAccount( - PublicAccount.createFromPublicKey('1674016C27FE2C2EB5DFA73996FA54A183B38AED0AA64F756A3918BAF08E061B', - NetworkType.MIJIN_TEST))).to.be.equal(true); + expect( + multisigAccountInfo.isCosignerOfMultisigAccount( + PublicAccount.createFromPublicKey( + '1674016C27FE2C2EB5DFA73996FA54A183B38AED0AA64F756A3918BAF08E061B', + NetworkType.MIJIN_TEST, + ), + ), + ).to.be.equal(true); }); it('should return false when account is not in the multisig account list', () => { @@ -146,9 +171,14 @@ describe('MultisigAccountInfo', () => { multisigAccountInfoDTO.multisig.multisigAccounts, ); - expect(multisigAccountInfo.isCosignerOfMultisigAccount( - PublicAccount.createFromPublicKey('B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D', - NetworkType.MIJIN_TEST))).to.be.equal(false); + expect( + multisigAccountInfo.isCosignerOfMultisigAccount( + PublicAccount.createFromPublicKey( + 'B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D', + NetworkType.MIJIN_TEST, + ), + ), + ).to.be.equal(false); }); }); }); diff --git a/test/model/account/PublicAccount.spec.ts b/test/model/account/PublicAccount.spec.ts index 4dd719f29e..8f94f31066 100644 --- a/test/model/account/PublicAccount.spec.ts +++ b/test/model/account/PublicAccount.spec.ts @@ -15,9 +15,9 @@ */ import { expect } from 'chai'; -import { Account } from '../../../src/model/account/Account'; import { PublicAccount } from '../../../src/model/account/PublicAccount'; import { NetworkType } from '../../../src/model/network/NetworkType'; +import { TestingAccount } from '../../conf/conf.spec'; describe('PublicAccount', () => { const publicKey = 'b4f12e7c9f6946091e2cb8b6d3a12b50d17ccbbf646386ea27ce2946a7423dcf'; @@ -32,69 +32,73 @@ describe('PublicAccount', () => { describe('Signature verification', () => { it('Can verify a signature', () => { // Arrange:' - const signerPublicAccount = PublicAccount.createFromPublicKey( - '16FB59F907524009730BCB9F860C8C5A1109A9E8F194275DA0B9F5A2085E2D02', - NetworkType.MIJIN_TEST); + const signerPublicAccount = TestingAccount.publicAccount; const data = 'ff60983e0c5d21d2fb83c67598d560f3cf0e28ae667b5616aaa58a059666cd8cf826b026243c92cf'; - const signature = '2E32A8A934C2B8BC54A1594643A866CCDB3166BD41B6DE3E0C9FC779E7F3F421A0BCC798408ACCC92F47A3A45EF237D5CB7473D768991EE79AC659E1DA8CBB0C'; // tslint:disable-line - + const signature = TestingAccount.signData(data); // Act & Assert: expect(signerPublicAccount.verifySignature(data, signature)).to.be.true; }); it('Throw error if signature has invalid length', () => { // Arrange: - const signerPublicAccount = PublicAccount.createFromPublicKey('22816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB508', - NetworkType.MIJIN_TEST); + const signerPublicAccount = PublicAccount.createFromPublicKey( + '22816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB508', + NetworkType.MIJIN_TEST, + ); const data = 'I am so so so awesome as always'; - const signature = 'B01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C5486'; // tslint:disable-line - - // Act & Assert: - expect(() => { signerPublicAccount.verifySignature(data, signature); }).to.throw('Signature length is incorrect'); + const signature = 'B01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C5486'; // Act & Assert: + expect(() => { + signerPublicAccount.verifySignature(data, signature); + }).to.throw('Signature length is incorrect'); }); it('Throw error if signature is not strictly hexadecimal', () => { // Arrange: - const signerPublicAccount = PublicAccount.createFromPublicKey('22816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB508', - NetworkType.MIJIN_TEST); + const signerPublicAccount = PublicAccount.createFromPublicKey( + '22816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB508', + NetworkType.MIJIN_TEST, + ); const data = 'I am so so so awesome as always'; - const signature = 'B01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C548625C9A5916A555A24F72F35a1wwwww';// tslint:disable-line - - // Act & Assert: - expect(() => { signerPublicAccount.verifySignature(data, signature); }) - .to.throw('Signature must be hexadecimal only'); + const signature = + 'B01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C548625C9A5916A555A24F72F35a1wwwww'; // Act & Assert: + expect(() => { + signerPublicAccount.verifySignature(data, signature); + }).to.throw('Signature must be hexadecimal only'); }); it('Return false if wrong public key provided', () => { // Arrange: - const signerPublicAccount = PublicAccount.createFromPublicKey('12816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB509', - NetworkType.MIJIN_TEST); + const signerPublicAccount = PublicAccount.createFromPublicKey( + '12816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB509', + NetworkType.MIJIN_TEST, + ); const data = 'I am so so so awesome as always'; - const signature = 'B01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C548625C9A5916A555A24F72F3526FA508';// tslint:disable-line - - // Act & Assert: + const signature = + 'B01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C548625C9A5916A555A24F72F3526FA508'; // Act & Assert: expect(signerPublicAccount.verifySignature(data, signature)).to.be.false; }); it('Return false if data is not corresponding to signature provided', () => { // Arrange: - const signerPublicAccount = PublicAccount.createFromPublicKey('22816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB508', - NetworkType.MIJIN_TEST); + const signerPublicAccount = PublicAccount.createFromPublicKey( + '22816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB508', + NetworkType.MIJIN_TEST, + ); const data = 'I am awesome as always'; - const signature = 'B01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C548625C9A5916A555A24F72F3526FA508';// tslint:disable-line - - // Act & Assert: + const signature = + 'B01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C548625C9A5916A555A24F72F3526FA508'; // Act & Assert: expect(signerPublicAccount.verifySignature(data, signature)).to.be.false; }); it('Return false if signature is not corresponding to data provided', () => { // Arrange: - const signerPublicAccount = PublicAccount.createFromPublicKey('22816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB508', - NetworkType.MIJIN_TEST); + const signerPublicAccount = PublicAccount.createFromPublicKey( + '22816F825B4CACEA334723D51297D8582332D8B875A5829908AAE85831ABB508', + NetworkType.MIJIN_TEST, + ); const data = 'I am so so so awesome as always'; - const signature = 'A01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C548625C9A5916A555A24F72F3526FA509';// tslint:disable-line - - // Act & Assert: + const signature = + 'A01DCA6484026C2ECDF3C822E64DEAAFC15EBCCE337EEE209C28513CB5351CDED8863A8E7B855CD471B55C91FAE611C548625C9A5916A555A24F72F3526FA509'; // Act & Assert: expect(signerPublicAccount.verifySignature(data, signature)).to.be.false; }); }); diff --git a/test/model/blockchain/BlockInfo.spec.ts b/test/model/blockchain/BlockInfo.spec.ts index c4839653eb..cdd17a7f2f 100644 --- a/test/model/blockchain/BlockInfo.spec.ts +++ b/test/model/blockchain/BlockInfo.spec.ts @@ -14,29 +14,29 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {BlockInfo} from '../../../src/model/blockchain/BlockInfo'; -import {UInt64} from '../../../src/model/UInt64'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { BlockInfo } from '../../../src/model/blockchain/BlockInfo'; +import { UInt64 } from '../../../src/model/UInt64'; describe('BlockInfo', () => { - it('should createComplete an BlockInfo object', () => { const blockDTO = { - block: { + block: { blockTransactionsHash: '702090BA31CEF9E90C62BBDECC0CCCC0F88192B6625839382850357F70DD68A0', blockReceiptsHash: '702090BA31CEF9E90C62BBDECC0CCCC0F88192B6625839382850357F70DD68A0', stateHash: '702090BA31CEF9E90C62BBDECC0CCCC0F88192B6625839382850357F70DD68A0', - difficulty: new UInt64([ 276447232, 23283 ]), + difficulty: new UInt64([276447232, 23283]), feeMultiplier: 1, - height: new UInt64([ 1, 0 ]), + height: new UInt64([1, 0]), previousBlockHash: '0000000000000000000000000000000000000000000000000000000000000000', - signature: '37351C8244AC166BE6664E3FA954E99A3239AC46E51E2B32CEA1C72DD0851100A7731868' + - 'E932E1A9BEF8A27D48E1FFEE401E933EB801824373E7537E51733E0F', + signature: + '37351C8244AC166BE6664E3FA954E99A3239AC46E51E2B32CEA1C72DD0851100A7731868' + + 'E932E1A9BEF8A27D48E1FFEE401E933EB801824373E7537E51733E0F', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', beneficiaryPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', - timestamp: new UInt64([ 0, 0 ]), + timestamp: new UInt64([0, 0]), type: 32768, version: 1, network: 144, @@ -46,7 +46,7 @@ describe('BlockInfo', () => { hash: '24E92B511B54EDB48A4850F9B42485FDD1A30589D92C775632DDDD71D7D1D691', numTransactions: 25, numStatements: 1, - totalFee: new UInt64([ 0, 0 ]), + totalFee: new UInt64([0, 0]), }, }; @@ -91,6 +91,5 @@ describe('BlockInfo', () => { expect(blockInfo.stateHash).to.be.equal(blockDTO.block.stateHash); expect((blockInfo.beneficiaryPublicKey as PublicAccount).publicKey).to.be.equal(blockDTO.block.beneficiaryPublicKey); expect(blockInfo.numStatements).to.be.equal(blockDTO.meta.numStatements); - }); }); diff --git a/test/model/blockchain/BlockchainScore.spec.ts b/test/model/blockchain/BlockchainScore.spec.ts index a009add999..a5630111b9 100644 --- a/test/model/blockchain/BlockchainScore.spec.ts +++ b/test/model/blockchain/BlockchainScore.spec.ts @@ -14,22 +14,18 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {BlockchainScore} from '../../../src/model/blockchain/BlockchainScore'; -import {UInt64} from '../../../src/model/UInt64'; +import { deepEqual } from 'assert'; +import { BlockchainScore } from '../../../src/model/blockchain/BlockchainScore'; +import { UInt64 } from '../../../src/model/UInt64'; describe('BlockchainScore', () => { - it('should createComplete an BlockchainScore object', () => { const blockchainScoreDTO = { scoreHigh: new UInt64([0, 0]), scoreLow: new UInt64([0, 0]), }; - const blockchainScore = new BlockchainScore( - blockchainScoreDTO.scoreLow, - blockchainScoreDTO.scoreHigh, - ); + const blockchainScore = new BlockchainScore(blockchainScoreDTO.scoreLow, blockchainScoreDTO.scoreHigh); deepEqual(blockchainScore.scoreLow, blockchainScoreDTO.scoreLow); deepEqual(blockchainScore.scoreHigh, blockchainScoreDTO.scoreHigh); diff --git a/test/model/blockchain/BlockchainStorageInfo.spec.ts b/test/model/blockchain/BlockchainStorageInfo.spec.ts index 105cd150fb..32944b64b6 100644 --- a/test/model/blockchain/BlockchainStorageInfo.spec.ts +++ b/test/model/blockchain/BlockchainStorageInfo.spec.ts @@ -14,11 +14,10 @@ * limitations under the License. */ -import {expect} from 'chai'; +import { expect } from 'chai'; import { StorageInfo } from '../../../src/model/blockchain/StorageInfo'; describe('BlockchainStorageInfo', () => { - it('should createComplete an StorageInfo object', () => { const blockchainStorageInfoDTO = { numBlocks: 1, diff --git a/test/model/message/EncryptedMessage.spec.ts b/test/model/message/EncryptedMessage.spec.ts index ae4cf20a5a..76a5ca57ab 100644 --- a/test/model/message/EncryptedMessage.spec.ts +++ b/test/model/message/EncryptedMessage.spec.ts @@ -14,28 +14,29 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Account} from '../../../src/model/account/Account'; -import {EncryptedMessage} from '../../../src/model/message/EncryptedMessage'; +import { expect } from 'chai'; +import { Account } from '../../../src/model/account/Account'; +import { EncryptedMessage } from '../../../src/model/message/EncryptedMessage'; import { Deadline, NetworkCurrencyLocal, NetworkType, TransferTransaction } from '../../../src/model/model'; describe('EncryptedMessage', () => { - let sender: Account; let recipient: Account; let sender_nis: Account; let recipient_nis: Account; before(() => { - sender = Account.createFromPrivateKey('2602F4236B199B3DF762B2AAB46FC3B77D8DDB214F0B62538D3827576C46C108', - NetworkType.MIJIN_TEST); - recipient = Account.createFromPrivateKey('B72F2950498111BADF276D6D9D5E345F04E0D5C9B8342DA983C3395B4CF18F08', - NetworkType.MIJIN_TEST); + sender = Account.createFromPrivateKey('2602F4236B199B3DF762B2AAB46FC3B77D8DDB214F0B62538D3827576C46C108', NetworkType.MIJIN_TEST); + recipient = Account.createFromPrivateKey( + 'B72F2950498111BADF276D6D9D5E345F04E0D5C9B8342DA983C3395B4CF18F08', + NetworkType.MIJIN_TEST, + ); - sender_nis = Account.createFromPrivateKey('2602F4236B199B3DF762B2AAB46FC3B77D8DDB214F0B62538D3827576C46C108', - NetworkType.TEST_NET); - recipient_nis = Account.createFromPrivateKey('B72F2950498111BADF276D6D9D5E345F04E0D5C9B8342DA983C3395B4CF18F08', - NetworkType.TEST_NET); + sender_nis = Account.createFromPrivateKey('2602F4236B199B3DF762B2AAB46FC3B77D8DDB214F0B62538D3827576C46C108', NetworkType.TEST_NET); + recipient_nis = Account.createFromPrivateKey( + 'B72F2950498111BADF276D6D9D5E345F04E0D5C9B8342DA983C3395B4CF18F08', + NetworkType.TEST_NET, + ); }); it('should create a encrypted message from a DTO', () => { @@ -44,15 +45,15 @@ describe('EncryptedMessage', () => { }); it('should return encrypted message dto', () => { - const encryptedMessage = sender.encryptMessage('test transaction', recipient.publicAccount, NetworkType.MIJIN_TEST); - const plainMessage = recipient.decryptMessage(encryptedMessage, sender.publicAccount, NetworkType.MIJIN_TEST); + const encryptedMessage = sender.encryptMessage('test transaction', recipient.publicAccount); + const plainMessage = recipient.decryptMessage(encryptedMessage, sender.publicAccount); expect(plainMessage.payload).to.be.equal('test transaction'); }); it('should decrypt message from raw encrypted message payload', () => { - const encryptedMessage = sender.encryptMessage('Testing simple transfer', recipient.publicAccount, NetworkType.MIJIN_TEST); + const encryptedMessage = sender.encryptMessage('Testing simple transfer', recipient.publicAccount); const payload = encryptedMessage.payload; - const plainMessage = recipient.decryptMessage(new EncryptedMessage(payload), sender.publicAccount, NetworkType.MIJIN_TEST); + const plainMessage = recipient.decryptMessage(new EncryptedMessage(payload), sender.publicAccount); expect(plainMessage.payload).to.be.equal('Testing simple transfer'); }); @@ -62,21 +63,21 @@ describe('EncryptedMessage', () => { Deadline.create(), recipient.address, [NetworkCurrencyLocal.createAbsolute(1)], - sender.encryptMessage('Testing simple transfer', recipient.publicAccount, NetworkType.MIJIN_TEST), + sender.encryptMessage('Testing simple transfer', recipient.publicAccount), NetworkType.MIJIN_TEST, ); const signedTransaction = transferTransaction.signWith(sender, generationHash); - const encryptMessage = EncryptedMessage - .createFromPayload(signedTransaction.payload.substring(354, signedTransaction.payload.length)); - const plainMessage = recipient.decryptMessage(encryptMessage, sender.publicAccount, NetworkType.MIJIN_TEST); + const encryptMessage = EncryptedMessage.createFromPayload( + signedTransaction.payload.substring(354, signedTransaction.payload.length), + ); + const plainMessage = recipient.decryptMessage(encryptMessage, sender.publicAccount); expect(plainMessage.payload).to.be.equal('Testing simple transfer'); }); it('should encrypt and decrypt message using NIS1 schema', () => { - const encryptedMessage = sender_nis.encryptMessage('Testing simple transfer', recipient_nis.publicAccount, NetworkType.TEST_NET); + const encryptedMessage = sender_nis.encryptMessage('Testing simple transfer', recipient_nis.publicAccount); const payload = encryptedMessage.payload; - const plainMessage = recipient_nis.decryptMessage(new EncryptedMessage(payload), sender_nis.publicAccount, NetworkType.TEST_NET); + const plainMessage = recipient_nis.decryptMessage(new EncryptedMessage(payload), sender_nis.publicAccount); expect(plainMessage.payload).to.be.equal('Testing simple transfer'); }); - }); diff --git a/test/model/message/Message.spec.ts b/test/model/message/Message.spec.ts index 32e59815ca..c5521b9e33 100644 --- a/test/model/message/Message.spec.ts +++ b/test/model/message/Message.spec.ts @@ -14,15 +14,14 @@ * limitations under the License. */ -import {expect} from 'chai'; +import { expect } from 'chai'; import { EncryptedMessage } from '../../../src/model/message/EncryptedMessage'; import { Message } from '../../../src/model/message/Message'; import { MessageType } from '../../../src/model/message/MessageType'; import { PersistentHarvestingDelegationMessage } from '../../../src/model/message/PersistentHarvestingDelegationMessage'; -import {PlainMessage} from '../../../src/model/message/PlainMessage'; +import { PlainMessage } from '../../../src/model/message/PlainMessage'; describe('Message', () => { - it('should create an plain message dto object', () => { const message = new PlainMessage('test'); expect(message.toDTO().type).to.be.equal(MessageType.PlainMessage); diff --git a/test/model/message/PersistentHarvestingDelegationMessage.spec.ts b/test/model/message/PersistentHarvestingDelegationMessage.spec.ts index c76c879e2a..0831afcec7 100644 --- a/test/model/message/PersistentHarvestingDelegationMessage.spec.ts +++ b/test/model/message/PersistentHarvestingDelegationMessage.spec.ts @@ -14,46 +14,46 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Account} from '../../../src/model/account/Account'; +import { expect } from 'chai'; +import { Account } from '../../../src/model/account/Account'; import { MessageType } from '../../../src/model/message/MessageType'; -import {PersistentHarvestingDelegationMessage} from '../../../src/model/message/PersistentHarvestingDelegationMessage'; +import { PersistentHarvestingDelegationMessage } from '../../../src/model/message/PersistentHarvestingDelegationMessage'; import { NetworkType } from '../../../src/model/network/NetworkType'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { PersistentDelegationRequestTransaction } from '../../../src/model/transaction/PersistentDelegationRequestTransaction'; describe('PersistentHarvestingDelegationMessage', () => { - let sender: Account; let recipient: Account; - - let sender_nis: Account; let recipient_nis: Account; const delegatedPrivateKey = 'F0AB1010EFEE19EE5373719881DF5123C13E643C519655F7E97347BFF77175BF'; before(() => { - sender = Account.createFromPrivateKey('2602F4236B199B3DF762B2AAB46FC3B77D8DDB214F0B62538D3827576C46C108', - NetworkType.MIJIN_TEST); - recipient = Account.createFromPrivateKey('B72F2950498111BADF276D6D9D5E345F04E0D5C9B8342DA983C3395B4CF18F08', - NetworkType.MIJIN_TEST); - - sender_nis = Account.createFromPrivateKey('2602F4236B199B3DF762B2AAB46FC3B77D8DDB214F0B62538D3827576C46C108', - NetworkType.TEST_NET); - recipient_nis = Account.createFromPrivateKey('B72F2950498111BADF276D6D9D5E345F04E0D5C9B8342DA983C3395B4CF18F08', - NetworkType.TEST_NET); + sender = Account.createFromPrivateKey('2602F4236B199B3DF762B2AAB46FC3B77D8DDB214F0B62538D3827576C46C108', NetworkType.MIJIN_TEST); + recipient = Account.createFromPrivateKey( + 'B72F2950498111BADF276D6D9D5E345F04E0D5C9B8342DA983C3395B4CF18F08', + NetworkType.MIJIN_TEST, + ); + recipient_nis = Account.createFromPrivateKey( + 'B72F2950498111BADF276D6D9D5E345F04E0D5C9B8342DA983C3395B4CF18F08', + NetworkType.TEST_NET, + ); }); it('should create a PersistentHarvestingDelegation message', () => { - const encryptedMessage = - PersistentHarvestingDelegationMessage - .create(delegatedPrivateKey, recipient.publicKey, NetworkType.MIJIN_TEST); + const encryptedMessage = PersistentHarvestingDelegationMessage.create( + delegatedPrivateKey, + recipient.publicKey, + NetworkType.MIJIN_TEST, + ); expect(encryptedMessage.payload.length).to.be.equal(208); expect(encryptedMessage.type).to.be.equal(MessageType.PersistentHarvestingDelegationMessage); }); it('should create a PersistentHarvestingDelegation message from a DTO', () => { - const payload = 'CC71C764BFE598FC121A1816D40600FF3CE1F5C8839DF6EA01A04A630CBEC5C8A' + - 'C121C890E95BBDC67E50AD37E2442279D1BA2328FB7A1781C59D2F414AEFCA288CD' + - '7B2D9F38D11C186CBD33869F2BB6A9F617A4696E4841628F1F396478BDDD0046BA264A1820'; + const payload = + 'CC71C764BFE598FC121A1816D40600FF3CE1F5C8839DF6EA01A04A630CBEC5C8A' + + 'C121C890E95BBDC67E50AD37E2442279D1BA2328FB7A1781C59D2F414AEFCA288CD' + + '7B2D9F38D11C186CBD33869F2BB6A9F617A4696E4841628F1F396478BDDD0046BA264A1820'; const msgTypeHex = MessageType.PersistentHarvestingDelegationMessage.toString(16).toUpperCase(); const encryptedMessage = PersistentHarvestingDelegationMessage.createFromPayload(payload); expect(encryptedMessage.payload.substring(2)).to.be.equal(payload); @@ -67,40 +67,38 @@ describe('PersistentHarvestingDelegationMessage', () => { }); it('should create and decrypt message', () => { - const encryptedMessage = - PersistentHarvestingDelegationMessage - .create(delegatedPrivateKey, recipient.publicKey, NetworkType.MIJIN_TEST); - const plainMessage = - PersistentHarvestingDelegationMessage.decrypt(encryptedMessage, recipient.privateKey); + const encryptedMessage = PersistentHarvestingDelegationMessage.create( + delegatedPrivateKey, + recipient.publicKey, + NetworkType.MIJIN_TEST, + ); + const plainMessage = PersistentHarvestingDelegationMessage.decrypt(encryptedMessage, recipient.privateKey); expect(plainMessage).to.be.equal(delegatedPrivateKey); }); it('return decrepted message reading from message payload', () => { const generationHash = '57F7DA205008026C776CB6AED843393F04CD458E0AA2D9F1D5F31A402072B2D6'; - const tx = - PersistentDelegationRequestTransaction.createPersistentDelegationRequestTransaction( - Deadline.create(), - delegatedPrivateKey, - recipient.publicKey, - NetworkType.MIJIN_TEST, - ); + const tx = PersistentDelegationRequestTransaction.createPersistentDelegationRequestTransaction( + Deadline.create(), + delegatedPrivateKey, + recipient.publicKey, + NetworkType.MIJIN_TEST, + ); const signedTransaction = tx.signWith(sender, generationHash); - const encryptMessage = - PersistentHarvestingDelegationMessage - .createFromPayload(signedTransaction.payload.substring(322, signedTransaction.payload.length)); - const plainMessage = - PersistentHarvestingDelegationMessage.decrypt(encryptMessage, recipient.privateKey); + const encryptMessage = PersistentHarvestingDelegationMessage.createFromPayload( + signedTransaction.payload.substring(322, signedTransaction.payload.length), + ); + const plainMessage = PersistentHarvestingDelegationMessage.decrypt(encryptMessage, recipient.privateKey); expect(plainMessage).to.be.equal(delegatedPrivateKey); }); it('should encrypt and decrypt message using NIS1 schema', () => { - const encryptedMessage = - PersistentHarvestingDelegationMessage - .create(delegatedPrivateKey, recipient_nis.publicKey, NetworkType.TEST_NET); - const plainMessage = - PersistentHarvestingDelegationMessage.decrypt(encryptedMessage, - recipient_nis.privateKey); + const encryptedMessage = PersistentHarvestingDelegationMessage.create( + delegatedPrivateKey, + recipient_nis.publicKey, + NetworkType.TEST_NET, + ); + const plainMessage = PersistentHarvestingDelegationMessage.decrypt(encryptedMessage, recipient_nis.privateKey); expect(plainMessage).to.be.equal(delegatedPrivateKey); }); - }); diff --git a/test/model/message/PlainMessage.spec.ts b/test/model/message/PlainMessage.spec.ts index 7d03f39355..fcbc8b7eeb 100644 --- a/test/model/message/PlainMessage.spec.ts +++ b/test/model/message/PlainMessage.spec.ts @@ -14,11 +14,10 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {EmptyMessage, PlainMessage} from '../../../src/model/message/PlainMessage'; +import { expect } from 'chai'; +import { EmptyMessage, PlainMessage } from '../../../src/model/message/PlainMessage'; describe('PlainMessage', () => { - it('should createComplete an empty message', () => { expect(EmptyMessage.payload).to.be.equal(''); }); @@ -35,7 +34,7 @@ describe('PlainMessage', () => { expect(message.payload).to.be.equal('test-message'); }); - it('should decode hex message', () => { + it('should decode hex message', () => { const hexMessage = '746573742D6D657373616765'; const decodedMessage = PlainMessage.decodeHex(hexMessage); expect(decodedMessage).to.be.equal('test-message'); diff --git a/test/model/metadata/Metadata.spec.ts b/test/model/metadata/Metadata.spec.ts index f4be431246..ed05e85113 100644 --- a/test/model/metadata/Metadata.spec.ts +++ b/test/model/metadata/Metadata.spec.ts @@ -14,12 +14,12 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; +import { deepEqual } from 'assert'; import { Account } from '../../../src/model/account/Account'; import { Metadata } from '../../../src/model/metadata/Metadata'; import { MetadataEntry } from '../../../src/model/metadata/MetadataEntry'; import { MetadataType } from '../../../src/model/metadata/MetadataType'; -import {UInt64} from '../../../src/model/UInt64'; +import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; describe('Metadata', () => { diff --git a/test/model/metadata/MetadataEntry.spec.ts b/test/model/metadata/MetadataEntry.spec.ts index 3932f4485f..26c319f6e3 100644 --- a/test/model/metadata/MetadataEntry.spec.ts +++ b/test/model/metadata/MetadataEntry.spec.ts @@ -14,12 +14,12 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; +import { deepEqual } from 'assert'; import { Account } from '../../../src/model/account/Account'; import { MetadataEntry } from '../../../src/model/metadata/MetadataEntry'; import { MetadataType } from '../../../src/model/metadata/MetadataType'; import { MosaicId, NamespaceId } from '../../../src/model/model'; -import {UInt64} from '../../../src/model/UInt64'; +import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; describe('MetadataEntry', () => { diff --git a/test/model/mosaic/Mosaic.spec.ts b/test/model/mosaic/Mosaic.spec.ts index 5364952fad..128f5b27cb 100644 --- a/test/model/mosaic/Mosaic.spec.ts +++ b/test/model/mosaic/Mosaic.spec.ts @@ -14,23 +14,19 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {Mosaic} from '../../../src/model/mosaic/Mosaic'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {UInt64} from '../../../src/model/UInt64'; +import { deepEqual } from 'assert'; +import { Mosaic } from '../../../src/model/mosaic/Mosaic'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { UInt64 } from '../../../src/model/UInt64'; describe('Mosaic', () => { - it('should createComplete an Mosaic object', () => { const mosaicDTO = { - amount: new UInt64([ 1, 0 ]), + amount: new UInt64([1, 0]), mosaicId: new MosaicId([3646934825, 3576016193]), }; - const mosaic = new Mosaic( - mosaicDTO.mosaicId, - mosaicDTO.amount, - ); + const mosaic = new Mosaic(mosaicDTO.mosaicId, mosaicDTO.amount); deepEqual(mosaic.id, mosaicDTO.mosaicId); deepEqual(mosaic.amount, mosaicDTO.amount); diff --git a/test/model/mosaic/MosaicAmountView.spec.ts b/test/model/mosaic/MosaicAmountView.spec.ts index 72bbab4cdd..9d6f279148 100644 --- a/test/model/mosaic/MosaicAmountView.spec.ts +++ b/test/model/mosaic/MosaicAmountView.spec.ts @@ -14,17 +14,16 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {MosaicFlags} from '../../../src/model/mosaic/MosaicFlags'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {MosaicInfo} from '../../../src/model/mosaic/MosaicInfo'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {UInt64} from '../../../src/model/UInt64'; -import {MosaicAmountView} from '../../../src/service/MosaicAmountView'; +import { expect } from 'chai'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { MosaicFlags } from '../../../src/model/mosaic/MosaicFlags'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { MosaicInfo } from '../../../src/model/mosaic/MosaicInfo'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { UInt64 } from '../../../src/model/UInt64'; +import { MosaicAmountView } from '../../../src/service/MosaicAmountView'; describe('MosaicAmountView', () => { - let mosaicInfo: MosaicInfo; before(() => { diff --git a/test/model/mosaic/MosaicFlags.spec.ts b/test/model/mosaic/MosaicFlags.spec.ts index e38eada1cc..3f60af5a3e 100644 --- a/test/model/mosaic/MosaicFlags.spec.ts +++ b/test/model/mosaic/MosaicFlags.spec.ts @@ -14,13 +14,10 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {MosaicFlags} from '../../../src/model/mosaic/MosaicFlags'; -import {UInt64} from '../../../src/model/UInt64'; +import { expect } from 'chai'; +import { MosaicFlags } from '../../../src/model/mosaic/MosaicFlags'; describe('MosaicFlags', () => { - it('should createComplete an MosaicFlags object with constructor', () => { const mosaicFlags = new MosaicFlags(7); expect(mosaicFlags.supplyMutable).to.be.equal(true); @@ -29,8 +26,6 @@ describe('MosaicFlags', () => { }); it('should createComplete an mosaicFlags object with static method', () => { - const duration = UInt64.fromUint(1000); - const mosaicFlags = MosaicFlags.create(false, false, false); expect(mosaicFlags.supplyMutable).to.be.equal(false); diff --git a/test/model/mosaic/MosaicInfo.spec.ts b/test/model/mosaic/MosaicInfo.spec.ts index 6439174a05..bee1bb148d 100644 --- a/test/model/mosaic/MosaicInfo.spec.ts +++ b/test/model/mosaic/MosaicInfo.spec.ts @@ -14,14 +14,14 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {MosaicFlags} from '../../../src/model/mosaic/MosaicFlags'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {MosaicInfo} from '../../../src/model/mosaic/MosaicInfo'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {UInt64} from '../../../src/model/UInt64'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { MosaicFlags } from '../../../src/model/mosaic/MosaicFlags'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { MosaicInfo } from '../../../src/model/mosaic/MosaicInfo'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { UInt64 } from '../../../src/model/UInt64'; describe('MosaicInfo', () => { const mosaicInfoDTO = { @@ -34,7 +34,8 @@ describe('MosaicInfo', () => { height: new UInt64([1, 0]), owner: PublicAccount.createFromPublicKey( 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', - NetworkType.MIJIN_TEST), + NetworkType.MIJIN_TEST, + ), revision: 1, flags: 7, divisibility: 3, @@ -42,10 +43,6 @@ describe('MosaicInfo', () => { }, }; - before(() => { - - }); - it('should createComplete an MosaicInfo object', () => { const mosaicInfo = new MosaicInfo( mosaicInfoDTO.mosaic.mosaicId, @@ -66,7 +63,6 @@ describe('MosaicInfo', () => { expect(mosaicInfo.divisibility).to.be.equal(mosaicInfoDTO.mosaic.divisibility); deepEqual(mosaicInfo.duration.toString(), mosaicInfoDTO.mosaic.duration); - }); it('should createComplete an MosaicInfo object without duration', () => { @@ -79,8 +75,7 @@ describe('MosaicInfo', () => { mosaicInfoDTO.mosaic.revision, new MosaicFlags(mosaicInfoDTO.mosaic.flags), mosaicInfoDTO.mosaic.divisibility, - UInt64.fromNumericString(mosaicInfoDTO.mosaic.duration, - ), + UInt64.fromNumericString(mosaicInfoDTO.mosaic.duration), ); deepEqual(mosaicInfo.id, mosaicInfoDTO.mosaic.mosaicId); @@ -91,11 +86,10 @@ describe('MosaicInfo', () => { expect(mosaicInfo.divisibility).to.be.equal(mosaicInfoDTO.mosaic.divisibility); deepEqual(mosaicInfo.duration.toDTO(), [0, 0]); - }); describe('isSupplyMutable', () => { - it('should return true when it\'s mutable', () => { + it("should return true when it's mutable", () => { const mosaicInfo = new MosaicInfo( mosaicInfoDTO.mosaic.mosaicId, mosaicInfoDTO.mosaic.supply, @@ -105,12 +99,11 @@ describe('MosaicInfo', () => { MosaicFlags.create(true, false, false), mosaicInfoDTO.mosaic.divisibility, UInt64.fromNumericString(mosaicInfoDTO.mosaic.duration), - ) - ; + ); expect(mosaicInfo.isSupplyMutable()).to.be.equal(true); }); - it('should return false when it\'s immutable', () => { + it("should return false when it's immutable", () => { const mosaicInfo = new MosaicInfo( mosaicInfoDTO.mosaic.mosaicId, mosaicInfoDTO.mosaic.supply, @@ -126,7 +119,7 @@ describe('MosaicInfo', () => { }); describe('isTransferable', () => { - it('should return true when it\'s transferable', () => { + it("should return true when it's transferable", () => { const mosaicInfo = new MosaicInfo( mosaicInfoDTO.mosaic.mosaicId, mosaicInfoDTO.mosaic.supply, @@ -140,7 +133,7 @@ describe('MosaicInfo', () => { expect(mosaicInfo.isTransferable()).to.be.equal(true); }); - it('should return false when it\'s not transferable', () => { + it("should return false when it's not transferable", () => { const mosaicInfo = new MosaicInfo( mosaicInfoDTO.mosaic.mosaicId, mosaicInfoDTO.mosaic.supply, @@ -156,7 +149,7 @@ describe('MosaicInfo', () => { }); describe('isRestrictable', () => { - it('should return true when it\'s restrictable', () => { + it("should return true when it's restrictable", () => { const mosaicInfo = new MosaicInfo( mosaicInfoDTO.mosaic.mosaicId, mosaicInfoDTO.mosaic.supply, @@ -170,7 +163,7 @@ describe('MosaicInfo', () => { expect(mosaicInfo.isRestrictable()).to.be.equal(true); }); - it('should return false when it\'s not restrictable', () => { + it("should return false when it's not restrictable", () => { const mosaicInfo = new MosaicInfo( mosaicInfoDTO.mosaic.mosaicId, mosaicInfoDTO.mosaic.supply, diff --git a/test/model/mosaic/MosaicNames.spec.ts b/test/model/mosaic/MosaicNames.spec.ts new file mode 100644 index 0000000000..f428599622 --- /dev/null +++ b/test/model/mosaic/MosaicNames.spec.ts @@ -0,0 +1,39 @@ +/* + * Copyright 2018 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { expect } from 'chai'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { MosaicNames } from '../../../src/model/mosaic/MosaicNames'; +import { NamespaceName } from '../../../src/model/namespace/NamespaceName'; +import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; + +describe('MosaicNames', () => { + let namespaceName: NamespaceName[]; + let mosaicId: MosaicId; + + before(() => { + namespaceName = [new NamespaceName(new NamespaceId('test'), 'test')]; + mosaicId = new MosaicId('85BBEA6CC462B244'); + }); + + it('should createComplete a Mosaic name', () => { + const mosaicNames = new MosaicNames(mosaicId, namespaceName); + expect(mosaicNames.mosaicId.toHex()).to.be.equal('85BBEA6CC462B244'); + expect(mosaicNames.names[0].name).to.be.equal('test'); + expect(mosaicNames.names[0].parentId).to.be.undefined; + expect(mosaicNames.names[0].namespaceId.fullName).to.be.equal('test'); + }); +}); diff --git a/test/model/mosaic/MosaicNonce.spec.ts b/test/model/mosaic/MosaicNonce.spec.ts index 0247f64449..af5941907c 100644 --- a/test/model/mosaic/MosaicNonce.spec.ts +++ b/test/model/mosaic/MosaicNonce.spec.ts @@ -18,7 +18,6 @@ import { expect } from 'chai'; import { MosaicNonce } from '../../../src/model/mosaic/MosaicNonce'; describe('MosaicNonce', () => { - it('should be created from Uint8Array', () => { const nonce = new MosaicNonce(new Uint8Array([0, 0, 0, 0])); deepEqual(nonce.toDTO(), 0); diff --git a/test/model/mosaic/MosaicView.spec.ts b/test/model/mosaic/MosaicView.spec.ts index 996db20578..0e65b7f98c 100644 --- a/test/model/mosaic/MosaicView.spec.ts +++ b/test/model/mosaic/MosaicView.spec.ts @@ -14,17 +14,16 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; +import { expect } from 'chai'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; import { MosaicFlags } from '../../../src/model/mosaic/MosaicFlags'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {MosaicInfo} from '../../../src/model/mosaic/MosaicInfo'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {UInt64} from '../../../src/model/UInt64'; -import {MosaicView} from '../../../src/service/MosaicView'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { MosaicInfo } from '../../../src/model/mosaic/MosaicInfo'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { UInt64 } from '../../../src/model/UInt64'; +import { MosaicView } from '../../../src/service/MosaicView'; describe('MosaicView', () => { - let mosaicInfo: MosaicInfo; before(() => { @@ -36,7 +35,8 @@ describe('MosaicView', () => { 1, // revision MosaicFlags.create(true, true, true), 2, - UInt64.fromUint(1000)); + UInt64.fromUint(1000), + ); }); it('should createComplete a Mosaic View', () => { diff --git a/test/model/mosaic/NetworkCurrency.spec.ts b/test/model/mosaic/NetworkCurrency.spec.ts index 7f61656afa..7bcbb4f0b4 100644 --- a/test/model/mosaic/NetworkCurrency.spec.ts +++ b/test/model/mosaic/NetworkCurrency.spec.ts @@ -14,25 +14,29 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {NetworkCurrencyLocal} from '../../../src/model/mosaic/NetworkCurrencyLocal'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyLocal'; import { NetworkCurrencyPublic } from '../../../src/model/mosaic/NetworkCurrencyPublic'; -import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; +import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; import { UInt64 } from '../../../src/model/UInt64'; describe('NetworkCurrencyLocal', () => { - it('should createComplete an NetworkCurrencyLocal object', () => { - const currency = NetworkCurrencyLocal.createRelative(1000); deepEqual(currency.id.id.toHex(), '85BBEA6CC462B244'); // holds NAMESPACE_ID expect(currency.amount.compact()).to.be.equal(1000 * 1000000); }); - it('should set amount in smallest unit when toDTO()', () => { + it('should createComplete an NetworkCurrencyLocal object', () => { + const currency = NetworkCurrencyLocal.createRelative(UInt64.fromUint(1000)); + deepEqual(currency.id.id.toHex(), '85BBEA6CC462B244'); // holds NAMESPACE_ID + expect(currency.amount.compact()).to.be.equal(1000 * 1000000); + }); + + it('should set amount in smallest unit when toDTO()', () => { const currency = NetworkCurrencyLocal.createRelative(1000); expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000 * 1000000); }); @@ -43,19 +47,32 @@ describe('NetworkCurrencyLocal', () => { expect(NetworkCurrencyLocal.TRANSFERABLE).to.be.equal(true); expect(NetworkCurrencyLocal.SUPPLY_MUTABLE).to.be.equal(false); }); + + it('should create network currency with absolute amount', () => { + const currency = NetworkCurrencyLocal.createAbsolute(1000); + expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000); + }); + + it('should create network currency with absolute amount in Uint64', () => { + const currency = NetworkCurrencyLocal.createAbsolute(UInt64.fromUint(1000)); + expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000); + }); }); describe('NetworkCurrencyPublic', () => { - it('should createComplete an NetworkCurrencyPublic object', () => { - const currency = NetworkCurrencyPublic.createRelative(1000); deepEqual(currency.id.id.toHex(), 'E74B99BA41F4AFEE'); // holds NAMESPACE_ID expect(currency.amount.compact()).to.be.equal(1000 * 1000000); }); - it('should set amount in smallest unit when toDTO()', () => { + it('should createComplete an NetworkCurrencyPublic object', () => { + const currency = NetworkCurrencyPublic.createRelative(UInt64.fromUint(1000)); + deepEqual(currency.id.id.toHex(), 'E74B99BA41F4AFEE'); // holds NAMESPACE_ID + expect(currency.amount.compact()).to.be.equal(1000 * 1000000); + }); + it('should set amount in smallest unit when toDTO()', () => { const currency = NetworkCurrencyPublic.createRelative(1000); expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000 * 1000000); }); @@ -66,4 +83,14 @@ describe('NetworkCurrencyPublic', () => { expect(NetworkCurrencyPublic.TRANSFERABLE).to.be.equal(true); expect(NetworkCurrencyPublic.SUPPLY_MUTABLE).to.be.equal(false); }); + + it('should create network currency with absolute amount', () => { + const currency = NetworkCurrencyPublic.createAbsolute(1000); + expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000); + }); + + it('should create network currency with absolute amount in Uint64', () => { + const currency = NetworkCurrencyPublic.createAbsolute(UInt64.fromUint(1000)); + expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000); + }); }); diff --git a/test/model/mosaic/NetworkHarvestLocal.spec.ts b/test/model/mosaic/NetworkHarvestLocal.spec.ts index 83cf35dd91..acf1389bc2 100644 --- a/test/model/mosaic/NetworkHarvestLocal.spec.ts +++ b/test/model/mosaic/NetworkHarvestLocal.spec.ts @@ -14,25 +14,28 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {NetworkHarvestLocal} from '../../../src/model/mosaic/NetworkHarvestLocal'; -import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { NetworkHarvestLocal } from '../../../src/model/mosaic/NetworkHarvestLocal'; +import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; import { UInt64 } from '../../../src/model/UInt64'; describe('NetworkHarvestLocal', () => { - it('should createComplete an NetworkHarvestLocal object', () => { - const currency = NetworkHarvestLocal.createRelative(1000); deepEqual(currency.id.id.toHex(), '941299B2B7E1291C'); expect(currency.amount.compact()).to.be.equal(1000 * 1000); }); - it('should set amount in smallest unit when toDTO()', () => { + it('should createComplete an NetworkHarvestLocal object', () => { + const currency = NetworkHarvestLocal.createRelative(UInt64.fromUint(1000)); + deepEqual(currency.id.id.toHex(), '941299B2B7E1291C'); + expect(currency.amount.compact()).to.be.equal(1000 * 1000); + }); + + it('should set amount in smallest unit when toDTO()', () => { const currency = NetworkHarvestLocal.createRelative(1000); expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000 * 1000); }); @@ -43,4 +46,14 @@ describe('NetworkHarvestLocal', () => { expect(NetworkHarvestLocal.TRANSFERABLE).to.be.equal(true); expect(NetworkHarvestLocal.SUPPLY_MUTABLE).to.be.equal(true); }); + + it('should create network currency with absolute amount', () => { + const currency = NetworkHarvestLocal.createAbsolute(1000); + expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000); + }); + + it('should create network currency with absolute amount in Uint64', () => { + const currency = NetworkHarvestLocal.createAbsolute(UInt64.fromUint(1000)); + expect(UInt64.fromNumericString(currency.toDTO().amount).toDTO()[0]).to.be.equal(1000); + }); }); diff --git a/test/model/namespace/Alias.spec.ts b/test/model/namespace/Alias.spec.ts index 669ade46d7..362cb21708 100644 --- a/test/model/namespace/Alias.spec.ts +++ b/test/model/namespace/Alias.spec.ts @@ -14,20 +14,15 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {Address} from '../../../src/model/account/Address'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {AddressAlias} from '../../../src/model/namespace/AddressAlias'; -import {Alias} from '../../../src/model/namespace/Alias'; -import {AliasType} from '../../../src/model/namespace/AliasType'; -import {EmptyAlias} from '../../../src/model/namespace/EmptyAlias'; -import {MosaicAlias} from '../../../src/model/namespace/MosaicAlias'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {UInt64} from '../../../src/model/UInt64'; +import { expect } from 'chai'; +import { Address } from '../../../src/model/account/Address'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { AddressAlias } from '../../../src/model/namespace/AddressAlias'; +import { AliasType } from '../../../src/model/namespace/AliasType'; +import { EmptyAlias } from '../../../src/model/namespace/EmptyAlias'; +import { MosaicAlias } from '../../../src/model/namespace/MosaicAlias'; describe('Alias', () => { - let emptyAliasDTO; let addressAliasDTO; let mosaicAliasDTO; let address; @@ -36,9 +31,6 @@ describe('Alias', () => { before(() => { address = Address.createFromRawAddress('SCTVW23D2MN5VE4AQ4TZIDZENGNOZXPRPRLIKCF2'); address2 = Address.createFromRawAddress('SARNASAS2BIAB6LMFA3FPMGBPGIJGK6IJETM3ZSP'); - emptyAliasDTO = { - type: 0, - }; mosaicAliasDTO = { type: AliasType.Mosaic, mosaicId: new MosaicId([481110499, 231112638]), @@ -55,7 +47,7 @@ describe('Alias', () => { }); it('should create a AddressAlias object', () => { - const alias = new AddressAlias( addressAliasDTO.address); + const alias = new AddressAlias(addressAliasDTO.address); expect(alias.type).to.be.equal(AliasType.Address); expect(alias.address).to.be.equal(addressAliasDTO.address); }); diff --git a/test/model/namespace/NamespaceId.spec.ts b/test/model/namespace/NamespaceId.spec.ts index 1e373c4878..3c6b0c475a 100644 --- a/test/model/namespace/NamespaceId.spec.ts +++ b/test/model/namespace/NamespaceId.spec.ts @@ -14,11 +14,10 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {Id} from '../../../src/model/Id'; -import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; -import { UInt64 } from '../../../src/model/UInt64'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { Id } from '../../../src/model/Id'; +import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; describe('NamespaceId', () => { it('should be created from root namespace name', () => { @@ -40,16 +39,16 @@ describe('NamespaceId', () => { }); const vectors = [ - {encoded: '84B3552D375FFA4B', uint: [929036875, 2226345261]}, // new NamespaceId('nem') - {encoded: 'F8495AEE892FA108', uint: [2301600008, 4165556974]}, // new NamespaceId('nem.owner.test1') - {encoded: 'ABAEF4E86505811F', uint: [1694859551, 2880369896]}, // new NamespaceId('nem.owner.test2') - {encoded: 'AEB8C92B0A1C2D55', uint: [169618773, 2931345707]}, // new NamespaceId('nem.owner.test3') - {encoded: '90E09AD44014CABF', uint: [1075104447, 2430638804]}, // new NamespaceId('nem.owner.test4') - {encoded: 'AB114281960BF1CC', uint: [2517365196, 2870035073]}, // new NamespaceId('nem.owner.test5') + { encoded: '84B3552D375FFA4B', uint: [929036875, 2226345261] }, // new NamespaceId('nem') + { encoded: 'F8495AEE892FA108', uint: [2301600008, 4165556974] }, // new NamespaceId('nem.owner.test1') + { encoded: 'ABAEF4E86505811F', uint: [1694859551, 2880369896] }, // new NamespaceId('nem.owner.test2') + { encoded: 'AEB8C92B0A1C2D55', uint: [169618773, 2931345707] }, // new NamespaceId('nem.owner.test3') + { encoded: '90E09AD44014CABF', uint: [1075104447, 2430638804] }, // new NamespaceId('nem.owner.test4') + { encoded: 'AB114281960BF1CC', uint: [2517365196, 2870035073] }, // new NamespaceId('nem.owner.test5') ]; it('should be created from encoded vectors', () => { - vectors.map(({encoded, uint}) => { + vectors.map(({ encoded, uint }) => { const fromHex = NamespaceId.createFromEncoded(encoded.toUpperCase()); const fromId = new NamespaceId(uint); deepEqual(fromId.id, fromHex.id); diff --git a/test/model/namespace/NamespaceInfo.spec.ts b/test/model/namespace/NamespaceInfo.spec.ts index e63a5f0149..7d7a35f793 100644 --- a/test/model/namespace/NamespaceInfo.spec.ts +++ b/test/model/namespace/NamespaceInfo.spec.ts @@ -14,18 +14,49 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; -import {NamespaceInfo} from '../../../src/model/namespace/NamespaceInfo'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {UInt64} from '../../../src/model/UInt64'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NamespaceInfo } from '../../../src/model/namespace/NamespaceInfo'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { UInt64 } from '../../../src/model/UInt64'; describe('NamespaceInfo', () => { let rootNamespaceDTO; let subNamespaceDTO; + function createRootFromDTO(dto): NamespaceInfo { + return new NamespaceInfo( + dto.meta.active, + dto.meta.index, + dto.meta.id, + dto.namespace.type, + dto.namespace.depth, + [dto.namespace.level0], + dto.namespace.parentId, + PublicAccount.createFromPublicKey(dto.namespace.owner, NetworkType.MIJIN_TEST), + dto.namespace.startHeight, + dto.namespace.endHeight, + dto.namespace.alias, + ); + } + + function createSubnamespaceFromDTO(dto): NamespaceInfo { + return new NamespaceInfo( + dto.meta.active, + dto.meta.index, + dto.meta.id, + dto.namespace.type, + dto.namespace.depth, + [dto.namespace.level0, dto.namespace.level1], + dto.namespace.parentId, + PublicAccount.createFromPublicKey(dto.namespace.owner, NetworkType.MIJIN_TEST), + dto.namespace.startHeight, + dto.namespace.endHeight, + dto.namespace.alias, + ); + } before(() => { rootNamespaceDTO = { @@ -42,7 +73,7 @@ describe('NamespaceInfo', () => { parentId: new NamespaceId([0, 0]), startHeight: new UInt64([1, 0]), type: 0, - alias: {type: 1, mosaicId: new MosaicId([481110499, 231112638])}, + alias: { type: 1, mosaicId: new MosaicId([481110499, 231112638]) }, }, }; subNamespaceDTO = { @@ -54,28 +85,13 @@ describe('NamespaceInfo', () => { namespace: { type: 1, depth: 2, - level0: new NamespaceId([ - 3316183705, - 3829351378, - ]), - level1: new NamespaceId([ - 1781696705, - 4157485863, - ]), - parentId: new NamespaceId([ - 3316183705, - 3829351378, - ]), + level0: new NamespaceId([3316183705, 3829351378]), + level1: new NamespaceId([1781696705, 4157485863]), + parentId: new NamespaceId([3316183705, 3829351378]), owner: '846B4439154579A5903B1459C9CF69CB8153F6D0110A7A0ED61DE29AE4810BF2', - startHeight: [ - 795, - 0, - ], - endHeight: [ - 50795, - 0, - ], - alias: {type: 0}, + startHeight: [795, 0], + endHeight: [50795, 0], + alias: { type: 0 }, }, }; }); @@ -157,39 +173,4 @@ describe('NamespaceInfo', () => { const namespaceInfo = createSubnamespaceFromDTO(subNamespaceDTO); expect(namespaceInfo.hasAlias()).to.be.equal(false); }); - - // region functions - function createRootFromDTO(dto): NamespaceInfo { - return new NamespaceInfo( - dto.meta.active, - dto.meta.index, - dto.meta.id, - dto.namespace.type, - dto.namespace.depth, - [dto.namespace.level0], - dto.namespace.parentId, - PublicAccount.createFromPublicKey(dto.namespace.owner, NetworkType.MIJIN_TEST), - dto.namespace.startHeight, - dto.namespace.endHeight, - dto.namespace.alias, - ); - } - - function createSubnamespaceFromDTO(dto): NamespaceInfo { - return new NamespaceInfo( - dto.meta.active, - dto.meta.index, - dto.meta.id, - dto.namespace.type, - dto.namespace.depth, - [dto.namespace.level0, dto.namespace.level1], - dto.namespace.parentId, - PublicAccount.createFromPublicKey(dto.namespace.owner, NetworkType.MIJIN_TEST), - dto.namespace.startHeight, - dto.namespace.endHeight, - dto.namespace.alias, - ); - } - - // endregion }); diff --git a/test/model/namespace/NamespaceName.spec.ts b/test/model/namespace/NamespaceName.spec.ts index b31e25f008..51381bf109 100644 --- a/test/model/namespace/NamespaceName.spec.ts +++ b/test/model/namespace/NamespaceName.spec.ts @@ -14,13 +14,12 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; -import {NamespaceName} from '../../../src/model/namespace/NamespaceName'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NamespaceName } from '../../../src/model/namespace/NamespaceName'; describe('NamespaceName', () => { - it('should createComplete an NamespaceName object', () => { const namespaceNameDTO = { name: 'nem', @@ -28,11 +27,7 @@ describe('NamespaceName', () => { parentId: new NamespaceId([1431234233, 1324322333]), }; - const namespaceName = new NamespaceName( - namespaceNameDTO.namespaceId, - namespaceNameDTO.name, - namespaceNameDTO.parentId, - ); + const namespaceName = new NamespaceName(namespaceNameDTO.namespaceId, namespaceNameDTO.name, namespaceNameDTO.parentId); deepEqual(namespaceName.namespaceId, namespaceNameDTO.namespaceId); deepEqual(namespaceName.parentId, namespaceNameDTO.parentId); diff --git a/test/model/network/NetworkType.spec.ts b/test/model/network/NetworkType.spec.ts index d018a5445d..24cb724f19 100644 --- a/test/model/network/NetworkType.spec.ts +++ b/test/model/network/NetworkType.spec.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { expect } from 'chai'; +import { NetworkType } from '../../../src/model/network/NetworkType'; describe('NetworkType', () => { it('MAIN_NET is 0x68', () => { diff --git a/test/model/receipt/Receipt.spec.ts b/test/model/receipt/Receipt.spec.ts index 3ad33b82ca..1f877ccb74 100644 --- a/test/model/receipt/Receipt.spec.ts +++ b/test/model/receipt/Receipt.spec.ts @@ -16,10 +16,7 @@ import { deepEqual } from 'assert'; import { expect } from 'chai'; -import { - CreateReceiptFromDTO, - CreateStatementFromDTO, -} from '../../../src/infrastructure/receipt/CreateReceiptFromDTO'; +import { CreateReceiptFromDTO, CreateStatementFromDTO } from '../../../src/infrastructure/receipt/CreateReceiptFromDTO'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; import { PublicAccount } from '../../../src/model/account/PublicAccount'; @@ -41,7 +38,6 @@ import { UInt64 } from '../../../src/model/UInt64'; describe('Receipt', () => { let account: Account; - let account2: Account; let transactionStatementsDTO; let addressResolutionStatementsDTO; let mosaicResolutionStatementsDTO; @@ -50,14 +46,13 @@ describe('Receipt', () => { before(() => { account = Account.createFromPrivateKey('D242FB34C2C4DD36E995B9C865F93940065E326661BA5A4A247331D211FE3A3D', NetworkType.MIJIN_TEST); - account2 = Account.createFromPrivateKey('E5DCCEBDB01A8B03A7DB7BA5888E2E33FD4617B5F6FED48C4C09C0780F422713', NetworkType.MIJIN_TEST); transactionStatementsDTO = [ { statement: { height: '52', source: { - primaryId: 0, - secondaryId: 0, + primaryId: 0, + secondaryId: 0, }, receipts: [ { @@ -77,13 +72,13 @@ describe('Receipt', () => { height: '1488', unresolved: '9103B60AAF2762688300000000000000000000000000000000', resolutionEntries: [ - { - source: { - primaryId: 4, - secondaryId: 0, + { + source: { + primaryId: 4, + secondaryId: 0, + }, + resolved: '917E7E29A01014C2F300000000000000000000000000000000', }, - resolved: '917E7E29A01014C2F300000000000000000000000000000000', - }, ], }, }, @@ -92,13 +87,13 @@ describe('Receipt', () => { height: '1488', unresolved: '917E7E29A01014C2F300000000000000000000000000000000', resolutionEntries: [ - { - source: { - primaryId: 2, - secondaryId: 0, + { + source: { + primaryId: 2, + secondaryId: 0, + }, + resolved: '9103B60AAF2762688300000000000000000000000000000000', }, - resolved: '9103B60AAF2762688300000000000000000000000000000000', - }, ], }, }, @@ -109,13 +104,13 @@ describe('Receipt', () => { height: '1506', unresolved: '85BBEA6CC462B244', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '941299B2B7E1291C', }, - resolved: '941299B2B7E1291C', - }, ], }, }, @@ -124,13 +119,13 @@ describe('Receipt', () => { height: '1506', unresolved: '85BBEA6CC462B244', resolutionEntries: [ - { - source: { - primaryId: 5, - secondaryId: 0, + { + source: { + primaryId: 5, + secondaryId: 0, + }, + resolved: '941299B2B7E1291C', }, - resolved: '941299B2B7E1291C', - }, ], }, }, @@ -151,7 +146,7 @@ describe('Receipt', () => { recipientAddress: '9103B60AAF2762688300000000000000000000000000000000', mosaicId: '941299B2B7E1291C', amount: '1000', - }; + }; const receipt = new BalanceTransferReceipt( PublicAccount.createFromPublicKey(receiptDTO.senderPublicKey, netWorkType), Address.createFromEncoded(receiptDTO.recipientAddress), @@ -249,11 +244,7 @@ describe('Receipt', () => { artifactId: 'D525AD41D95FCF29', }; - const receipt = new ArtifactExpiryReceipt( - new NamespaceId([3646934825, 3576016193]), - receiptDTO.version, - receiptDTO.type, - ); + const receipt = new ArtifactExpiryReceipt(new NamespaceId([3646934825, 3576016193]), receiptDTO.version, receiptDTO.type); deepEqual(receipt.artifactId.id.toHex().toUpperCase(), receiptDTO.artifactId); deepEqual(receipt.type, ReceiptType.Namespace_Expired); @@ -267,11 +258,7 @@ describe('Receipt', () => { artifactId: '941299B2B7E1291C', }; - const receipt = new ArtifactExpiryReceipt( - new MosaicId(receiptDTO.artifactId), - receiptDTO.version, - receiptDTO.type, - ); + const receipt = new ArtifactExpiryReceipt(new MosaicId(receiptDTO.artifactId), receiptDTO.version, receiptDTO.type); deepEqual(receipt.artifactId.toHex().toUpperCase(), receiptDTO.artifactId); deepEqual(receipt.type, ReceiptType.Mosaic_Expired); deepEqual(receipt.version, ReceiptVersion.ARTIFACT_EXPIRY); @@ -281,9 +268,8 @@ describe('Receipt', () => { const statementDto = transactionStatementsDTO[0]; const statement = new TransactionStatement( statementDto.statement.height, - new ReceiptSource( statementDto.statement.source.primaryId, statementDto.statement.source.secondaryId), - statementDto.statement.receipts.map((receipt) => - CreateReceiptFromDTO(receipt, netWorkType)), + new ReceiptSource(statementDto.statement.source.primaryId, statementDto.statement.source.secondaryId), + statementDto.statement.receipts.map((receipt) => CreateReceiptFromDTO(receipt, netWorkType)), ); deepEqual(statement.source.primaryId, statementDto.statement.source.primaryId); deepEqual(statement.source.secondaryId, statementDto.statement.source.secondaryId); @@ -297,8 +283,10 @@ describe('Receipt', () => { statementDto.statement.height, new MosaicId(statementDto.statement.unresolved), statementDto.statement.resolutionEntries.map((resolved) => { - return new ResolutionEntry(new MosaicId(resolved.resolved), - new ReceiptSource( resolved.source.primaryId, resolved.source.secondaryId)); + return new ResolutionEntry( + new MosaicId(resolved.resolved), + new ReceiptSource(resolved.source.primaryId, resolved.source.secondaryId), + ); }), ); deepEqual((statement.unresolved as MosaicId).toHex(), statementDto.statement.unresolved); @@ -312,14 +300,20 @@ describe('Receipt', () => { statementDto.statement.height, Address.createFromEncoded(statementDto.statement.unresolved), statementDto.statement.resolutionEntries.map((resolved) => { - return new ResolutionEntry(Address.createFromEncoded(resolved.resolved), - new ReceiptSource( resolved.source.primaryId, resolved.source.secondaryId)); + return new ResolutionEntry( + Address.createFromEncoded(resolved.resolved), + new ReceiptSource(resolved.source.primaryId, resolved.source.secondaryId), + ); }), ); - deepEqual((statement.unresolved as Address).plain(), - Address.createFromEncoded('9103B60AAF2762688300000000000000000000000000000000').plain()); - deepEqual((statement.resolutionEntries[0].resolved as Address).plain(), - Address.createFromEncoded('917E7E29A01014C2F300000000000000000000000000000000').plain()); + deepEqual( + (statement.unresolved as Address).plain(), + Address.createFromEncoded('9103B60AAF2762688300000000000000000000000000000000').plain(), + ); + deepEqual( + (statement.resolutionEntries[0].resolved as Address).plain(), + Address.createFromEncoded('917E7E29A01014C2F300000000000000000000000000000000').plain(), + ); }); it('should createComplete a inflation receipt', () => { diff --git a/test/model/receipt/ResolutionStatement.spec.ts b/test/model/receipt/ResolutionStatement.spec.ts index 5a6b092680..9ddb63b24d 100644 --- a/test/model/receipt/ResolutionStatement.spec.ts +++ b/test/model/receipt/ResolutionStatement.spec.ts @@ -17,7 +17,7 @@ import { expect } from 'chai'; import { CreateStatementFromDTO } from '../../../src/infrastructure/receipt/CreateReceiptFromDTO'; import { Account } from '../../../src/model/account/Account'; -import { Address, MosaicId, NamespaceId, ResolutionType } from '../../../src/model/model'; +import { Address, MosaicId } from '../../../src/model/model'; import { NetworkType } from '../../../src/model/network/NetworkType'; describe('ResolutionStatement', () => { @@ -34,8 +34,8 @@ describe('ResolutionStatement', () => { statement: { height: '1473', source: { - primaryId: 0, - secondaryId: 0, + primaryId: 0, + secondaryId: 0, }, receipts: [ { @@ -55,13 +55,13 @@ describe('ResolutionStatement', () => { height: '1473', unresolved: '9156258DE356F030A500000000000000000000000000000000', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '90AB9480887275E559F3BCA87E6158AA7AFF339BE85E77A0F3', }, - resolved: '90AB9480887275E559F3BCA87E6158AA7AFF339BE85E77A0F3', - }, ], }, }, @@ -72,20 +72,20 @@ describe('ResolutionStatement', () => { height: '1473', unresolved: '85BBEA6CC462B244', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '504677C3281108DB', }, - resolved: '504677C3281108DB', - }, - { - source: { - primaryId: 3, - secondaryId: 5, + { + source: { + primaryId: 3, + secondaryId: 5, + }, + resolved: '401F622A3111A3E4', }, - resolved: '401F622A3111A3E4', - }, ], }, }, @@ -94,13 +94,13 @@ describe('ResolutionStatement', () => { height: '1473', unresolved: 'E81F622A5B11A340', resolutionEntries: [ - { - source: { - primaryId: 3, - secondaryId: 1, + { + source: { + primaryId: 3, + secondaryId: 1, + }, + resolved: '756482FB80FD406C', }, - resolved: '756482FB80FD406C', - }, ], }, }, @@ -109,34 +109,34 @@ describe('ResolutionStatement', () => { height: '1500', unresolved: '85BBEA6CC462B244', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 1, + { + source: { + primaryId: 1, + secondaryId: 1, + }, + resolved: '0DC67FBE1CAD29E5', }, - resolved: '0DC67FBE1CAD29E5', - }, - { - source: { - primaryId: 1, - secondaryId: 4, + { + source: { + primaryId: 1, + secondaryId: 4, + }, + resolved: '7CDF3B117A3C40CC', }, - resolved: '7CDF3B117A3C40CC', - }, - { - source: { - primaryId: 1, - secondaryId: 7, + { + source: { + primaryId: 1, + secondaryId: 7, + }, + resolved: '0DC67FBE1CAD29E5', }, - resolved: '0DC67FBE1CAD29E5', - }, - { - source: { - primaryId: 2, - secondaryId: 4, + { + source: { + primaryId: 2, + secondaryId: 4, + }, + resolved: '7CDF3B117A3C40CC', }, - resolved: '7CDF3B117A3C40CC', - }, ], }, }, @@ -214,5 +214,4 @@ describe('ResolutionStatement', () => { expect((resolution.getResolutionEntryById(1, 6)!.resolved as MosaicId).toHex()).to.be.equal('7CDF3B117A3C40CC'); expect((resolution.getResolutionEntryById(1, 2)!.resolved as MosaicId).toHex()).to.be.equal('0DC67FBE1CAD29E5'); }); - }); diff --git a/test/model/receipt/Statement.spec.ts b/test/model/receipt/Statement.spec.ts index d26b413f74..4969d482fe 100644 --- a/test/model/receipt/Statement.spec.ts +++ b/test/model/receipt/Statement.spec.ts @@ -18,7 +18,7 @@ import { expect } from 'chai'; import { UnresolvedMapping } from '../../../src/core/utils/UnresolvedMapping'; import { CreateStatementFromDTO } from '../../../src/infrastructure/receipt/CreateReceiptFromDTO'; import { Account } from '../../../src/model/account/Account'; -import { Address, MosaicId, NamespaceId, ResolutionType } from '../../../src/model/model'; +import { Address, MosaicId, NamespaceId } from '../../../src/model/model'; import { NetworkType } from '../../../src/model/network/NetworkType'; describe('Statement', () => { @@ -35,8 +35,8 @@ describe('Statement', () => { statement: { height: '1473', source: { - primaryId: 0, - secondaryId: 0, + primaryId: 0, + secondaryId: 0, }, receipts: [ { @@ -56,13 +56,13 @@ describe('Statement', () => { height: '1473', unresolved: '9156258DE356F030A500000000000000000000000000000000', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '90AB9480887275E559F3BCA87E6158AA7AFF339BE85E77A0F3', }, - resolved: '90AB9480887275E559F3BCA87E6158AA7AFF339BE85E77A0F3', - }, ], }, }, @@ -73,13 +73,13 @@ describe('Statement', () => { height: '1473', unresolved: '85BBEA6CC462B244', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '504677C3281108DB', }, - resolved: '504677C3281108DB', - }, ], }, }, @@ -88,13 +88,13 @@ describe('Statement', () => { height: '1473', unresolved: 'E81F622A5B11A340', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '756482FB80FD406C', }, - resolved: '756482FB80FD406C', - }, ], }, }, @@ -125,13 +125,13 @@ describe('Statement', () => { height: '1473', unresolved: '9156258DE356F030A500000000000000000000000000000000', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '90AB9480887275E559F3BCA87E6158AA7AFF339BE85E77A0F3', }, - resolved: '90AB9480887275E559F3BCA87E6158AA7AFF339BE85E77A0F3', - }, ], }, }, @@ -165,13 +165,13 @@ describe('Statement', () => { height: '1473', unresolved: '85BBEA6CC462B244', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '504677C3281108DB', }, - resolved: '504677C3281108DB', - }, ], }, }, @@ -180,13 +180,13 @@ describe('Statement', () => { height: '1473', unresolved: 'E81F622A5B11A340', resolutionEntries: [ - { - source: { - primaryId: 1, - secondaryId: 0, + { + source: { + primaryId: 1, + secondaryId: 0, + }, + resolved: '756482FB80FD406C', }, - resolved: '756482FB80FD406C', - }, ], }, }, @@ -199,5 +199,4 @@ describe('Statement', () => { expect(resolved instanceof MosaicId).to.be.true; expect((resolved as MosaicId).equals(new MosaicId('756482FB80FD406C'))).to.be.true; }); - }); diff --git a/test/model/restriction/AccountRestriction.spec.ts b/test/model/restriction/AccountRestriction.spec.ts index 54e099418a..77b0ccbe33 100644 --- a/test/model/restriction/AccountRestriction.spec.ts +++ b/test/model/restriction/AccountRestriction.spec.ts @@ -14,13 +14,12 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; import { Address } from '../../../src/model/account/Address'; import { AccountRestriction } from '../../../src/model/restriction/AccountRestriction'; import { AccountRestrictionFlags } from '../../../src/model/restriction/AccountRestrictionType'; describe('AccountRestriction', () => { - it('should createComplete an AccountRestriction object', () => { const accountRestrictionDTO = { restrictionFlags: AccountRestrictionFlags.AllowIncomingAddress, diff --git a/test/model/restriction/AccountRestrictions.spec.ts b/test/model/restriction/AccountRestrictions.spec.ts index 20f5243394..1ebda099f0 100644 --- a/test/model/restriction/AccountRestrictions.spec.ts +++ b/test/model/restriction/AccountRestrictions.spec.ts @@ -14,34 +14,35 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {Address} from '../../../src/model/account/Address'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { Address } from '../../../src/model/account/Address'; import { AccountRestriction } from '../../../src/model/restriction/AccountRestriction'; import { AccountRestrictionModificationAction } from '../../../src/model/restriction/AccountRestrictionModificationAction'; import { AccountRestrictions } from '../../../src/model/restriction/AccountRestrictions'; import { AccountRestrictionFlags } from '../../../src/model/restriction/AccountRestrictionType'; describe('AccountRestrictions', () => { - it('should createComplete an AccountRestrictions object', () => { const accountRestrictionsDTO = { address: Address.createFromEncoded('9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142'), - restrictions: [{ - restrictionFlags: AccountRestrictionFlags.AllowIncomingAddress, - values: [{modificationAction: AccountRestrictionModificationAction.Add, - value: 'SDUP5PLHDXKBX3UU5Q52LAY4WYEKGEWC6IB3VBFM', - }], - }], + restrictions: [ + { + restrictionFlags: AccountRestrictionFlags.AllowIncomingAddress, + values: [ + { + modificationAction: AccountRestrictionModificationAction.Add, + value: 'SDUP5PLHDXKBX3UU5Q52LAY4WYEKGEWC6IB3VBFM', + }, + ], + }, + ], }; const accountRestrictions = new AccountRestrictions( accountRestrictionsDTO.address, accountRestrictionsDTO.restrictions.map((r) => { - return new AccountRestriction( - r.restrictionFlags, - r.values, - ); + return new AccountRestriction(r.restrictionFlags, r.values); }), ); @@ -49,8 +50,10 @@ describe('AccountRestrictions', () => { deepEqual(accountRestrictions.restrictions.length, accountRestrictionsDTO.restrictions.length); deepEqual(accountRestrictions.restrictions[0].restrictionFlags, accountRestrictionsDTO.restrictions[0].restrictionFlags); deepEqual(accountRestrictions.restrictions[0].values.length, accountRestrictionsDTO.restrictions[0].values.length); - deepEqual((accountRestrictions.restrictions[0].values[0] as any).modificationAction, - accountRestrictionsDTO.restrictions[0].values[0].modificationAction); + deepEqual( + (accountRestrictions.restrictions[0].values[0] as any).modificationAction, + accountRestrictionsDTO.restrictions[0].values[0].modificationAction, + ); deepEqual((accountRestrictions.restrictions[0].values[0] as any).value, accountRestrictionsDTO.restrictions[0].values[0].value); }); }); diff --git a/test/model/restriction/AccountRestrictionsInfo.spec.ts b/test/model/restriction/AccountRestrictionsInfo.spec.ts index ce14dce10d..81714adf19 100644 --- a/test/model/restriction/AccountRestrictionsInfo.spec.ts +++ b/test/model/restriction/AccountRestrictionsInfo.spec.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {Address} from '../../../src/model/account/Address'; +import { deepEqual } from 'assert'; +import { Address } from '../../../src/model/account/Address'; import { AccountRestriction } from '../../../src/model/restriction/AccountRestriction'; import { AccountRestrictionModificationAction } from '../../../src/model/restriction/AccountRestrictionModificationAction'; import { AccountRestrictions } from '../../../src/model/restriction/AccountRestrictions'; @@ -23,35 +23,47 @@ import { AccountRestrictionsInfo } from '../../../src/model/restriction/AccountR import { AccountRestrictionFlags } from '../../../src/model/restriction/AccountRestrictionType'; describe('AccountRestrictionsInfo', () => { - it('should createComplete an AccountRestrictionsInfo object', () => { - const accountRestrictionsInfoDTO = { - meta: {id: '12345'}, + meta: { id: '12345' }, accountRestrictions: { address: '9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142', - restrictions: [{ - restrictionFlags: AccountRestrictionFlags.AllowIncomingAddress, - values: [{modificationAction: AccountRestrictionModificationAction.Add, - value: 'SDUP5PLHDXKBX3UU5Q52LAY4WYEKGEWC6IB3VBFM', - }], - }], + restrictions: [ + { + restrictionFlags: AccountRestrictionFlags.AllowIncomingAddress, + values: [ + { + modificationAction: AccountRestrictionModificationAction.Add, + value: 'SDUP5PLHDXKBX3UU5Q52LAY4WYEKGEWC6IB3VBFM', + }, + ], + }, + ], }, }; const accountRestrictionsInfo = new AccountRestrictionsInfo( accountRestrictionsInfoDTO.meta, - new AccountRestrictions(Address.createFromEncoded(accountRestrictionsInfoDTO.accountRestrictions.address), - accountRestrictionsInfoDTO.accountRestrictions.restrictions.map((prop) => - new AccountRestriction(prop.restrictionFlags, prop.values))), + new AccountRestrictions( + Address.createFromEncoded(accountRestrictionsInfoDTO.accountRestrictions.address), + accountRestrictionsInfoDTO.accountRestrictions.restrictions.map( + (prop) => new AccountRestriction(prop.restrictionFlags, prop.values), + ), + ), ); deepEqual(accountRestrictionsInfo.meta.id, accountRestrictionsInfoDTO.meta.id); - deepEqual(accountRestrictionsInfo.accountRestrictions.address, - Address.createFromEncoded(accountRestrictionsInfoDTO.accountRestrictions.address)); - deepEqual(accountRestrictionsInfo.accountRestrictions.restrictions.length, - accountRestrictionsInfoDTO.accountRestrictions.restrictions.length); - deepEqual(accountRestrictionsInfo.accountRestrictions.restrictions[0].values[0], - accountRestrictionsInfoDTO.accountRestrictions.restrictions[0].values[0]); + deepEqual( + accountRestrictionsInfo.accountRestrictions.address, + Address.createFromEncoded(accountRestrictionsInfoDTO.accountRestrictions.address), + ); + deepEqual( + accountRestrictionsInfo.accountRestrictions.restrictions.length, + accountRestrictionsInfoDTO.accountRestrictions.restrictions.length, + ); + deepEqual( + accountRestrictionsInfo.accountRestrictions.restrictions[0].values[0], + accountRestrictionsInfoDTO.accountRestrictions.restrictions[0].values[0], + ); }); }); diff --git a/test/model/restriction/MosaicRestriction.spec.ts b/test/model/restriction/MosaicRestriction.spec.ts index b2033df179..f07864e240 100644 --- a/test/model/restriction/MosaicRestriction.spec.ts +++ b/test/model/restriction/MosaicRestriction.spec.ts @@ -14,23 +14,17 @@ * limitations under the License. */ -import {expect} from 'chai'; -import { Account } from '../../../src/model/account/Account'; -import {Address} from '../../../src/model/account/Address'; +import { expect } from 'chai'; +import { Address } from '../../../src/model/account/Address'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { MosaicAddressRestriction } from '../../../src/model/restriction/MosaicAddressRestriction'; import { MosaicGlobalRestriction } from '../../../src/model/restriction/MosaicGlobalRestriction'; import { MosaicGlobalRestrictionItem } from '../../../src/model/restriction/MosaicGlobalRestrictionItem'; import { MosaicRestrictionEntryType } from '../../../src/model/restriction/MosaicRestrictionEntryType'; import { MosaicRestrictionType } from '../../../src/model/restriction/MosaicRestrictionType'; -import { TestingAccount } from '../../conf/conf.spec'; describe('MosaicRestrictions', () => { - let account: Account; const hash = '57F7DA205008026C776CB6AED843393F04CD458E0AA2D9F1D5F31A402072B2D6'; - before(() => { - account = TestingAccount; - }); it('should createComplete an MosaicAddressRestriction object', () => { const mosaicAddressRestrictionDTO = { @@ -38,10 +32,12 @@ describe('MosaicRestrictions', () => { entryType: 0, mosaicId: '85BBEA6CC462B244', targetAddress: '9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142', - restrictions: [{ - key: 'testKey', - value: 'testValue', - }], + restrictions: [ + { + key: 'testKey', + value: 'testValue', + }, + ], }; const mosaicAddressRestriction = new MosaicAddressRestriction( @@ -49,14 +45,17 @@ describe('MosaicRestrictions', () => { mosaicAddressRestrictionDTO.entryType, new MosaicId(mosaicAddressRestrictionDTO.mosaicId), Address.createFromEncoded(mosaicAddressRestrictionDTO.targetAddress), - new Map().set(mosaicAddressRestrictionDTO.restrictions[0].key, - mosaicAddressRestrictionDTO.restrictions[0].value), + new Map().set( + mosaicAddressRestrictionDTO.restrictions[0].key, + mosaicAddressRestrictionDTO.restrictions[0].value, + ), ); expect(mosaicAddressRestriction.compositeHash).to.be.equal(hash); expect(mosaicAddressRestriction.entryType).to.be.equal(MosaicRestrictionEntryType.ADDRESS); - expect(mosaicAddressRestriction.targetAddress.plain()) - .to.be.equal(Address.createFromEncoded('9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142').plain()); + expect(mosaicAddressRestriction.targetAddress.plain()).to.be.equal( + Address.createFromEncoded('9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142').plain(), + ); expect(mosaicAddressRestriction.restrictions.size).to.be.equal(1); expect(mosaicAddressRestriction.restrictions.get('testKey')).to.not.be.equal(undefined); }); @@ -84,14 +83,16 @@ describe('MosaicRestrictions', () => { compositeHash: hash, entryType: 0, mosaicId: '85BBEA6CC462B244', - restrictions: [{ - key: 'testKey', - restriction: { - referenceMosaicId: '85BBEA6CC462B244', - restrictionValue: '123', - restrictionType: 1, + restrictions: [ + { + key: 'testKey', + restriction: { + referenceMosaicId: '85BBEA6CC462B244', + restrictionValue: '123', + restrictionType: 1, + }, }, - }], + ], }; const mosaicGlobalRestriction = new MosaicGlobalRestriction( diff --git a/test/model/transaction/AccountLinkTransaction.spec.ts b/test/model/transaction/AccountLinkTransaction.spec.ts index 889d7a6e86..3aad7fb9eb 100644 --- a/test/model/transaction/AccountLinkTransaction.spec.ts +++ b/test/model/transaction/AccountLinkTransaction.spec.ts @@ -15,7 +15,7 @@ */ import { expect } from 'chai'; -import {Convert} from '../../../src/core/format'; +import { Convert } from '../../../src/core/format'; import { Account } from '../../../src/model/account/Account'; import { NetworkType } from '../../../src/model/network/NetworkType'; import { AccountLinkTransaction } from '../../../src/model/transaction/AccountLinkTransaction'; @@ -69,10 +69,9 @@ describe('AccountLinkTransaction', () => { const signedTransaction = accountLinkTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B601'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B601', + ); }); it('should create an AccountLinkTransaction object with unlink action', () => { @@ -88,10 +87,9 @@ describe('AccountLinkTransaction', () => { const signedTransaction = accountLinkTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B600'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B600', + ); }); describe('size', () => { @@ -114,7 +112,6 @@ describe('AccountLinkTransaction', () => { LinkAction.Unlink, NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(accountLinkTransaction.maxFee.compact()).to.be.equal(322); const signedTransaction = accountLinkTransaction.signWith(account, generationHash); diff --git a/test/model/transaction/AccountMetadataTransaction.spec.ts b/test/model/transaction/AccountMetadataTransaction.spec.ts index d9dda03acc..839669da0e 100644 --- a/test/model/transaction/AccountMetadataTransaction.spec.ts +++ b/test/model/transaction/AccountMetadataTransaction.spec.ts @@ -22,6 +22,9 @@ import { AccountMetadataTransaction } from '../../../src/model/transaction/Accou import { Deadline } from '../../../src/model/transaction/Deadline'; import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; +import { EmbeddedTransactionBuilder } from 'catbuffer-typescript/builders/EmbeddedTransactionBuilder'; +import { TransactionType } from '../../../src/model/transaction/TransactionType'; +import { deepEqual } from 'assert'; describe('AccountMetadataTransaction', () => { let account: Account; @@ -71,23 +74,9 @@ describe('AccountMetadataTransaction', () => { const signedTransaction = accountMetadataTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B6E80300000000000001000A0000000000000000000000'); - }); - - it('should throw error if value size is bigger than 1024', () => { - expect(() => { - AccountMetadataTransaction.create( - Deadline.create(), - account.publicKey, - UInt64.fromUint(1000), - 1, - Convert.uint8ToUtf8(new Uint8Array(1025)), - NetworkType.MIJIN_TEST, - ); - }).to.throw(Error, 'The maximum value size is 1024'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B6E80300000000000001000A0000000000000000000000', + ); }); describe('size', () => { @@ -108,4 +97,39 @@ describe('AccountMetadataTransaction', () => { expect(signedTransaction.hash).not.to.be.undefined; }); }); + + it('should create EmbeddedTransactionBuilder', () => { + const accountMetadataTransaction = AccountMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(1000), + 1, + Convert.uint8ToUtf8(new Uint8Array(10)), + NetworkType.MIJIN_TEST, + ); + + Object.assign(accountMetadataTransaction, { signer: account.publicAccount }); + + const embedded = accountMetadataTransaction.toEmbeddedTransaction(); + + expect(embedded).to.be.instanceOf(EmbeddedTransactionBuilder); + expect(Convert.uint8ToHex(embedded.signerPublicKey.key)).to.be.equal(account.publicKey); + expect(embedded.type.valueOf()).to.be.equal(TransactionType.ACCOUNT_METADATA.valueOf()); + }); + + it('should resolve alias', () => { + const accountMetadataTransaction = AccountMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(1000), + 1, + Convert.uint8ToUtf8(new Uint8Array(10)), + NetworkType.MIJIN_TEST, + ); + + const resolved = accountMetadataTransaction.resolveAliases(); + + expect(resolved).to.be.instanceOf(AccountMetadataTransaction); + deepEqual(accountMetadataTransaction, resolved); + }); }); diff --git a/test/model/transaction/AccountRestrictionTransaction.spec.ts b/test/model/transaction/AccountRestrictionTransaction.spec.ts index 461c078df6..94ed90c297 100644 --- a/test/model/transaction/AccountRestrictionTransaction.spec.ts +++ b/test/model/transaction/AccountRestrictionTransaction.spec.ts @@ -14,20 +14,20 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; -import {Address} from '../../../src/model/account/Address'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; +import { Address } from '../../../src/model/account/Address'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { AccountRestrictionModificationAction } from '../../../src/model/restriction/AccountRestrictionModificationAction'; import { AccountRestrictionFlags } from '../../../src/model/restriction/AccountRestrictionType'; import { AccountRestrictionModification } from '../../../src/model/transaction/AccountRestrictionModification'; -import {AccountRestrictionTransaction} from '../../../src/model/transaction/AccountRestrictionTransaction'; -import {Deadline} from '../../../src/model/transaction/Deadline'; +import { AccountRestrictionTransaction } from '../../../src/model/transaction/AccountRestrictionTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; import { TransactionType } from '../../../src/model/transaction/TransactionType'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('AccountRestrictionTransaction', () => { let account: Account; @@ -37,20 +37,14 @@ describe('AccountRestrictionTransaction', () => { }); it('should create address restriction filter', () => { const address = Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); - const addressRestrictionFilter = AccountRestrictionModification.createForAddress( - AccountRestrictionModificationAction.Add, - address, - ); + const addressRestrictionFilter = AccountRestrictionModification.createForAddress(AccountRestrictionModificationAction.Add, address); expect(addressRestrictionFilter.modificationAction).to.be.equal(AccountRestrictionModificationAction.Add); expect(addressRestrictionFilter.value).to.be.equal(address.plain()); }); it('should create mosaic restriction filter', () => { const mosaicId = new MosaicId([2262289484, 3405110546]); - const mosaicRestrictionFilter = AccountRestrictionModification.createForMosaic( - AccountRestrictionModificationAction.Add, - mosaicId, - ); + const mosaicRestrictionFilter = AccountRestrictionModification.createForMosaic(AccountRestrictionModificationAction.Add, mosaicId); expect(mosaicRestrictionFilter.modificationAction).to.be.equal(AccountRestrictionModificationAction.Add); expect(mosaicRestrictionFilter.value[0]).to.be.equal(mosaicId.id.lower); expect(mosaicRestrictionFilter.value[1]).to.be.equal(mosaicId.id.higher); @@ -136,7 +130,6 @@ describe('AccountRestrictionTransaction', () => { }); it('should create allow incmoing address restriction transaction', () => { - const address = Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); const addressRestrictionTransaction = AccountRestrictionTransaction.createAddressRestrictionModificationTransaction( Deadline.create(), @@ -148,23 +141,21 @@ describe('AccountRestrictionTransaction', () => { const signedTransaction = addressRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('01000100000000009050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '01000100000000009050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142', + ); }); it('should throw exception when create address restriction transaction with wrong type', () => { - const address = Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); - const invalidType = [AccountRestrictionFlags.AllowIncomingTransactionType, - AccountRestrictionFlags.AllowMosaic, - AccountRestrictionFlags.AllowOutgoingTransactionType, - AccountRestrictionFlags.BlockIncomingTransactionType, - AccountRestrictionFlags.BlockMosaic, - AccountRestrictionFlags.BlockOutgoingTransactionType, - ]; + const invalidType = [ + AccountRestrictionFlags.AllowIncomingTransactionType, + AccountRestrictionFlags.AllowMosaic, + AccountRestrictionFlags.AllowOutgoingTransactionType, + AccountRestrictionFlags.BlockIncomingTransactionType, + AccountRestrictionFlags.BlockMosaic, + AccountRestrictionFlags.BlockOutgoingTransactionType, + ]; invalidType.forEach((type) => { expect(() => { AccountRestrictionTransaction.createAddressRestrictionModificationTransaction( @@ -174,12 +165,11 @@ describe('AccountRestrictionTransaction', () => { [], NetworkType.MIJIN_TEST, ); - }).to.throw(Error, 'Restriction type is not allowed.'); + }).to.throw(Error, 'Restriction type is not allowed.'); }); }); it('should create mosaic restriction transaction', () => { - const mosaicId = new MosaicId([2262289484, 3405110546]); const mosaicRestrictionTransaction = AccountRestrictionTransaction.createMosaicRestrictionModificationTransaction( Deadline.create(), @@ -191,25 +181,21 @@ describe('AccountRestrictionTransaction', () => { const signedTransaction = mosaicRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('02000100000000004CCCD78612DDF5CA'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal('02000100000000004CCCD78612DDF5CA'); }); it('should throw exception when create account mosaic restriction transaction with wrong type', () => { - const mosaicId = new MosaicId([2262289484, 3405110546]); - const invalidType = [AccountRestrictionFlags.AllowIncomingTransactionType, - AccountRestrictionFlags.AllowIncomingAddress, - AccountRestrictionFlags.AllowOutgoingTransactionType, - AccountRestrictionFlags.BlockIncomingTransactionType, - AccountRestrictionFlags.AllowOutgoingAddress, - AccountRestrictionFlags.BlockOutgoingTransactionType, - AccountRestrictionFlags.BlockIncomingAddress, - AccountRestrictionFlags.BlockOutgoingAddress, - ]; + const invalidType = [ + AccountRestrictionFlags.AllowIncomingTransactionType, + AccountRestrictionFlags.AllowIncomingAddress, + AccountRestrictionFlags.AllowOutgoingTransactionType, + AccountRestrictionFlags.BlockIncomingTransactionType, + AccountRestrictionFlags.AllowOutgoingAddress, + AccountRestrictionFlags.BlockOutgoingTransactionType, + AccountRestrictionFlags.BlockIncomingAddress, + AccountRestrictionFlags.BlockOutgoingAddress, + ]; invalidType.forEach((type) => { expect(() => { AccountRestrictionTransaction.createMosaicRestrictionModificationTransaction( @@ -219,12 +205,11 @@ describe('AccountRestrictionTransaction', () => { [], NetworkType.MIJIN_TEST, ); - }).to.throw(Error, 'Restriction type is not allowed.'); + }).to.throw(Error, 'Restriction type is not allowed.'); }); }); it('should create operation restriction transaction', () => { - const operation = TransactionType.ADDRESS_ALIAS; const operationRestrictionTransaction = AccountRestrictionTransaction.createOperationRestrictionModificationTransaction( Deadline.create(), @@ -236,23 +221,19 @@ describe('AccountRestrictionTransaction', () => { const signedTransaction = operationRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('04000100000000004E42'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal('04000100000000004E42'); }); it('should throw exception when create account operation restriction transaction with wrong type', () => { - const operation = TransactionType.ADDRESS_ALIAS; - const invalidType = [AccountRestrictionFlags.AllowIncomingAddress, - AccountRestrictionFlags.AllowMosaic, - AccountRestrictionFlags.BlockMosaic, - AccountRestrictionFlags.AllowOutgoingAddress, - AccountRestrictionFlags.BlockIncomingAddress, - AccountRestrictionFlags.BlockOutgoingAddress, - ]; + const invalidType = [ + AccountRestrictionFlags.AllowIncomingAddress, + AccountRestrictionFlags.AllowMosaic, + AccountRestrictionFlags.BlockMosaic, + AccountRestrictionFlags.AllowOutgoingAddress, + AccountRestrictionFlags.BlockIncomingAddress, + AccountRestrictionFlags.BlockOutgoingAddress, + ]; invalidType.forEach((type) => { expect(() => { AccountRestrictionTransaction.createOperationRestrictionModificationTransaction( @@ -262,12 +243,11 @@ describe('AccountRestrictionTransaction', () => { [], NetworkType.MIJIN_TEST, ); - }).to.throw(Error, 'Restriction type is not allowed.'); + }).to.throw(Error, 'Restriction type is not allowed.'); }); }); it('should create outgoing address restriction transaction', () => { - const address = Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); let addressRestrictionTransaction = AccountRestrictionTransaction.createAddressRestrictionModificationTransaction( Deadline.create(), @@ -279,10 +259,9 @@ describe('AccountRestrictionTransaction', () => { let signedTransaction = addressRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('01400100000000009050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '01400100000000009050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142', + ); addressRestrictionTransaction = AccountRestrictionTransaction.createAddressRestrictionModificationTransaction( Deadline.create(), @@ -294,15 +273,12 @@ describe('AccountRestrictionTransaction', () => { signedTransaction = addressRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('01C00100000000009050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '01C00100000000009050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142', + ); }); it('should create outgoing operation restriction transaction', () => { - const operation = TransactionType.ADDRESS_ALIAS; let operationRestrictionTransaction = AccountRestrictionTransaction.createOperationRestrictionModificationTransaction( Deadline.create(), @@ -314,10 +290,7 @@ describe('AccountRestrictionTransaction', () => { let signedTransaction = operationRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('04400100000000004E42'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal('04400100000000004E42'); operationRestrictionTransaction = AccountRestrictionTransaction.createOperationRestrictionModificationTransaction( Deadline.create(), @@ -329,10 +302,6 @@ describe('AccountRestrictionTransaction', () => { signedTransaction = operationRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('04C00100000000004E42'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal('04C00100000000004E42'); }); }); diff --git a/test/model/transaction/AddressAliasTransaction.spec.ts b/test/model/transaction/AddressAliasTransaction.spec.ts index db8d7b954b..56042a59b8 100644 --- a/test/model/transaction/AddressAliasTransaction.spec.ts +++ b/test/model/transaction/AddressAliasTransaction.spec.ts @@ -14,18 +14,17 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; -import {Address} from '../../../src/model/account/Address'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {AliasAction} from '../../../src/model/namespace/AliasAction'; -import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {AddressAliasTransaction} from '../../../src/model/transaction/AddressAliasTransaction'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; +import { Address } from '../../../src/model/account/Address'; +import { AliasAction } from '../../../src/model/namespace/AliasAction'; +import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { AddressAliasTransaction } from '../../../src/model/transaction/AddressAliasTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('AddressAliasTransaction', () => { let account: Account; @@ -83,11 +82,9 @@ describe('AddressAliasTransaction', () => { const signedTransaction = addressAliasTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('2AD8FC018D9A49E19050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E14201'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '2AD8FC018D9A49E19050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E14201', + ); }); describe('size', () => { @@ -116,7 +113,6 @@ describe('AddressAliasTransaction', () => { address, NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(addressAliasTransaction.maxFee.compact()).to.be.equal(324); }); }); diff --git a/test/model/transaction/AggregateTransaction.spec.ts b/test/model/transaction/AggregateTransaction.spec.ts index 4c1c4f1fa4..0b587835eb 100644 --- a/test/model/transaction/AggregateTransaction.spec.ts +++ b/test/model/transaction/AggregateTransaction.spec.ts @@ -63,11 +63,18 @@ describe('AggregateTransaction', () => { }); before(() => { account = TestingAccount; - statement = new Statement([], - [new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, - [new ResolutionEntry(account.address, new ReceiptSource(1, 1))])], - [new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, - [new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 1))])], + statement = new Statement( + [], + [ + new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, [ + new ResolutionEntry(account.address, new ReceiptSource(1, 1)), + ]), + ], + [ + new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, [ + new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 1)), + ]), + ], ); }); @@ -125,14 +132,14 @@ describe('AggregateTransaction', () => { Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signWith(account, generationHash); expect(signedTransaction.payload.substring(0, 8)).to.be.equal('08010000'); - expect(signedTransaction.payload.substring( - 424, - signedTransaction.payload.length, - )).to.be.equal('019054419050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D657373616765000000'); + expect(signedTransaction.payload.substring(424, signedTransaction.payload.length)).to.be.equal( + '019054419050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D657373616765000000', + ); }); it('should createComplete an AggregateTransaction object with NamespaceRegistrationTransaction', () => { @@ -154,16 +161,15 @@ describe('AggregateTransaction', () => { expect(signedTransaction.payload.substring(0, 8)).to.be.equal('00010000'); expect(signedTransaction.payload.substring(320, 352)).to.be.equal('58000000000000005500000000000000'); - expect(signedTransaction.payload.substring( - 424, - signedTransaction.payload.length, - )).to.be.equal('01904E41E803000000000000CFCBE72D994BE69B0013726F6F742D746573742D6E616D657370616365000000'); + expect(signedTransaction.payload.substring(424, signedTransaction.payload.length)).to.be.equal( + '01904E41E803000000000000CFCBE72D994BE69B0013726F6F742D746573742D6E616D657370616365000000', + ); }); it('should createComplete an AggregateTransaction object with MosaicDefinitionTransaction', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(true, true, true), 3, @@ -182,10 +188,9 @@ describe('AggregateTransaction', () => { expect(signedTransaction.payload.substring(0, 8)).to.be.equal('F0000000'); expect(signedTransaction.payload.substring(320, 352)).to.be.equal('48000000000000004600000000000000'); - expect(signedTransaction.payload.substring( - 424, - signedTransaction.payload.length, - )).to.be.equal('01904D410100000000000000E803000000000000E6DE84B807030000'); + expect(signedTransaction.payload.substring(424, signedTransaction.payload.length)).to.be.equal( + '01904D410100000000000000E803000000000000E6DE84B807030000', + ); }); it('should createComplete an AggregateTransaction object with MosaicSupplyChangeTransaction', () => { @@ -209,10 +214,9 @@ describe('AggregateTransaction', () => { expect(signedTransaction.payload.substring(0, 8)).to.be.equal('F0000000'); expect(signedTransaction.payload.substring(320, 352)).to.be.equal('48000000000000004100000000000000'); - expect(signedTransaction.payload.substring( - 424, - signedTransaction.payload.length, - )).to.be.equal('01904D424CCCD78612DDF5CA0A000000000000000100000000000000'); + expect(signedTransaction.payload.substring(424, signedTransaction.payload.length)).to.be.equal( + '01904D424CCCD78612DDF5CA0A000000000000000100000000000000', + ); }); it('should createComplete an AggregateTransaction object with MultisigAccountModificationTransaction', () => { @@ -220,10 +224,15 @@ describe('AggregateTransaction', () => { Deadline.create(), 2, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST), - PublicAccount.createFromPublicKey('B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', - NetworkType.MIJIN_TEST), + [ + PublicAccount.createFromPublicKey( + 'B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', + NetworkType.MIJIN_TEST, + ), + PublicAccount.createFromPublicKey( + 'B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', + NetworkType.MIJIN_TEST, + ), ], [], NetworkType.MIJIN_TEST, @@ -239,11 +248,10 @@ describe('AggregateTransaction', () => { expect(signedTransaction.payload.substring(0, 8)).to.be.equal('20010000'); expect(signedTransaction.payload.substring(320, 352)).to.be.equal('78000000000000007800000000000000'); - expect(signedTransaction.payload.substring( - 424, - signedTransaction.payload.length, - )).to.be.equal('019055410102020000000000B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6' + - 'EC24B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4'); + expect(signedTransaction.payload.substring(424, signedTransaction.payload.length)).to.be.equal( + '019055410102020000000000B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6' + + 'EC24B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', + ); }); it('should createComplete an AggregateTransaction object with different cosignatories', () => { @@ -254,7 +262,8 @@ describe('AggregateTransaction', () => { PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); - const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), + const aggregateTransaction = AggregateTransaction.createComplete( + Deadline.create(), [transferTransaction.toAggregate(MultisigAccount.publicAccount)], NetworkType.MIJIN_TEST, [], @@ -267,12 +276,10 @@ describe('AggregateTransaction', () => { expect(signedTransaction.payload.substring(0, 8)).to.be.equal('68010000'); expect(signedTransaction.payload.substring(320, 352)).to.be.equal('60000000000000005D00000000000000'); - expect(signedTransaction.payload.substring( - 424, - 424 + 162, - )).to.be.equal('019054419050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573' + - '742D6D657373616765000000F9D6329A1A927F5D8918D3D313524CF179DE126AF8F0E83F0FBF2782B5'); - + expect(signedTransaction.payload.substring(424, 424 + 162)).to.be.equal( + '019054419050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573' + + '742D6D657373616765000000F9D6329A1A927F5D8918D3D313524CF179DE126AF8F0E83F0FBF2782B5', + ); }); it('should createBonded an AggregateTransaction object with TransferTransaction', () => { @@ -296,10 +303,9 @@ describe('AggregateTransaction', () => { expect(signedTransaction.payload.substring(0, 8)).to.be.equal('08010000'); expect(signedTransaction.payload.substring(320, 352)).to.be.equal('60000000000000005D00000000000000'); expect(signedTransaction.payload.substring(220, 224)).to.be.equal('4142'); - expect(signedTransaction.payload.substring( - 424, - signedTransaction.payload.length, - )).to.be.equal('019054419050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D657373616765000000'); + expect(signedTransaction.payload.substring(424, signedTransaction.payload.length)).to.be.equal( + '019054419050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D657373616765000000', + ); }); it('should validate if accounts have signed an aggregate transaction', () => { @@ -314,15 +320,17 @@ describe('AggregateTransaction', () => { transaction: { cosignatures: [ { - signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + - 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', + signature: + '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + - '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { @@ -338,8 +346,7 @@ describe('AggregateTransaction', () => { minRemovalDelta: 1, modifications: [ { - cosignatoryPublicKey: '589B73FBC22063E9AE6FBAC67CB9C6EA865EF556E5' + - 'FB8B7310D45F77C1250B97', + cosignatoryPublicKey: '589B73FBC22063E9AE6FBAC67CB9C6EA865EF556E5' + 'FB8B7310D45F77C1250B97', modificationAction: 0, }, ], @@ -356,41 +363,47 @@ describe('AggregateTransaction', () => { }, }; - const aggregateTransaction = CreateTransactionFromDTO( - aggregateTransactionDTO) as AggregateTransaction; - expect(aggregateTransaction.signedByAccount( - PublicAccount.createFromPublicKey('A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', - NetworkType.MIJIN_TEST))).to.be.equal(true); - expect(aggregateTransaction.signedByAccount( - PublicAccount.createFromPublicKey('7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', - NetworkType.MIJIN_TEST))).to.be.equal(true); - expect(aggregateTransaction.signedByAccount( - PublicAccount.createFromPublicKey('B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', - NetworkType.MIJIN_TEST))).to.be.equal(false); - - expect(aggregateTransaction.innerTransactions[0].signer!.publicKey) - .to.be.equal('B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF'); + const aggregateTransaction = CreateTransactionFromDTO(aggregateTransactionDTO) as AggregateTransaction; + expect( + aggregateTransaction.signedByAccount( + PublicAccount.createFromPublicKey( + 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', + NetworkType.MIJIN_TEST, + ), + ), + ).to.be.equal(true); + expect( + aggregateTransaction.signedByAccount( + PublicAccount.createFromPublicKey( + '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', + NetworkType.MIJIN_TEST, + ), + ), + ).to.be.equal(true); + expect( + aggregateTransaction.signedByAccount( + PublicAccount.createFromPublicKey( + 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', + NetworkType.MIJIN_TEST, + ), + ), + ).to.be.equal(false); + + expect(aggregateTransaction.innerTransactions[0].signer!.publicKey).to.be.equal( + 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', + ); expect(Convert.hexToUint8(aggregateTransaction.serialize()).length).to.be.equal(aggregateTransaction.size); }); - it('should have type 0x4141 when it\'s complete', () => { - const aggregateTransaction = AggregateTransaction.createComplete( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + it("should have type 0x4141 when it's complete", () => { + const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), [], NetworkType.MIJIN_TEST, []); expect(aggregateTransaction.type).to.be.equal(0x4141); }); - it('should have type 0x4241 when it\'s bonded', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - ); + it("should have type 0x4241 when it's bonded", () => { + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST); expect(aggregateTransaction.type).to.be.equal(0x4241); }); @@ -408,14 +421,16 @@ describe('AggregateTransaction', () => { Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); expect(() => { AggregateTransaction.createComplete( Deadline.create(), [aggregateTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); }).to.throw(Error, 'Inner transaction cannot be an aggregated transaction.'); }); @@ -427,21 +442,27 @@ describe('AggregateTransaction', () => { const accountBob = CosignatoryAccount; const accountCarol = Cosignatory2Account; - const AtoBTx = TransferTransaction.create(Deadline.create(), - accountBob.address, - [], - PlainMessage.create('a to b'), - NetworkType.MIJIN_TEST); - const BtoATx = TransferTransaction.create(Deadline.create(), - accountAlice.address, - [], - PlainMessage.create('b to a'), - NetworkType.MIJIN_TEST); - const CtoATx = TransferTransaction.create(Deadline.create(), - accountAlice.address, - [], - PlainMessage.create('c to a'), - NetworkType.MIJIN_TEST); + const AtoBTx = TransferTransaction.create( + Deadline.create(), + accountBob.address, + [], + PlainMessage.create('a to b'), + NetworkType.MIJIN_TEST, + ); + const BtoATx = TransferTransaction.create( + Deadline.create(), + accountAlice.address, + [], + PlainMessage.create('b to a'), + NetworkType.MIJIN_TEST, + ); + const CtoATx = TransferTransaction.create( + Deadline.create(), + accountAlice.address, + [], + PlainMessage.create('c to a'), + NetworkType.MIJIN_TEST, + ); // 01. Alice creates the aggregated tx and sign it, Then payload send to Bob & Carol const aggregateTransaction = AggregateTransaction.createComplete( @@ -449,7 +470,8 @@ describe('AggregateTransaction', () => { [ AtoBTx.toAggregate(accountAlice.publicAccount), BtoATx.toAggregate(accountBob.publicAccount), - CtoATx.toAggregate(accountCarol.publicAccount)], + CtoATx.toAggregate(accountCarol.publicAccount), + ], NetworkType.MIJIN_TEST, [], ); @@ -480,23 +502,30 @@ describe('AggregateTransaction', () => { expect(signedTransaction.payload.indexOf(accountCarol.publicKey) > -1).to.be.true; // To make sure that the new cosign method returns the same payload & hash as standard cosigning - const standardCosignedTransaction = aggregateTransaction - .signTransactionWithCosignatories(accountAlice, [accountBob, accountCarol], generationHash); + const standardCosignedTransaction = aggregateTransaction.signTransactionWithCosignatories( + accountAlice, + [accountBob, accountCarol], + generationHash, + ); expect(standardCosignedTransaction.payload).to.be.equal(signedTransaction.payload); expect(standardCosignedTransaction.hash).to.be.equal(signedTransaction.hash); }); it('Should be able to add innertransactions to current aggregate tx', () => { - const transferTx1 = TransferTransaction.create(Deadline.create(), - account.address, - [], - PlainMessage.create('a to b'), - NetworkType.MIJIN_TEST); - const transferTx2 = TransferTransaction.create(Deadline.create(), - account.address, - [], - PlainMessage.create('b to a'), - NetworkType.MIJIN_TEST); + const transferTx1 = TransferTransaction.create( + Deadline.create(), + account.address, + [], + PlainMessage.create('a to b'), + NetworkType.MIJIN_TEST, + ); + const transferTx2 = TransferTransaction.create( + Deadline.create(), + account.address, + [], + PlainMessage.create('b to a'), + NetworkType.MIJIN_TEST, + ); let aggregateTransaction = AggregateTransaction.createComplete( Deadline.create(), [transferTx1.toAggregate(account.publicAccount)], @@ -514,11 +543,13 @@ describe('AggregateTransaction', () => { }); it('Should be able to add cosignatures to current aggregate tx', () => { - const transferTx1 = TransferTransaction.create(Deadline.create(), - account.address, - [], - PlainMessage.create('a to b'), - NetworkType.MIJIN_TEST); + const transferTx1 = TransferTransaction.create( + Deadline.create(), + account.address, + [], + PlainMessage.create('a to b'), + NetworkType.MIJIN_TEST, + ); let aggregateTransaction = AggregateTransaction.createComplete( Deadline.create(), [transferTx1.toAggregate(account.publicAccount)], @@ -547,9 +578,7 @@ describe('AggregateTransaction', () => { const transaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('NEM'), NetworkType.MIJIN_TEST, ); @@ -578,14 +607,32 @@ describe('AggregateTransaction', () => { [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, [], - ).setMaxFee(2); -​ - expect(aggregateTransaction.maxFee.compact()).to.be.equal(560); + ).setMaxFeeForAggregate(2, 10); + expect(aggregateTransaction.maxFee.compact()).to.be.equal(560 + 960 * 2); const signedTransaction = aggregateTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; }); + it('Test set maxFee using multiplier', () => { + const transferTransaction = TransferTransaction.create( + Deadline.create(1, ChronoUnit.HOURS), + unresolvedAddress, + [new Mosaic(unresolvedMosaicId, UInt64.fromUint(1))], + PlainMessage.create('test-message'), + NetworkType.MIJIN_TEST, + ); + + expect(() => { + AggregateTransaction.createComplete( + Deadline.create(), + [transferTransaction.toAggregate(account.publicAccount)], + NetworkType.MIJIN_TEST, + [], + ).setMaxFee(2); + }).to.throw(); + }); + it('Test resolveAlias can resolve', () => { const transferTransaction = new TransferTransaction( NetworkType.MIJIN_TEST, @@ -597,7 +644,8 @@ describe('AggregateTransaction', () => { PlainMessage.create('test'), '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')); + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ); const aggregateTransaction = new AggregateTransaction( NetworkType.MIJIN_TEST, @@ -609,8 +657,8 @@ describe('AggregateTransaction', () => { [], '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); const innerTransaction = aggregateTransaction.innerTransactions[0] as TransferTransaction; expect(innerTransaction.recipientAddress instanceof Address).to.be.true; expect(innerTransaction.mosaics[0].id instanceof MosaicId).to.be.true; diff --git a/test/model/transaction/CosignatureTransaction.spec.ts b/test/model/transaction/CosignatureTransaction.spec.ts index 1c5555559e..5dcdc6f501 100644 --- a/test/model/transaction/CosignatureTransaction.spec.ts +++ b/test/model/transaction/CosignatureTransaction.spec.ts @@ -14,16 +14,16 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {CreateTransactionFromDTO} from '../../../src/infrastructure/transaction/CreateTransactionFromDTO'; -import {Account} from '../../../src/model/account/Account'; +import { expect } from 'chai'; +import { CreateTransactionFromDTO } from '../../../src/infrastructure/transaction/CreateTransactionFromDTO'; +import { Account } from '../../../src/model/account/Account'; import { PlainMessage } from '../../../src/model/message/PlainMessage'; import { NetworkType } from '../../../src/model/network/NetworkType'; -import {AggregateTransaction} from '../../../src/model/transaction/AggregateTransaction'; -import {CosignatureTransaction} from '../../../src/model/transaction/CosignatureTransaction'; +import { AggregateTransaction } from '../../../src/model/transaction/AggregateTransaction'; +import { CosignatureTransaction } from '../../../src/model/transaction/CosignatureTransaction'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { TransferTransaction } from '../../../src/model/transaction/TransferTransaction'; -import {TestingAccount} from '../../conf/conf.spec'; +import { TestingAccount } from '../../conf/conf.spec'; describe('CosignatureTransaction', () => { let account: Account; @@ -33,7 +33,6 @@ describe('CosignatureTransaction', () => { }); it('should createComplete an TransferTransaction object and sign it', () => { - const aggregateTransferTransactionDTO = { meta: { hash: '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96', @@ -45,15 +44,17 @@ describe('CosignatureTransaction', () => { transaction: { cosignatures: [ { - signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + - 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', + signature: + '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', - signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + - '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', + signature: + '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { @@ -94,17 +95,21 @@ describe('CosignatureTransaction', () => { const cosignatureSignedTransaction = account.signCosignatureTransaction(cosignatureTransaction); expect(cosignatureSignedTransaction.parentHash).to.be.equal(aggregateTransferTransaction.transactionInfo!.hash); - expect(cosignatureSignedTransaction.signature).to.be.equal('5EA75D1A2C8AD25DA4F400C1BD2DA84449FAF583AFD813E' + - '1179E72AF0CDF5AC1C0F7404AF6FC7268EE416204240DD3D5B11420D80215F19AA314FC86D6E03E0D'); + expect(cosignatureSignedTransaction.signature).to.be.equal( + '5EA75D1A2C8AD25DA4F400C1BD2DA84449FAF583AFD813E' + + '1179E72AF0CDF5AC1C0F7404AF6FC7268EE416204240DD3D5B11420D80215F19AA314FC86D6E03E0D', + ); expect(cosignatureSignedTransaction.signerPublicKey).to.be.equal(account.publicKey); }); it('should sign a transaction with transaction payload', () => { - const txPayload = TransferTransaction.create(Deadline.create(), - account.address, - [], - PlainMessage.create('a to b'), - NetworkType.MIJIN_TEST).serialize(); + const txPayload = TransferTransaction.create( + Deadline.create(), + account.address, + [], + PlainMessage.create('a to b'), + NetworkType.MIJIN_TEST, + ).serialize(); const signedTx = CosignatureTransaction.signTransactionPayload(account, txPayload, generationHash); diff --git a/test/model/transaction/Deadline.spec.ts b/test/model/transaction/Deadline.spec.ts index 74620cff8d..655045a7e6 100644 --- a/test/model/transaction/Deadline.spec.ts +++ b/test/model/transaction/Deadline.spec.ts @@ -14,16 +14,16 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {ChronoUnit, Instant, LocalDateTime, ZoneId} from 'js-joda'; -import {Deadline} from '../../../src/model/transaction/Deadline'; +import { expect } from 'chai'; +import { ChronoUnit, Instant, LocalDateTime, ZoneId } from 'js-joda'; +import { Deadline } from '../../../src/model/transaction/Deadline'; describe('Deadline', () => { it('should createComplete timestamp today', () => { const deadline = Deadline.create(); // avoid SYSTEM and UTC differences - const networkTimeStamp = (new Date()).getTime(); + const networkTimeStamp = new Date().getTime(); const timestampLocal = LocalDateTime.ofInstant(Instant.ofEpochMilli(networkTimeStamp), ZoneId.SYSTEM); const reproducedDate = timestampLocal.plus(2, ChronoUnit.HOURS); diff --git a/test/model/transaction/HashLockTransaction.spec.ts b/test/model/transaction/HashLockTransaction.spec.ts index 9b5682dfa3..54e137ab54 100644 --- a/test/model/transaction/HashLockTransaction.spec.ts +++ b/test/model/transaction/HashLockTransaction.spec.ts @@ -13,32 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyLocal'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {AggregateTransaction} from '../../../src/model/transaction/AggregateTransaction'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {HashLockTransaction} from '../../../src/model/transaction/HashLockTransaction'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { AggregateTransaction } from '../../../src/model/transaction/AggregateTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { HashLockTransaction } from '../../../src/model/transaction/HashLockTransaction'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('HashLockTransaction', () => { const account = TestingAccount; const generationHash = '57F7DA205008026C776CB6AED843393F04CD458E0AA2D9F1D5F31A402072B2D6'; it('creation with an aggregate bonded tx', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const transaction = HashLockTransaction.create(Deadline.create(), + const transaction = HashLockTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, + ); expect(transaction.mosaic.id).to.be.equal(NetworkCurrencyLocal.NAMESPACE_ID); expect(transaction.mosaic.amount.compact()).to.be.equal(10000000); expect(transaction.hash).to.be.equal(signedTransaction.hash); @@ -46,19 +43,16 @@ describe('HashLockTransaction', () => { }); it('should throw exception if it is not a aggregate bonded tx', () => { - const aggregateTransaction = AggregateTransaction.createComplete( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); expect(() => { - HashLockTransaction.create(Deadline.create(), + HashLockTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, + ); }).to.throw(Error); }); }); diff --git a/test/model/transaction/HashTypeLengthValidator.spec.ts b/test/model/transaction/HashTypeLengthValidator.spec.ts index 14cef84c9c..d56a2f6b8d 100644 --- a/test/model/transaction/HashTypeLengthValidator.spec.ts +++ b/test/model/transaction/HashTypeLengthValidator.spec.ts @@ -1,5 +1,5 @@ /* - * Copyright 2018 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,67 +13,72 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import * as CryptoJS from 'crypto-js'; -import {keccak_256, sha3_256, sha3_512} from 'js-sha3'; -import {HashType, HashTypeLengthValidator} from '../../../src/model/transaction/HashType'; +import { expect } from 'chai'; +import { sha3_256, sha3_512 } from 'js-sha3'; +import { LockHashAlgorithm, LockHashAlgorithmLengthValidator } from '../../../src/model/transaction/LockHashAlgorithm'; -describe('HashTypeLengthValidator', () => { - it('HashType.SHA3_256 should be exactly 64 chars length', () => { - expect(HashTypeLengthValidator(HashType.Op_Sha3_256, sha3_256.create().update('abcxyz').hex())).to.be.equal(true); - }); - - it('HashType.SHA3_256 should return false if it is not 64 chars length', () => { - expect(HashTypeLengthValidator(HashType.Op_Sha3_256, sha3_512.create().update('abcxyz').hex())).to.be.equal(false); - }); - - it('HashType.SHA_256 should return false if it is not a hash valid', () => { - const invalidHash = 'zyz6053bb910a6027f138ac5ebe92d43a9a18b7239b3c4d5ea69f1632e50aeef28184e46cd22ded096b76631858' + - '0a569e74521a9d63885cc8d5e8644793be928'; - expect(HashTypeLengthValidator(HashType.Op_Sha3_256, invalidHash)).to.be.equal(false); - }); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const CryptoJS = require('crypto-js'); - it('HashType.Keccak_256 should be exactly 64 chars length', () => { - expect(HashTypeLengthValidator(HashType.Op_Keccak_256, keccak_256.create().update('abcxyz').hex())).to.be.equal(true); +describe('LockHashAlgorithmLengthValidator', () => { + it('LockHashAlgorithm.SHA3_256 should be exactly 64 chars length', () => { + expect(LockHashAlgorithmLengthValidator(LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update('abcxyz').hex())).to.be.equal(true); }); - it('HashType.Keccak_256 should return false if it is not 64 chars length', () => { - expect(HashTypeLengthValidator(HashType.Op_Keccak_256, sha3_512.create().update('abcxyz').toString())).to.be.equal(false); + it('LockHashAlgorithm.SHA3_256 should return false if it is not 64 chars length', () => { + expect(LockHashAlgorithmLengthValidator(LockHashAlgorithm.Op_Sha3_256, sha3_512.create().update('abcxyz').hex())).to.be.equal( + false, + ); }); - it('HashType.Keccak_256 should return false if it is not a hash valid', () => { - const invalidHash = 'zyz6053bb910a6027f138ac5ebe92d43a9a18b7239b3c4d5ea69f1632e50aeef28184e46cd22ded096b76631858' + + it('LockHashAlgorithm.SHA_256 should return false if it is not a hash valid', () => { + const invalidHash = + 'zyz6053bb910a6027f138ac5ebe92d43a9a18b7239b3c4d5ea69f1632e50aeef28184e46cd22ded096b76631858' + '0a569e74521a9d63885cc8d5e8644793be928'; - expect(HashTypeLengthValidator(HashType.Op_Keccak_256, invalidHash)).to.be.equal(false); + expect(LockHashAlgorithmLengthValidator(LockHashAlgorithm.Op_Sha3_256, invalidHash)).to.be.equal(false); }); - it('HashType.Op_Hash_256 should be exactly 64 chars length', () => { - // tslint:disable-next-line:max-line-length - expect(HashTypeLengthValidator(HashType.Op_Hash_256, CryptoJS.SHA256(CryptoJS.SHA256('abcxyz').toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex))).to.be.equal(true); + it('LockHashAlgorithm.Op_Hash_256 should be exactly 64 chars length', () => { + expect( + LockHashAlgorithmLengthValidator( + LockHashAlgorithm.Op_Hash_256, + CryptoJS.SHA256(CryptoJS.SHA256('abcxyz').toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex), + ), + ).to.be.equal(true); }); - it('HashType.Op_Hash_256 should return false if it is not 64 chars length', () => { - expect(HashTypeLengthValidator(HashType.Op_Hash_256, sha3_512.create().update('abcxyz').toString())).to.be.equal(false); + it('LockHashAlgorithm.Op_Hash_256 should return false if it is not 64 chars length', () => { + expect(LockHashAlgorithmLengthValidator(LockHashAlgorithm.Op_Hash_256, sha3_512.create().update('abcxyz').toString())).to.be.equal( + false, + ); }); - it('HashType.Op_Hash_256 should return false if it is not a hash valid', () => { - const invalidHash = 'zyz6053bb910a6027f138ac5ebe92d43a9a18b7239b3c4d5ea69f1632e50aeef28184e46cd22ded096b76631858' + + it('LockHashAlgorithm.Op_Hash_256 should return false if it is not a hash valid', () => { + const invalidHash = + 'zyz6053bb910a6027f138ac5ebe92d43a9a18b7239b3c4d5ea69f1632e50aeef28184e46cd22ded096b76631858' + '0a569e74521a9d63885cc8d5e8644793be928'; - expect(HashTypeLengthValidator(HashType.Op_Hash_256, invalidHash)).to.be.equal(false); + expect(LockHashAlgorithmLengthValidator(LockHashAlgorithm.Op_Hash_256, invalidHash)).to.be.equal(false); }); - it('HashType.Op_Hash_160 should be exactly 40 chars length', () => { - // tslint:disable-next-line:max-line-length - expect(HashTypeLengthValidator(HashType.Op_Hash_160, CryptoJS.RIPEMD160(CryptoJS.SHA256('abcxyz').toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex))).to.be.equal(true); + it('LockHashAlgorithm.Op_Hash_160 should be exactly 40 chars length', () => { + expect( + LockHashAlgorithmLengthValidator( + LockHashAlgorithm.Op_Hash_160, + CryptoJS.RIPEMD160(CryptoJS.SHA256('abcxyz').toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex), + ), + ).to.be.equal(true); }); - it('HashType.Op_Hash_160 should return false if it is not 64 chars length', () => { - expect(HashTypeLengthValidator(HashType.Op_Hash_160, sha3_512.create().update('abcxyz').toString())).to.be.equal(false); + it('LockHashAlgorithm.Op_Hash_160 should return false if it is not 64 chars length', () => { + expect(LockHashAlgorithmLengthValidator(LockHashAlgorithm.Op_Hash_160, sha3_512.create().update('abcxyz').toString())).to.be.equal( + false, + ); }); - it('HashType.Op_Hash_160 should return false if it is not a hash valid', () => { - const invalidHash = 'zyz6053bb910a6027f138ac5ebe92d43a9a18b7239b3c4d5ea69f1632e50aeef28184e46cd22ded096b76631858' + + it('LockHashAlgorithm.Op_Hash_160 should return false if it is not a hash valid', () => { + const invalidHash = + 'zyz6053bb910a6027f138ac5ebe92d43a9a18b7239b3c4d5ea69f1632e50aeef28184e46cd22ded096b76631858' + '0a569e74521a9d63885cc8d5e8644793be928'; - expect(HashTypeLengthValidator(HashType.Op_Hash_160, invalidHash)).to.be.equal(false); + expect(LockHashAlgorithmLengthValidator(LockHashAlgorithm.Op_Hash_160, invalidHash)).to.be.equal(false); }); }); diff --git a/test/model/transaction/LockFundsTransaction.spec.ts b/test/model/transaction/LockFundsTransaction.spec.ts index cf2a8a9cba..b8596da01d 100644 --- a/test/model/transaction/LockFundsTransaction.spec.ts +++ b/test/model/transaction/LockFundsTransaction.spec.ts @@ -13,26 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; import { Mosaic } from '../../../src/model/mosaic/Mosaic'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; -import {NetworkCurrencyLocal} from '../../../src/model/mosaic/NetworkCurrencyLocal'; +import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; import { ResolutionType } from '../../../src/model/receipt/ResolutionType'; import { Statement } from '../../../src/model/receipt/Statement'; -import {AggregateTransaction} from '../../../src/model/transaction/AggregateTransaction'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {LockFundsTransaction} from '../../../src/model/transaction/LockFundsTransaction'; +import { AggregateTransaction } from '../../../src/model/transaction/AggregateTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { LockFundsTransaction } from '../../../src/model/transaction/LockFundsTransaction'; import { TransactionInfo } from '../../../src/model/transaction/TransactionInfo'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('LockFundsTransaction', () => { let account: Account; @@ -42,22 +42,22 @@ describe('LockFundsTransaction', () => { const resolvedMosaicId = new MosaicId('0DC67FBE1CAD29E5'); before(() => { account = TestingAccount; - statement = new Statement([], + statement = new Statement( [], - [new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, - [new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0))])], + [], + [ + new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, [ + new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0)), + ]), + ], ); }); it('should default maxFee field be set to 0', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockFundsTransaction = LockFundsTransaction.create(Deadline.create(), + const lockFundsTransaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, @@ -70,14 +70,10 @@ describe('LockFundsTransaction', () => { }); it('should filled maxFee override transaction maxFee', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockFundsTransaction = LockFundsTransaction.create(Deadline.create(), + const lockFundsTransaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, @@ -90,49 +86,39 @@ describe('LockFundsTransaction', () => { }); it('creation with an aggregate bonded tx', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const transaction = LockFundsTransaction.create(Deadline.create(), + const transaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, + ); deepEqual(transaction.mosaic.id.id, NetworkCurrencyLocal.NAMESPACE_ID.id); expect(transaction.mosaic.amount.compact()).to.be.equal(10000000); expect(transaction.hash).to.be.equal(signedTransaction.hash); }); it('should throw exception if it is not a aggregate bonded tx', () => { - const aggregateTransaction = AggregateTransaction.createComplete( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createComplete(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); expect(() => { - LockFundsTransaction.create(Deadline.create(), + LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, + ); }).to.throw(Error); }); it('should create and sign LockFundsTransaction', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockFundsTransaction = LockFundsTransaction.create(Deadline.create(), + const lockFundsTransaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, @@ -140,22 +126,17 @@ describe('LockFundsTransaction', () => { ); const signedTx = lockFundsTransaction.signWith(account, generationHash); - expect(signedTx.payload.substring( - 144, - signedTransaction.payload.length - 104, - )).to.be.equal('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B6000000000190484100000000'); + expect(signedTx.payload.substring(144, signedTransaction.payload.length - 104)).to.be.equal( + '9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8787B6000000000190484100000000', + ); }); describe('size', () => { it('should return 184 for LockFundsTransaction transaction byte size', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockFundsTransaction = LockFundsTransaction.create(Deadline.create(), + const lockFundsTransaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, @@ -166,20 +147,15 @@ describe('LockFundsTransaction', () => { }); it('Test set maxFee using multiplier', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); - const lockFundsTransaction = LockFundsTransaction.create(Deadline.create(), + const lockFundsTransaction = LockFundsTransaction.create( + Deadline.create(), NetworkCurrencyLocal.createRelative(10), UInt64.fromUint(10), signedTransaction, NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(lockFundsTransaction.maxFee.compact()).to.be.equal(368); const signedTransactionTest = lockFundsTransaction.signWith(account, generationHash); @@ -187,12 +163,7 @@ describe('LockFundsTransaction', () => { }); it('Test resolveAlias can resolve', () => { - const aggregateTransaction = AggregateTransaction.createBonded( - Deadline.create(), - [], - NetworkType.MIJIN_TEST, - [], - ); + const aggregateTransaction = AggregateTransaction.createBonded(Deadline.create(), [], NetworkType.MIJIN_TEST, []); const signedTransaction = account.sign(aggregateTransaction, generationHash); const transaction = new LockFundsTransaction( NetworkType.MIJIN_TEST, @@ -204,8 +175,8 @@ describe('LockFundsTransaction', () => { signedTransaction, '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); expect(transaction.mosaic.id instanceof MosaicId).to.be.true; expect((transaction.mosaic.id as MosaicId).equals(resolvedMosaicId)).to.be.true; diff --git a/test/model/transaction/MosaicAddressRestrictionTransaction.spec.ts b/test/model/transaction/MosaicAddressRestrictionTransaction.spec.ts index 5aceec8548..3bca4254f6 100644 --- a/test/model/transaction/MosaicAddressRestrictionTransaction.spec.ts +++ b/test/model/transaction/MosaicAddressRestrictionTransaction.spec.ts @@ -14,23 +14,23 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; import { ResolutionType } from '../../../src/model/receipt/ResolutionType'; import { Statement } from '../../../src/model/receipt/Statement'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {MosaicAddressRestrictionTransaction} from '../../../src/model/transaction/MosaicAddressRestrictionTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { MosaicAddressRestrictionTransaction } from '../../../src/model/transaction/MosaicAddressRestrictionTransaction'; import { TransactionInfo } from '../../../src/model/transaction/TransactionInfo'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('MosaicAddressRestrictionTransaction', () => { let account: Account; @@ -41,11 +41,18 @@ describe('MosaicAddressRestrictionTransaction', () => { const resolvedMosaicId = new MosaicId('0DC67FBE1CAD29E5'); before(() => { account = TestingAccount; - statement = new Statement([], - [new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, - [new ResolutionEntry(account.address, new ReceiptSource(1, 0))])], - [new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, - [new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0))])], + statement = new Statement( + [], + [ + new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, [ + new ResolutionEntry(account.address, new ReceiptSource(1, 0)), + ]), + ], + [ + new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, [ + new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0)), + ]), + ], ); }); @@ -68,11 +75,9 @@ describe('MosaicAddressRestrictionTransaction', () => { const signedTransaction = mosaicAddressRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('010000000000000001000000000000000900000000000000080' + - '000000000000090D66C33420E5411995BACFCA2B28CF1C9F5DD7AB1204EA451'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '010000000000000001000000000000000900000000000000080' + '000000000000090D66C33420E5411995BACFCA2B28CF1C9F5DD7AB1204EA451', + ); }); it('should createComplete an MosaicAddressRestrictionTransaction use mosaic alias', () => { @@ -94,11 +99,9 @@ describe('MosaicAddressRestrictionTransaction', () => { const signedTransaction = mosaicAddressRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('C51FB4C93FCA509501000000000000000900000000000000080000000000' + - '000090D66C33420E5411995BACFCA2B28CF1C9F5DD7AB1204EA451'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + 'C51FB4C93FCA509501000000000000000900000000000000080000000000' + '000090D66C33420E5411995BACFCA2B28CF1C9F5DD7AB1204EA451', + ); }); it('should createComplete an MosaicAddressRestrictionTransaction use address alias', () => { @@ -121,11 +124,9 @@ describe('MosaicAddressRestrictionTransaction', () => { const signedTransaction = mosaicAddressRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('01000000000000000100000000000000090000000000000008000000000' + - '0000091C51FB4C93FCA509500000000000000000000000000000000'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '01000000000000000100000000000000090000000000000008000000000' + '0000091C51FB4C93FCA509500000000000000000000000000000000', + ); }); it('should format targetAddress payload with 8 bytes binary namespaceId - targetAddressToString', () => { @@ -144,10 +145,7 @@ describe('MosaicAddressRestrictionTransaction', () => { const signedTransaction = transaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - 304, - )).to.be.equal('010000000000000001000000000000000900000000000000'); + expect(signedTransaction.payload.substring(256, 304)).to.be.equal('010000000000000001000000000000000900000000000000'); expect(Convert.hexToUint8(transaction.serialize()).length).to.be.equal(transaction.size); }); @@ -162,7 +160,6 @@ describe('MosaicAddressRestrictionTransaction', () => { NetworkType.MIJIN_TEST, UInt64.fromUint(9), ).setMaxFee(2); -​ expect(transaction.maxFee.compact()).to.be.equal(370); const signedTransaction = transaction.signWith(account, generationHash); @@ -182,8 +179,8 @@ describe('MosaicAddressRestrictionTransaction', () => { UInt64.fromUint(9), '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); expect(transaction.targetAddress instanceof Address).to.be.true; expect(transaction.mosaicId instanceof MosaicId).to.be.true; expect((transaction.targetAddress as Address).equals(account.address)).to.be.true; diff --git a/test/model/transaction/MosaicAliasTransaction.spec.ts b/test/model/transaction/MosaicAliasTransaction.spec.ts index e8cf306a03..745ab77ed9 100644 --- a/test/model/transaction/MosaicAliasTransaction.spec.ts +++ b/test/model/transaction/MosaicAliasTransaction.spec.ts @@ -14,17 +14,20 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {AliasAction} from '../../../src/model/namespace/AliasAction'; -import {NamespaceId} from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {MosaicAliasTransaction} from '../../../src/model/transaction/MosaicAliasTransaction'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { AliasAction } from '../../../src/model/namespace/AliasAction'; +import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { MosaicAliasTransaction } from '../../../src/model/transaction/MosaicAliasTransaction'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; +import { deepEqual } from 'assert'; +import { EmbeddedTransactionBuilder } from 'catbuffer-typescript/builders/EmbeddedTransactionBuilder'; +import { TransactionType } from '../../../src/model/transaction/TransactionType'; describe('MosaicAliasTransaction', () => { let account: Account; @@ -83,11 +86,9 @@ describe('MosaicAliasTransaction', () => { const signedTransaction = mosaicAliasTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('2AD8FC018D9A49E14CCCD78612DDF5CA01'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '2AD8FC018D9A49E14CCCD78612DDF5CA01', + ); }); describe('size', () => { @@ -116,10 +117,43 @@ describe('MosaicAliasTransaction', () => { mosaicId, NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(mosaicAliasTransaction.maxFee.compact()).to.be.equal(290); const signedTransaction = mosaicAliasTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; }); + + it('Test resolveAlias can resolve', () => { + const namespaceId = new NamespaceId([33347626, 3779697293]); + const mosaicId = new MosaicId([2262289484, 3405110546]); + const mosaicAliasTransaction = MosaicAliasTransaction.create( + Deadline.create(), + AliasAction.Link, + namespaceId, + mosaicId, + NetworkType.MIJIN_TEST, + ); + const resolved = mosaicAliasTransaction.resolveAliases(); + deepEqual(mosaicAliasTransaction, resolved); + }); + + it('should create EmbeddedTransactionBuilder', () => { + const namespaceId = new NamespaceId([33347626, 3779697293]); + const mosaicId = new MosaicId([2262289484, 3405110546]); + const mosaicAliasTransaction = MosaicAliasTransaction.create( + Deadline.create(), + AliasAction.Link, + namespaceId, + mosaicId, + NetworkType.MIJIN_TEST, + ); + + Object.assign(mosaicAliasTransaction, { signer: account.publicAccount }); + + const embedded = mosaicAliasTransaction.toEmbeddedTransaction(); + + expect(embedded).to.be.instanceOf(EmbeddedTransactionBuilder); + expect(Convert.uint8ToHex(embedded.signerPublicKey.key)).to.be.equal(account.publicKey); + expect(embedded.type.valueOf()).to.be.equal(TransactionType.MOSAIC_ALIAS.valueOf()); + }); }); diff --git a/test/model/transaction/MosaicDefinitionTransaction.spec.ts b/test/model/transaction/MosaicDefinitionTransaction.spec.ts index 1529e2c211..c368a8cddf 100644 --- a/test/model/transaction/MosaicDefinitionTransaction.spec.ts +++ b/test/model/transaction/MosaicDefinitionTransaction.spec.ts @@ -36,7 +36,7 @@ describe('MosaicDefinitionTransaction', () => { it('should default maxFee field be set to 0', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(true, true, true), 3, @@ -51,7 +51,7 @@ describe('MosaicDefinitionTransaction', () => { it('should filled maxFee override transaction maxFee', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(true, true, true), 3, @@ -67,7 +67,7 @@ describe('MosaicDefinitionTransaction', () => { it('should createComplete an MosaicDefinitionTransaction object and sign it with flags 7', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(true, true, true), 3, @@ -84,18 +84,15 @@ describe('MosaicDefinitionTransaction', () => { const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('0100000000000000E803000000000000E6DE84B80703'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '0100000000000000E803000000000000E6DE84B80703', + ); }); it('should createComplete an MosaicDefinitionTransaction object and sign it with flags 0', () => { - const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, @@ -112,18 +109,16 @@ describe('MosaicDefinitionTransaction', () => { const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('0100000000000000E803000000000000E6DE84B80003'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '0100000000000000E803000000000000E6DE84B80003', + ); }); describe('size', () => { it('should return 150 for MosaicDefinition transaction byte size', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(true, true, false), 3, @@ -136,10 +131,9 @@ describe('MosaicDefinitionTransaction', () => { }); it('should createComplete an MosaicDefinitionTransaction object and sign it without duration', () => { - const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, @@ -154,23 +148,21 @@ describe('MosaicDefinitionTransaction', () => { const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('01000000000000000000000000000000E6DE84B80003'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '01000000000000000000000000000000E6DE84B80003', + ); }); it('Test set maxFee using multiplier', () => { const mosaicDefinitionTransaction = MosaicDefinitionTransaction.create( Deadline.create(), - MosaicNonce.createFromUint8Array(new Uint8Array([0xE6, 0xDE, 0x84, 0xB8])), // nonce + MosaicNonce.createFromUint8Array(new Uint8Array([0xe6, 0xde, 0x84, 0xb8])), // nonce new MosaicId(UInt64.fromUint(1).toDTO()), // ID MosaicFlags.create(false, false, false), 3, UInt64.fromUint(0), NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(mosaicDefinitionTransaction.maxFee.compact()).to.be.equal(300); const signedTransaction = mosaicDefinitionTransaction.signWith(account, generationHash); diff --git a/test/model/transaction/MosaicGlobalRestrictionTransaction.spec.ts b/test/model/transaction/MosaicGlobalRestrictionTransaction.spec.ts index fe733553fe..05c1b57dcc 100644 --- a/test/model/transaction/MosaicGlobalRestrictionTransaction.spec.ts +++ b/test/model/transaction/MosaicGlobalRestrictionTransaction.spec.ts @@ -14,23 +14,23 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; import { ResolutionType } from '../../../src/model/receipt/ResolutionType'; import { Statement } from '../../../src/model/receipt/Statement'; import { MosaicRestrictionType } from '../../../src/model/restriction/MosaicRestrictionType'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {MosaicGlobalRestrictionTransaction} from '../../../src/model/transaction/MosaicGlobalRestrictionTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { MosaicGlobalRestrictionTransaction } from '../../../src/model/transaction/MosaicGlobalRestrictionTransaction'; import { TransactionInfo } from '../../../src/model/transaction/TransactionInfo'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('MosaicGlobalRestrictionTransaction', () => { let account: Account; @@ -40,10 +40,14 @@ describe('MosaicGlobalRestrictionTransaction', () => { const resolvedMosaicId = new MosaicId('0DC67FBE1CAD29E5'); before(() => { account = TestingAccount; - statement = new Statement([], + statement = new Statement( [], - [new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, - [new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0))])], + [], + [ + new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, [ + new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0)), + ]), + ], ); }); @@ -72,11 +76,9 @@ describe('MosaicGlobalRestrictionTransaction', () => { const signedTransaction = mosaicGlobalRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('010000000000000002000000000000000100000000000000090000000000000008000000000000000106'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '010000000000000002000000000000000100000000000000090000000000000008000000000000000106', + ); }); it('should createComplete an MosaicGlobalRestrictionTransaction use mosaic alias', () => { @@ -104,14 +106,13 @@ describe('MosaicGlobalRestrictionTransaction', () => { const signedTransaction = mosaicGlobalRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('C51FB4C93FCA509502000000000000000100000000000000090000000000000008000000000000000106'); - - expect(Convert.hexToUint8(mosaicGlobalRestrictionTransaction.serialize()).length) - .to.be.equal(mosaicGlobalRestrictionTransaction.size); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + 'C51FB4C93FCA509502000000000000000100000000000000090000000000000008000000000000000106', + ); + expect(Convert.hexToUint8(mosaicGlobalRestrictionTransaction.serialize()).length).to.be.equal( + mosaicGlobalRestrictionTransaction.size, + ); }); it('should createComplete an MosaicGlobalRestrictionTransaction use mosaic alias reference', () => { @@ -139,11 +140,9 @@ describe('MosaicGlobalRestrictionTransaction', () => { const signedTransaction = mosaicGlobalRestrictionTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('0100000000000000C51FB4C93FCA50950100000000000000090000000000000008000000000000000106'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '0100000000000000C51FB4C93FCA50950100000000000000090000000000000008000000000000000106', + ); }); it('Test set maxFee using multiplier', () => { @@ -160,7 +159,6 @@ describe('MosaicGlobalRestrictionTransaction', () => { NetworkType.MIJIN_TEST, referenceMosaicId, ).setMaxFee(2); -​ expect(mosaicGlobalRestrictionTransaction.maxFee.compact()).to.be.equal(340); const signedTransaction = mosaicGlobalRestrictionTransaction.signWith(account, generationHash); @@ -182,8 +180,8 @@ describe('MosaicGlobalRestrictionTransaction', () => { MosaicRestrictionType.GE, '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); expect(mosaicGlobalRestrictionTransaction.mosaicId instanceof MosaicId).to.be.true; expect((mosaicGlobalRestrictionTransaction.mosaicId as MosaicId).equals(resolvedMosaicId)).to.be.true; expect(mosaicGlobalRestrictionTransaction.referenceMosaicId instanceof MosaicId).to.be.true; diff --git a/test/model/transaction/MosaicMetadataTransaction.spec.ts b/test/model/transaction/MosaicMetadataTransaction.spec.ts index d084164cef..3751864ed0 100644 --- a/test/model/transaction/MosaicMetadataTransaction.spec.ts +++ b/test/model/transaction/MosaicMetadataTransaction.spec.ts @@ -30,6 +30,8 @@ import { MosaicMetadataTransaction } from '../../../src/model/transaction/Mosaic import { TransactionInfo } from '../../../src/model/transaction/TransactionInfo'; import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; +import { EmbeddedTransactionBuilder } from 'catbuffer-typescript'; +import { TransactionType } from '../../../src/model/model'; describe('MosaicMetadataTransaction', () => { let account: Account; @@ -39,10 +41,14 @@ describe('MosaicMetadataTransaction', () => { const resolvedMosaicId = new MosaicId('0DC67FBE1CAD29E5'); before(() => { account = TestingAccount; - statement = new Statement([], + statement = new Statement( [], - [new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, - [new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0))])], + [], + [ + new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, [ + new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0)), + ]), + ], ); }); @@ -90,25 +96,10 @@ describe('MosaicMetadataTransaction', () => { const signedTransaction = mosaicMetadataTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8' + - '787B6E8030000000000004CCCD78612DDF5CA01000A0000000000000000000000'); - }); - - it('should throw error if value size is bigger than 1024', () => { - expect(() => { - MosaicMetadataTransaction.create( - Deadline.create(), - account.publicKey, - UInt64.fromUint(1000), - new MosaicId([2262289484, 3405110546]), - 1, - Convert.uint8ToUtf8(new Uint8Array(1025)), - NetworkType.MIJIN_TEST, - ); - }).to.throw(Error, 'The maximum value size is 1024'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA8' + + '787B6E8030000000000004CCCD78612DDF5CA01000A0000000000000000000000', + ); }); it('should create and sign an MosaicMetadataTransaction object using alias', () => { @@ -125,11 +116,10 @@ describe('MosaicMetadataTransaction', () => { const signedTransaction = mosaicMetadataTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA878' + - '7B6E803000000000000C51FB4C93FCA509501000A0000000000000000000000'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '9801508C58666C746F471538E43002B85B1CD542F9874B2861183919BA878' + + '7B6E803000000000000C51FB4C93FCA509501000A0000000000000000000000', + ); }); describe('size', () => { @@ -145,7 +135,6 @@ describe('MosaicMetadataTransaction', () => { ); expect(mosaicMetadataTransaction.size).to.be.equal(190); expect(Convert.hexToUint8(mosaicMetadataTransaction.serialize()).length).to.be.equal(mosaicMetadataTransaction.size); - }); }); @@ -159,7 +148,6 @@ describe('MosaicMetadataTransaction', () => { Convert.uint8ToUtf8(new Uint8Array(10)), NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(mosaicMetadataTransaction.maxFee.compact()).to.be.equal(380); const signedTransaction = mosaicMetadataTransaction.signWith(account, generationHash); @@ -179,12 +167,32 @@ describe('MosaicMetadataTransaction', () => { Convert.uint8ToUtf8(new Uint8Array(10)), '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); expect(mosaicMetadataTransaction.targetMosaicId instanceof MosaicId).to.be.true; expect((mosaicMetadataTransaction.targetMosaicId as MosaicId).equals(resolvedMosaicId)).to.be.true; const signedTransaction = mosaicMetadataTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; }); + + it('should create EmbeddedTransactionBuilder', () => { + const mosaicMetadataTransaction = MosaicMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(1000), + new MosaicId([2262289484, 3405110546]), + 1, + Convert.uint8ToUtf8(new Uint8Array(10)), + NetworkType.MIJIN_TEST, + ); + + Object.assign(mosaicMetadataTransaction, { signer: account.publicAccount }); + + const embedded = mosaicMetadataTransaction.toEmbeddedTransaction(); + + expect(embedded).to.be.instanceOf(EmbeddedTransactionBuilder); + expect(Convert.uint8ToHex(embedded.signerPublicKey.key)).to.be.equal(account.publicKey); + expect(embedded.type.valueOf()).to.be.equal(TransactionType.MOSAIC_METADATA.valueOf()); + }); }); diff --git a/test/model/transaction/MosaicSupplyChangeTransaction.spec.ts b/test/model/transaction/MosaicSupplyChangeTransaction.spec.ts index 6a42f809b4..937c62a934 100644 --- a/test/model/transaction/MosaicSupplyChangeTransaction.spec.ts +++ b/test/model/transaction/MosaicSupplyChangeTransaction.spec.ts @@ -14,23 +14,23 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; -import {MosaicId} from '../../../src/model/mosaic/MosaicId'; -import {MosaicSupplyChangeAction} from '../../../src/model/mosaic/MosaicSupplyChangeAction'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; +import { MosaicId } from '../../../src/model/mosaic/MosaicId'; +import { MosaicSupplyChangeAction } from '../../../src/model/mosaic/MosaicSupplyChangeAction'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; import { ResolutionType } from '../../../src/model/receipt/ResolutionType'; import { Statement } from '../../../src/model/receipt/Statement'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {MosaicSupplyChangeTransaction} from '../../../src/model/transaction/MosaicSupplyChangeTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { MosaicSupplyChangeTransaction } from '../../../src/model/transaction/MosaicSupplyChangeTransaction'; import { TransactionInfo } from '../../../src/model/transaction/TransactionInfo'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('MosaicSupplyChangeTransaction', () => { let account: Account; @@ -40,10 +40,14 @@ describe('MosaicSupplyChangeTransaction', () => { const resolvedMosaicId = new MosaicId('0DC67FBE1CAD29E5'); before(() => { account = TestingAccount; - statement = new Statement([], + statement = new Statement( [], - [new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, - [new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0))])], + [], + [ + new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, [ + new ResolutionEntry(resolvedMosaicId, new ReceiptSource(1, 0)), + ]), + ], ); }); @@ -94,11 +98,9 @@ describe('MosaicSupplyChangeTransaction', () => { const signedTransaction = mosaicSupplyChangeTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('4CCCD78612DDF5CA0A0000000000000001'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '4CCCD78612DDF5CA0A0000000000000001', + ); }); describe('size', () => { @@ -125,7 +127,6 @@ describe('MosaicSupplyChangeTransaction', () => { UInt64.fromUint(10), NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(mosaicSupplyChangeTransaction.maxFee.compact()).to.be.equal(290); const signedTransaction = mosaicSupplyChangeTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; @@ -142,8 +143,8 @@ describe('MosaicSupplyChangeTransaction', () => { UInt64.fromUint(10), '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); expect(mosaicSupplyChangeTransaction.mosaicId instanceof MosaicId).to.be.true; expect((mosaicSupplyChangeTransaction.mosaicId as MosaicId).equals(resolvedMosaicId)).to.be.true; diff --git a/test/model/transaction/MultisigAccountModificationTransaction.spec.ts b/test/model/transaction/MultisigAccountModificationTransaction.spec.ts index 18bdcfe5b8..0ea8838be3 100644 --- a/test/model/transaction/MultisigAccountModificationTransaction.spec.ts +++ b/test/model/transaction/MultisigAccountModificationTransaction.spec.ts @@ -14,15 +14,15 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {MultisigAccountModificationTransaction} from '../../../src/model/transaction/MultisigAccountModificationTransaction'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { MultisigAccountModificationTransaction } from '../../../src/model/transaction/MultisigAccountModificationTransaction'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('MultisigAccountModificationTransaction', () => { let account: Account; @@ -36,10 +36,15 @@ describe('MultisigAccountModificationTransaction', () => { Deadline.create(), 2, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST), - PublicAccount.createFromPublicKey('B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', - NetworkType.MIJIN_TEST), + [ + PublicAccount.createFromPublicKey( + 'B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', + NetworkType.MIJIN_TEST, + ), + PublicAccount.createFromPublicKey( + 'B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', + NetworkType.MIJIN_TEST, + ), ], [], NetworkType.MIJIN_TEST, @@ -54,10 +59,15 @@ describe('MultisigAccountModificationTransaction', () => { Deadline.create(), 2, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST), - PublicAccount.createFromPublicKey('B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', - NetworkType.MIJIN_TEST), + [ + PublicAccount.createFromPublicKey( + 'B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', + NetworkType.MIJIN_TEST, + ), + PublicAccount.createFromPublicKey( + 'B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', + NetworkType.MIJIN_TEST, + ), ], [], NetworkType.MIJIN_TEST, @@ -73,36 +83,37 @@ describe('MultisigAccountModificationTransaction', () => { Deadline.create(), 2, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST), - PublicAccount.createFromPublicKey('B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', - NetworkType.MIJIN_TEST), + [ + PublicAccount.createFromPublicKey( + 'B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', + NetworkType.MIJIN_TEST, + ), + PublicAccount.createFromPublicKey( + 'B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', + NetworkType.MIJIN_TEST, + ), ], [], NetworkType.MIJIN_TEST, ); - expect(modifyMultisigAccountTransaction.minApprovalDelta) - .to.be.equal(2); - expect(modifyMultisigAccountTransaction.minRemovalDelta) - .to.be.equal(1); - expect(modifyMultisigAccountTransaction.publicKeyAdditions.length) - .to.be.equal(2); - expect(modifyMultisigAccountTransaction.publicKeyAdditions[0].publicKey) - .to.be.equal('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24'); - expect(modifyMultisigAccountTransaction.publicKeyAdditions[1].publicKey) - .to.be.equal('B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4'); - expect(modifyMultisigAccountTransaction.publicKeyDeletions.length) - .to.be.equal(0); + expect(modifyMultisigAccountTransaction.minApprovalDelta).to.be.equal(2); + expect(modifyMultisigAccountTransaction.minRemovalDelta).to.be.equal(1); + expect(modifyMultisigAccountTransaction.publicKeyAdditions.length).to.be.equal(2); + expect(modifyMultisigAccountTransaction.publicKeyAdditions[0].publicKey).to.be.equal( + 'B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', + ); + expect(modifyMultisigAccountTransaction.publicKeyAdditions[1].publicKey).to.be.equal( + 'B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', + ); + expect(modifyMultisigAccountTransaction.publicKeyDeletions.length).to.be.equal(0); const signedTransaction = modifyMultisigAccountTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('0102020000000000B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC' + - '6EC24B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '0102020000000000B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC' + + '6EC24B1B5581FC81A6970DEE418D2C2978F2724228B7B36C5C6DF71B0162BB04778B4', + ); }); describe('size', () => { @@ -111,14 +122,19 @@ describe('MultisigAccountModificationTransaction', () => { Deadline.create(), 1, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST)], + [ + PublicAccount.createFromPublicKey( + 'B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', + NetworkType.MIJIN_TEST, + ), + ], [], NetworkType.MIJIN_TEST, ); expect(modifyMultisigAccountTransaction.size).to.be.equal(168); - expect(Convert.hexToUint8(modifyMultisigAccountTransaction.serialize()).length) - .to.be.equal(modifyMultisigAccountTransaction.size); + expect(Convert.hexToUint8(modifyMultisigAccountTransaction.serialize()).length).to.be.equal( + modifyMultisigAccountTransaction.size, + ); }); }); @@ -127,12 +143,10 @@ describe('MultisigAccountModificationTransaction', () => { Deadline.create(), 1, 1, - [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', - NetworkType.MIJIN_TEST)], + [PublicAccount.createFromPublicKey('B0F93CBEE49EEB9953C6F3985B15A4F238E205584D8F924C621CBE4D7AC6EC24', NetworkType.MIJIN_TEST)], [], NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(modifyMultisigAccountTransaction.maxFee.compact()).to.be.equal(336); const signedTransaction = modifyMultisigAccountTransaction.signWith(account, generationHash); diff --git a/test/model/transaction/MultisigCosignatoryModification.spec.ts b/test/model/transaction/MultisigCosignatoryModification.spec.ts index c313c565c3..47f24f0872 100644 --- a/test/model/transaction/MultisigCosignatoryModification.spec.ts +++ b/test/model/transaction/MultisigCosignatoryModification.spec.ts @@ -14,21 +14,21 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {PublicAccount} from '../../../src/model/account/PublicAccount'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {CosignatoryModificationAction} from '../../../src/model/transaction/CosignatoryModificationAction'; -import {MultisigCosignatoryModification} from '../../../src/model/transaction/MultisigCosignatoryModification'; +import { expect } from 'chai'; +import { PublicAccount } from '../../../src/model/account/PublicAccount'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { CosignatoryModificationAction } from '../../../src/model/transaction/CosignatoryModificationAction'; +import { MultisigCosignatoryModification } from '../../../src/model/transaction/MultisigCosignatoryModification'; describe('MultisigCosignatoryModification', () => { - it('should create Add MultisigCosignatoryModification', () => { const multisigCosignatoryModification = new MultisigCosignatoryModification( CosignatoryModificationAction.Add, PublicAccount.createFromPublicKey('C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB', NetworkType.MIJIN_TEST), ); - expect(multisigCosignatoryModification.cosignatoryPublicAccount.publicKey) - .to.be.equal('C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB'); + expect(multisigCosignatoryModification.cosignatoryPublicAccount.publicKey).to.be.equal( + 'C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB', + ); expect(multisigCosignatoryModification.modificationAction).to.be.equal(CosignatoryModificationAction.Add); }); @@ -37,8 +37,9 @@ describe('MultisigCosignatoryModification', () => { CosignatoryModificationAction.Add, PublicAccount.createFromPublicKey('C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB', NetworkType.MIJIN_TEST), ).toDTO(); - expect(multisigCosignatoryModification.cosignatoryPublicKey) - .to.be.equal('C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB'); + expect(multisigCosignatoryModification.cosignatoryPublicKey).to.be.equal( + 'C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB', + ); expect(multisigCosignatoryModification.modificationAction).to.be.equal(CosignatoryModificationAction.Add); }); @@ -47,8 +48,9 @@ describe('MultisigCosignatoryModification', () => { CosignatoryModificationAction.Remove, PublicAccount.createFromPublicKey('C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB', NetworkType.MIJIN_TEST), ); - expect(multisigCosignatoryModification.cosignatoryPublicAccount.publicKey) - .to.be.equal('C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB'); + expect(multisigCosignatoryModification.cosignatoryPublicAccount.publicKey).to.be.equal( + 'C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB', + ); expect(multisigCosignatoryModification.modificationAction).to.be.equal(CosignatoryModificationAction.Remove); }); @@ -57,8 +59,9 @@ describe('MultisigCosignatoryModification', () => { CosignatoryModificationAction.Remove, PublicAccount.createFromPublicKey('C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB', NetworkType.MIJIN_TEST), ).toDTO(); - expect(multisigCosignatoryModification.cosignatoryPublicKey) - .to.be.equal('C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB'); + expect(multisigCosignatoryModification.cosignatoryPublicKey).to.be.equal( + 'C52C211CF935C61D65F26B253AA260416F018C3D21E4D184A7671F403C849BBB', + ); expect(multisigCosignatoryModification.modificationAction).to.be.equal(CosignatoryModificationAction.Remove); }); }); diff --git a/test/model/transaction/NamespaceMetadataTransaction.spec.ts b/test/model/transaction/NamespaceMetadataTransaction.spec.ts index 801735c777..42551d6543 100644 --- a/test/model/transaction/NamespaceMetadataTransaction.spec.ts +++ b/test/model/transaction/NamespaceMetadataTransaction.spec.ts @@ -23,6 +23,9 @@ import { Deadline } from '../../../src/model/transaction/Deadline'; import { NamespaceMetadataTransaction } from '../../../src/model/transaction/NamespaceMetadataTransaction'; import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; +import { EmbeddedTransactionBuilder } from 'catbuffer-typescript/builders/EmbeddedTransactionBuilder'; +import { TransactionType } from '../../../src/model/transaction/TransactionType'; +import { deepEqual } from 'assert'; describe('NamespaceMetadataTransaction', () => { let account: Account; @@ -75,25 +78,10 @@ describe('NamespaceMetadataTransaction', () => { const signedTransaction = namespaceMetadataTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('9801508C58666C746F471538E43002B85B1CD542F9874B2861183919B' + - 'A8787B6E8030000000000004CCCD78612DDF5CA01000A0000000000000000000000'); - }); - - it('should throw error if value size is bigger than 1024', () => { - expect(() => { - NamespaceMetadataTransaction.create( - Deadline.create(), - account.publicKey, - UInt64.fromUint(1000), - new NamespaceId([2262289484, 3405110546]), - 1, - Convert.uint8ToUtf8(new Uint8Array(1025)), - NetworkType.MIJIN_TEST, - ); - }).to.throw(Error, 'The maximum value size is 1024'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '9801508C58666C746F471538E43002B85B1CD542F9874B2861183919B' + + 'A8787B6E8030000000000004CCCD78612DDF5CA01000A0000000000000000000000', + ); }); describe('size', () => { @@ -122,10 +110,45 @@ describe('NamespaceMetadataTransaction', () => { Convert.uint8ToUtf8(new Uint8Array(10)), NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(namespaceMetadataTransaction.maxFee.compact()).to.be.equal(380); const signedTransaction = namespaceMetadataTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; }); + + it('should create EmbeddedTransactionBuilder', () => { + const namespaceMetadataTransaction = NamespaceMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(1000), + new NamespaceId([2262289484, 3405110546]), + 1, + Convert.uint8ToUtf8(new Uint8Array(10)), + NetworkType.MIJIN_TEST, + ); + + Object.assign(namespaceMetadataTransaction, { signer: account.publicAccount }); + + const embedded = namespaceMetadataTransaction.toEmbeddedTransaction(); + + expect(embedded).to.be.instanceOf(EmbeddedTransactionBuilder); + expect(Convert.uint8ToHex(embedded.signerPublicKey.key)).to.be.equal(account.publicKey); + expect(embedded.type.valueOf()).to.be.equal(TransactionType.NAMESPACE_METADATA.valueOf()); + }); + + it('should resolve alias', () => { + const namespaceMetadataTransaction = NamespaceMetadataTransaction.create( + Deadline.create(), + account.publicKey, + UInt64.fromUint(1000), + new NamespaceId([2262289484, 3405110546]), + 1, + Convert.uint8ToUtf8(new Uint8Array(10)), + NetworkType.MIJIN_TEST, + ); + const resolved = namespaceMetadataTransaction.resolveAliases(); + + expect(resolved).to.be.instanceOf(NamespaceMetadataTransaction); + deepEqual(namespaceMetadataTransaction, resolved); + }); }); diff --git a/test/model/transaction/NamespaceRegistrationTransaction.spec.ts b/test/model/transaction/NamespaceRegistrationTransaction.spec.ts index 38fd8bd2d7..ec21a309d5 100644 --- a/test/model/transaction/NamespaceRegistrationTransaction.spec.ts +++ b/test/model/transaction/NamespaceRegistrationTransaction.spec.ts @@ -14,15 +14,15 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Convert} from '../../../src/core/format'; -import {Account} from '../../../src/model/account/Account'; +import { expect } from 'chai'; +import { Convert } from '../../../src/core/format'; +import { Account } from '../../../src/model/account/Account'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {NamespaceRegistrationTransaction} from '../../../src/model/transaction/NamespaceRegistrationTransaction'; -import {UInt64} from '../../../src/model/UInt64'; -import {TestingAccount} from '../../conf/conf.spec'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { NamespaceRegistrationTransaction } from '../../../src/model/transaction/NamespaceRegistrationTransaction'; +import { UInt64 } from '../../../src/model/UInt64'; +import { TestingAccount } from '../../conf/conf.spec'; describe('NamespaceRegistrationTransaction', () => { let account: Account; @@ -69,11 +69,9 @@ describe('NamespaceRegistrationTransaction', () => { const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('E803000000000000CFCBE72D994BE69B0013726F6F742D746573742D6E616D657370616365'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + 'E803000000000000CFCBE72D994BE69B0013726F6F742D746573742D6E616D657370616365', + ); }); it('should createComplete an sub NamespaceRegistrationTransaction object and sign it', () => { @@ -86,11 +84,9 @@ describe('NamespaceRegistrationTransaction', () => { const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('4DF55E7F6D8FB7FF924207DF2CA1BBF30113726F6F742D746573742D6E616D657370616365'); - + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '4DF55E7F6D8FB7FF924207DF2CA1BBF30113726F6F742D746573742D6E616D657370616365', + ); }); it('should createComplete an sub NamespaceRegistrationTransaction object and sign it - ParentId', () => { @@ -103,10 +99,9 @@ describe('NamespaceRegistrationTransaction', () => { const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('4BFA5F372D55B384CFCBE72D994BE69B0113726F6F742D746573742D6E616D657370616365'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '4BFA5F372D55B384CFCBE72D994BE69B0113726F6F742D746573742D6E616D657370616365', + ); }); describe('size', () => { @@ -129,7 +124,6 @@ describe('NamespaceRegistrationTransaction', () => { UInt64.fromUint(1000), NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(registerNamespaceTransaction.maxFee.compact()).to.be.equal(330); const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash); diff --git a/test/model/transaction/PersistentDelegationRequestTransaction.spec.ts b/test/model/transaction/PersistentDelegationRequestTransaction.spec.ts index fb5e2a71e4..6c76fe503c 100644 --- a/test/model/transaction/PersistentDelegationRequestTransaction.spec.ts +++ b/test/model/transaction/PersistentDelegationRequestTransaction.spec.ts @@ -20,10 +20,8 @@ import { Address } from '../../../src/model/account/Address'; import { MessageMarker } from '../../../src/model/message/MessageMarker'; import { NetworkType } from '../../../src/model/network/NetworkType'; import { Deadline } from '../../../src/model/transaction/Deadline'; -import { - PersistentDelegationRequestTransaction, -} from '../../../src/model/transaction/PersistentDelegationRequestTransaction'; -import {UInt64} from '../../../src/model/UInt64'; +import { PersistentDelegationRequestTransaction } from '../../../src/model/transaction/PersistentDelegationRequestTransaction'; +import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; describe('PersistentDelegationRequestTransaction', () => { @@ -38,54 +36,53 @@ describe('PersistentDelegationRequestTransaction', () => { }); it('should default maxFee field be set to 0', () => { - const persistentDelegationRequestTransaction = - PersistentDelegationRequestTransaction.createPersistentDelegationRequestTransaction( - Deadline.create(), - delegatedPrivateKey, - recipientPublicKey, - NetworkType.MIJIN_TEST, - ); + const persistentDelegationRequestTransaction = PersistentDelegationRequestTransaction.createPersistentDelegationRequestTransaction( + Deadline.create(), + delegatedPrivateKey, + recipientPublicKey, + NetworkType.MIJIN_TEST, + ); expect(persistentDelegationRequestTransaction.maxFee.higher).to.be.equal(0); expect(persistentDelegationRequestTransaction.maxFee.lower).to.be.equal(0); }); it('should filled maxFee override transaction maxFee', () => { - const persistentDelegationRequestTransaction = - PersistentDelegationRequestTransaction.createPersistentDelegationRequestTransaction( - Deadline.create(), - delegatedPrivateKey, - recipientPublicKey, - NetworkType.MIJIN_TEST, - new UInt64([1, 0]), - ); + const persistentDelegationRequestTransaction = PersistentDelegationRequestTransaction.createPersistentDelegationRequestTransaction( + Deadline.create(), + delegatedPrivateKey, + recipientPublicKey, + NetworkType.MIJIN_TEST, + new UInt64([1, 0]), + ); expect(persistentDelegationRequestTransaction.maxFee.higher).to.be.equal(0); expect(persistentDelegationRequestTransaction.maxFee.lower).to.be.equal(1); }); it('should createComplete an persistentDelegationRequestTransaction object and sign it', () => { - const persistentDelegationRequestTransaction = - PersistentDelegationRequestTransaction.createPersistentDelegationRequestTransaction( - Deadline.create(), - delegatedPrivateKey, - recipientPublicKey, - NetworkType.MIJIN_TEST, - ); + const persistentDelegationRequestTransaction = PersistentDelegationRequestTransaction.createPersistentDelegationRequestTransaction( + Deadline.create(), + delegatedPrivateKey, + recipientPublicKey, + NetworkType.MIJIN_TEST, + ); expect(persistentDelegationRequestTransaction.message.payload.length).to.be.equal(192 + messageMarker.length); expect(persistentDelegationRequestTransaction.message.payload.includes(messageMarker)).to.be.true; expect(persistentDelegationRequestTransaction.mosaics.length).to.be.equal(0); expect(persistentDelegationRequestTransaction.recipientAddress).to.be.instanceof(Address); - expect((persistentDelegationRequestTransaction.recipientAddress as Address).plain()) - .to.be.equal('SDBC4JE7GTJAKN2XJCQWWRJMYA35AFOYQBATXOUA'); + expect((persistentDelegationRequestTransaction.recipientAddress as Address).plain()).to.be.equal( + 'SDBC4JE7GTJAKN2XJCQWWRJMYA35AFOYQBATXOUA', + ); const signedTransaction = persistentDelegationRequestTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - ).includes(persistentDelegationRequestTransaction.message.payload)).to.be.true; + expect( + signedTransaction.payload + .substring(256, signedTransaction.payload.length) + .includes(persistentDelegationRequestTransaction.message.payload), + ).to.be.true; }); it('should throw exception with invalid harvester publicKey (message)', () => { diff --git a/test/model/transaction/SecretLockTransaction.spec.ts b/test/model/transaction/SecretLockTransaction.spec.ts index 9d394e512c..3a8a8cda2b 100644 --- a/test/model/transaction/SecretLockTransaction.spec.ts +++ b/test/model/transaction/SecretLockTransaction.spec.ts @@ -1,5 +1,5 @@ /* - * Copyright 2018 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,30 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import * as CryptoJS from 'crypto-js'; -import {keccak_256, sha3_256} from 'js-sha3'; -import {Convert, Convert as convert} from '../../../src/core/format'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { sha3_256 } from 'js-sha3'; +import { Convert, Convert as convert } from '../../../src/core/format'; import { Account } from '../../../src/model/account/Account'; -import {Address} from '../../../src/model/account/Address'; +import { Address } from '../../../src/model/account/Address'; import { Mosaic } from '../../../src/model/mosaic/Mosaic'; import { MosaicId } from '../../../src/model/mosaic/MosaicId'; -import {NetworkCurrencyLocal} from '../../../src/model/mosaic/NetworkCurrencyLocal'; +import { NetworkCurrencyLocal } from '../../../src/model/mosaic/NetworkCurrencyLocal'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; import { ResolutionType } from '../../../src/model/receipt/ResolutionType'; import { Statement } from '../../../src/model/receipt/Statement'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {HashType} from '../../../src/model/transaction/HashType'; -import {SecretLockTransaction} from '../../../src/model/transaction/SecretLockTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { LockHashAlgorithm } from '../../../src/model/transaction/LockHashAlgorithm'; +import { SecretLockTransaction } from '../../../src/model/transaction/SecretLockTransaction'; import { TransactionInfo } from '../../../src/model/transaction/TransactionInfo'; -import {UInt64} from '../../../src/model/UInt64'; +import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const CryptoJS = require('crypto-js'); + describe('SecretLockTransaction', () => { let account: Account; let statement: Statement; @@ -46,11 +48,18 @@ describe('SecretLockTransaction', () => { const generationHash = '57F7DA205008026C776CB6AED843393F04CD458E0AA2D9F1D5F31A402072B2D6'; before(() => { account = TestingAccount; - statement = new Statement([], - [new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, - [new ResolutionEntry(account.address, new ReceiptSource(1, 0))])], - [new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, - [new ResolutionEntry(mosaicId, new ReceiptSource(1, 0))])], + statement = new Statement( + [], + [ + new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, [ + new ResolutionEntry(account.address, new ReceiptSource(1, 0)), + ]), + ], + [ + new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, [ + new ResolutionEntry(mosaicId, new ReceiptSource(1, 0)), + ]), + ], ); }); @@ -61,7 +70,7 @@ describe('SecretLockTransaction', () => { Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, @@ -78,7 +87,7 @@ describe('SecretLockTransaction', () => { Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, @@ -89,14 +98,14 @@ describe('SecretLockTransaction', () => { expect(secretLockTransaction.maxFee.lower).to.be.equal(1); }); - it('should be created with HashType: Op_Sha3_256 secret', () => { + it('should be created with LockHashAlgorithm: Op_Sha3_256 secret', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, @@ -104,7 +113,7 @@ describe('SecretLockTransaction', () => { deepEqual(secretLockTransaction.mosaic.id.id, NetworkCurrencyLocal.NAMESPACE_ID.id); expect(secretLockTransaction.mosaic.amount.equals(UInt64.fromUint(10))).to.be.equal(true); expect(secretLockTransaction.duration.equals(UInt64.fromUint(100))).to.be.equal(true); - expect(secretLockTransaction.hashType).to.be.equal(0); + expect(secretLockTransaction.hashAlgorithm).to.be.equal(0); expect(secretLockTransaction.secret).to.be.equal('9b3155b37159da50aa52d5967c509b410f5a36a3b1e31ecb5ac76675d79b4a5e'); expect(secretLockTransaction.recipientAddress).to.be.equal(recipientAddress); }); @@ -116,28 +125,26 @@ describe('SecretLockTransaction', () => { Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, ); const signedTx = secretLockTransaction.signWith(account, generationHash); - expect(signedTx.payload.substring( - 256, - signedTx.payload.length, - )).to.be.equal( + expect(signedTx.payload.substring(256, signedTx.payload.length)).to.be.equal( '9B3155B37159DA50AA52D5967C509B410F5A36A3B1E31ECB5AC76675D79B4A5E44B262C46CEABB850A' + - '0000000000000064000000000000000090C2337113E6D8F15B56E0821149299F340C01706FC1CAD6CB'); + '0000000000000064000000000000000090C2337113E6D8F15B56E0821149299F340C01706FC1CAD6CB', + ); }); it('should throw exception when the input is not related to HashTyp: Op_Sha3_256', () => { expect(() => { const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); - const secretLockTransaction = SecretLockTransaction.create( + SecretLockTransaction.create( Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, 'non valid hash', recipientAddress, NetworkType.MIJIN_TEST, @@ -145,48 +152,14 @@ describe('SecretLockTransaction', () => { }).to.throw(Error); }); - it('should be created with HashType: Op_Keccak_256 secret', () => { - const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; - const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); - const secretLockTransaction = SecretLockTransaction.create( - Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), - UInt64.fromUint(100), - HashType.Op_Keccak_256, - keccak_256.create().update(convert.hexToUint8(proof)).hex(), - recipientAddress, - NetworkType.MIJIN_TEST, - ); - deepEqual(secretLockTransaction.mosaic.id.id, NetworkCurrencyLocal.NAMESPACE_ID.id); - expect(secretLockTransaction.mosaic.amount.equals(UInt64.fromUint(10))).to.be.equal(true); - expect(secretLockTransaction.duration.equals(UInt64.fromUint(100))).to.be.equal(true); - expect(secretLockTransaction.hashType).to.be.equal(1); - expect(secretLockTransaction.secret).to.be.equal('241c1d54c18c8422def03aa16b4b243a8ba491374295a1a6965545e6ac1af314'); - expect(secretLockTransaction.recipientAddress).to.be.equal(recipientAddress); - }); - - it('should throw exception when the input is not related to HashTyp: Op_Keccak_256', () => { - expect(() => { - const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); - const secretLockTransaction = SecretLockTransaction.create( - Deadline.create(), - NetworkCurrencyLocal.createAbsolute(10), - UInt64.fromUint(100), - HashType.Op_Keccak_256, - 'non valid hash', - recipientAddress, - NetworkType.MIJIN_TEST, - ); - }).to.throw(Error); - }); - it('should be created with HashType: Op_Hash_160 secret', () => { + it('should be created with LockHashAlgorithm: Op_Hash_160 secret', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9'; const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, CryptoJS.RIPEMD160(CryptoJS.SHA256(proof).toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex), recipientAddress, NetworkType.MIJIN_TEST, @@ -194,7 +167,7 @@ describe('SecretLockTransaction', () => { deepEqual(secretLockTransaction.mosaic.id.id, NetworkCurrencyLocal.NAMESPACE_ID.id); expect(secretLockTransaction.mosaic.amount.equals(UInt64.fromUint(10))).to.be.equal(true); expect(secretLockTransaction.duration.equals(UInt64.fromUint(100))).to.be.equal(true); - expect(secretLockTransaction.hashType).to.be.equal(2); + expect(secretLockTransaction.hashAlgorithm).to.be.equal(1); expect(secretLockTransaction.secret).to.be.equal('3fc43d717d824302e3821de8129ea2f7786912e5'); expect(secretLockTransaction.recipientAddress).to.be.equal(recipientAddress); }); @@ -202,25 +175,25 @@ describe('SecretLockTransaction', () => { it('should throw exception when the input is not related to HashTyp: Op_Hash_160', () => { expect(() => { const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); - const secretLockTransaction = SecretLockTransaction.create( + SecretLockTransaction.create( Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, 'non valid hash', recipientAddress, NetworkType.MIJIN_TEST, ); }).to.throw(Error); }); - it('should be created with HashType: Op_Hash_256 secret', () => { + it('should be created with LockHashAlgorithm: Op_Hash_256 secret', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); const secretLockTransaction = SecretLockTransaction.create( Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, CryptoJS.SHA256(CryptoJS.SHA256(proof).toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex), recipientAddress, NetworkType.MIJIN_TEST, @@ -228,7 +201,7 @@ describe('SecretLockTransaction', () => { deepEqual(secretLockTransaction.mosaic.id.id, NetworkCurrencyLocal.NAMESPACE_ID.id); expect(secretLockTransaction.mosaic.amount.equals(UInt64.fromUint(10))).to.be.equal(true); expect(secretLockTransaction.duration.equals(UInt64.fromUint(100))).to.be.equal(true); - expect(secretLockTransaction.hashType).to.be.equal(3); + expect(secretLockTransaction.hashAlgorithm).to.be.equal(2); expect(secretLockTransaction.secret).to.be.equal('c346f5ecf5bcfa54ab14fad815c8239bdeb051df8835d212dba2af59f688a00e'); expect(secretLockTransaction.recipientAddress).to.be.equal(recipientAddress); }); @@ -236,11 +209,11 @@ describe('SecretLockTransaction', () => { it('should throw exception when the input is not related to HashTyp: Op_Hash_256', () => { expect(() => { const recipientAddress = Address.createFromRawAddress('SDBDG4IT43MPCW2W4CBBCSJJT42AYALQN7A4VVWL'); - const secretLockTransaction = SecretLockTransaction.create( + SecretLockTransaction.create( Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, 'non valid hash', recipientAddress, NetworkType.MIJIN_TEST, @@ -256,7 +229,7 @@ describe('SecretLockTransaction', () => { Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, CryptoJS.SHA256(CryptoJS.SHA256(proof).toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex), recipientAddress, NetworkType.MIJIN_TEST, @@ -273,7 +246,7 @@ describe('SecretLockTransaction', () => { Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, @@ -281,7 +254,7 @@ describe('SecretLockTransaction', () => { deepEqual(secretLockTransaction.mosaic.id.id, NetworkCurrencyLocal.NAMESPACE_ID.id); expect(secretLockTransaction.mosaic.amount.equals(UInt64.fromUint(10))).to.be.equal(true); expect(secretLockTransaction.duration.equals(UInt64.fromUint(100))).to.be.equal(true); - expect(secretLockTransaction.hashType).to.be.equal(0); + expect(secretLockTransaction.hashAlgorithm).to.be.equal(0); expect(secretLockTransaction.secret).to.be.equal('9b3155b37159da50aa52d5967c509b410f5a36a3b1e31ecb5ac76675d79b4a5e'); expect(secretLockTransaction.recipientAddress).to.be.equal(recipientAddress); }); @@ -293,12 +266,11 @@ describe('SecretLockTransaction', () => { Deadline.create(), NetworkCurrencyLocal.createAbsolute(10), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), recipientAddress, NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(secretLockTransaction.maxFee.compact()).to.be.equal(420); const signedTransaction = secretLockTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; @@ -313,13 +285,13 @@ describe('SecretLockTransaction', () => { UInt64.fromUint(0), new Mosaic(unresolvedMosaicId, UInt64.fromUint(1)), UInt64.fromUint(100), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), unresolvedAddress, '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); expect(secretLockTransaction.recipientAddress instanceof Address).to.be.true; expect(secretLockTransaction.mosaic.id instanceof MosaicId).to.be.true; expect((secretLockTransaction.recipientAddress as Address).equals(account.address)).to.be.true; diff --git a/test/model/transaction/SecretProofTransaction.spec.ts b/test/model/transaction/SecretProofTransaction.spec.ts index e118cefe26..9dfc6edc8f 100644 --- a/test/model/transaction/SecretProofTransaction.spec.ts +++ b/test/model/transaction/SecretProofTransaction.spec.ts @@ -1,5 +1,5 @@ /* - * Copyright 2018 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,25 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import * as CryptoJS from 'crypto-js'; -import {keccak_256, sha3_256} from 'js-sha3'; -import {Convert, Convert as convert} from '../../../src/core/format'; +import { expect } from 'chai'; +import { sha3_256 } from 'js-sha3'; +import { Convert, Convert as convert } from '../../../src/core/format'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; import { NamespaceId } from '../../../src/model/namespace/NamespaceId'; -import {NetworkType} from '../../../src/model/network/NetworkType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; import { ReceiptSource } from '../../../src/model/receipt/ReceiptSource'; import { ResolutionEntry } from '../../../src/model/receipt/ResolutionEntry'; import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatement'; import { ResolutionType } from '../../../src/model/receipt/ResolutionType'; import { Statement } from '../../../src/model/receipt/Statement'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {HashType} from '../../../src/model/transaction/HashType'; -import {SecretProofTransaction} from '../../../src/model/transaction/SecretProofTransaction'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { LockHashAlgorithm } from '../../../src/model/transaction/LockHashAlgorithm'; +import { SecretProofTransaction } from '../../../src/model/transaction/SecretProofTransaction'; import { TransactionInfo } from '../../../src/model/transaction/TransactionInfo'; -import {UInt64} from '../../../src/model/UInt64'; +import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; +import { EmbeddedTransactionBuilder } from 'catbuffer-typescript/builders/EmbeddedTransactionBuilder'; +import { TransactionType } from '../../../src/model/transaction/TransactionType'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const CryptoJS = require('crypto-js'); describe('SecretProofTransaction', () => { let account: Account; @@ -40,9 +44,13 @@ describe('SecretProofTransaction', () => { const generationHash = '57F7DA205008026C776CB6AED843393F04CD458E0AA2D9F1D5F31A402072B2D6'; before(() => { account = TestingAccount; - statement = new Statement([], - [new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, - [new ResolutionEntry(account.address, new ReceiptSource(1, 0))])], + statement = new Statement( + [], + [ + new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, [ + new ResolutionEntry(account.address, new ReceiptSource(1, 0)), + ]), + ], [], ); }); @@ -51,7 +59,7 @@ describe('SecretProofTransaction', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), account.address, proof, @@ -66,7 +74,7 @@ describe('SecretProofTransaction', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), account.address, proof, @@ -78,27 +86,27 @@ describe('SecretProofTransaction', () => { expect(secretProofTransaction.maxFee.lower).to.be.equal(1); }); - it('should be created with HashType: Op_Sha3_256 secret', () => { + it('should be created with LockHashAlgorithm: Op_Sha3_256 secret', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), account.address, proof, NetworkType.MIJIN_TEST, ); - expect(secretProofTransaction.hashType).to.be.equal(0); - expect(secretProofTransaction.secret).to.be.equal('9b3155b37159da50aa52d5967c509b410f5a36a3b1e31ecb5ac76675d79b4a5e' ); + expect(secretProofTransaction.hashAlgorithm).to.be.equal(0); + expect(secretProofTransaction.secret).to.be.equal('9b3155b37159da50aa52d5967c509b410f5a36a3b1e31ecb5ac76675d79b4a5e'); expect(secretProofTransaction.proof).to.be.equal(proof); }); - it('should throw exception when the input is not related to HashType', () => { + it('should throw exception when the input is not related to LockHashAlgorithm', () => { expect(() => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; - const secretProofTransaction = SecretProofTransaction.create( + SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, 'non valid hash', account.address, proof, @@ -106,55 +114,28 @@ describe('SecretProofTransaction', () => { ); }).to.throw(Error); }); - it('should be created with HashType: Op_Keccak_256 secret', () => { - const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; - const secretProofTransaction = SecretProofTransaction.create( - Deadline.create(), - HashType.Op_Keccak_256, - keccak_256.create().update(convert.hexToUint8(proof)).hex(), - account.address, - proof, - NetworkType.MIJIN_TEST, - ); - expect(secretProofTransaction.hashType).to.be.equal(1); - expect(secretProofTransaction.secret).to.be.equal('241c1d54c18c8422def03aa16b4b243a8ba491374295a1a6965545e6ac1af314' ); - expect(secretProofTransaction.proof).to.be.equal(proof); - }); - it('should throw exception when the input is not related to HashType', () => { - expect(() => { - const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; - const secretProofTransaction = SecretProofTransaction.create( - Deadline.create(), - HashType.Op_Keccak_256, - 'non valid hash', - account.address, - proof, - NetworkType.MIJIN_TEST, - ); - }).to.throw(Error); - }); - it('should be created with HashType: Op_Hash_160 secret', () => { + it('should be created with LockHashAlgorithm: Op_Hash_160 secret', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, CryptoJS.RIPEMD160(CryptoJS.SHA256(proof).toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex), account.address, proof, NetworkType.MIJIN_TEST, ); - expect(secretProofTransaction.hashType).to.be.equal(2); - expect(secretProofTransaction.secret).to.be.equal('3fc43d717d824302e3821de8129ea2f7786912e5' ); + expect(secretProofTransaction.hashAlgorithm).to.be.equal(1); + expect(secretProofTransaction.secret).to.be.equal('3fc43d717d824302e3821de8129ea2f7786912e5'); expect(secretProofTransaction.proof).to.be.equal(proof); }); - it('should throw exception when the input is not related to HashType', () => { + it('should throw exception when the input is not related to LockHashAlgorithm', () => { expect(() => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; - const secretProofTransaction = SecretProofTransaction.create( + SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_160, + LockHashAlgorithm.Op_Hash_160, 'non valid hash', account.address, proof, @@ -163,27 +144,27 @@ describe('SecretProofTransaction', () => { }).to.throw(Error); }); - it('should be created with HashType: Op_Hash_256 secret', () => { + it('should be created with LockHashAlgorithm: Op_Hash_256 secret', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, CryptoJS.SHA256(CryptoJS.SHA256(proof).toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex), account.address, proof, NetworkType.MIJIN_TEST, ); - expect(secretProofTransaction.hashType).to.be.equal(3); - expect(secretProofTransaction.secret).to.be.equal('c346f5ecf5bcfa54ab14fad815c8239bdeb051df8835d212dba2af59f688a00e' ); + expect(secretProofTransaction.hashAlgorithm).to.be.equal(2); + expect(secretProofTransaction.secret).to.be.equal('c346f5ecf5bcfa54ab14fad815c8239bdeb051df8835d212dba2af59f688a00e'); expect(secretProofTransaction.proof).to.be.equal(proof); }); - it('should throw exception when the input is not related to HashType', () => { + it('should throw exception when the input is not related to LockHashAlgorithm', () => { expect(() => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; - const secretProofTransaction = SecretProofTransaction.create( + SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, 'non valid hash', account.address, proof, @@ -197,7 +178,7 @@ describe('SecretProofTransaction', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Hash_256, + LockHashAlgorithm.Op_Hash_256, CryptoJS.SHA256(CryptoJS.SHA256(proof).toString(CryptoJS.enc.Hex)).toString(CryptoJS.enc.Hex), account.address, proof, @@ -212,7 +193,7 @@ describe('SecretProofTransaction', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), account.address, proof, @@ -220,12 +201,10 @@ describe('SecretProofTransaction', () => { ); const signedTx = secretProofTransaction.signWith(account, generationHash); - expect(signedTx.payload.substring( - 256, - signedTx.payload.length, - )).to.be.equal( + expect(signedTx.payload.substring(256, signedTx.payload.length)).to.be.equal( '9B3155B37159DA50AA52D5967C509B410F5A36A3B1E31ECB5AC76675D79B4A5E20000090D66C33420E5411995BA' + - 'CFCA2B28CF1C9F5DD7AB1204EA451B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'); + 'CFCA2B28CF1C9F5DD7AB1204EA451B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7', + ); }); it('should be created with alias address', () => { @@ -233,14 +212,14 @@ describe('SecretProofTransaction', () => { const recipientAddress = new NamespaceId('test'); const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), recipientAddress, proof, NetworkType.MIJIN_TEST, ); - expect(secretProofTransaction.hashType).to.be.equal(0); - expect(secretProofTransaction.secret).to.be.equal('9b3155b37159da50aa52d5967c509b410f5a36a3b1e31ecb5ac76675d79b4a5e' ); + expect(secretProofTransaction.hashAlgorithm).to.be.equal(0); + expect(secretProofTransaction.secret).to.be.equal('9b3155b37159da50aa52d5967c509b410f5a36a3b1e31ecb5ac76675d79b4a5e'); expect(secretProofTransaction.proof).to.be.equal(proof); expect(secretProofTransaction.recipientAddress).to.be.equal(recipientAddress); }); @@ -249,13 +228,12 @@ describe('SecretProofTransaction', () => { const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; const secretProofTransaction = SecretProofTransaction.create( Deadline.create(), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), account.address, proof, NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(secretProofTransaction.maxFee.compact()).to.be.equal(440); const signedTransaction = secretProofTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; @@ -268,18 +246,57 @@ describe('SecretProofTransaction', () => { 1, Deadline.create(), UInt64.fromUint(0), - HashType.Op_Sha3_256, + LockHashAlgorithm.Op_Sha3_256, sha3_256.create().update(convert.hexToUint8(proof)).hex(), unresolvedAddress, proof, '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); expect(transferTransaction.recipientAddress instanceof Address).to.be.true; expect((transferTransaction.recipientAddress as Address).equals(account.address)).to.be.true; const signedTransaction = transferTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; }); + + it('should create EmbeddedTransactionBuilder', () => { + const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; + const secretProofTransaction = new SecretProofTransaction( + NetworkType.MIJIN_TEST, + 1, + Deadline.create(), + UInt64.fromUint(0), + LockHashAlgorithm.Op_Sha3_256, + sha3_256.create().update(convert.hexToUint8(proof)).hex(), + unresolvedAddress, + proof, + '', + account.publicAccount, + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ); + Object.assign(secretProofTransaction, { signer: account.publicAccount }); + + const embedded = secretProofTransaction.toEmbeddedTransaction(); + + expect(embedded).to.be.instanceOf(EmbeddedTransactionBuilder); + expect(Convert.uint8ToHex(embedded.signerPublicKey.key)).to.be.equal(account.publicKey); + expect(embedded.type.valueOf()).to.be.equal(TransactionType.SECRET_PROOF.valueOf()); + }); + + it('should return secret bytes', () => { + const proof = 'B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7'; + const secretProofTransaction = SecretProofTransaction.create( + Deadline.create(), + LockHashAlgorithm.Op_Sha3_256, + sha3_256.create().update(convert.hexToUint8(proof)).hex(), + account.address, + proof, + NetworkType.MIJIN_TEST, + ); + const secretBytes = secretProofTransaction.getSecretByte(); + expect(secretBytes).not.to.be.undefined; + expect(Convert.uint8ToHex(secretBytes)).to.be.equal('9B3155B37159DA50AA52D5967C509B410F5A36A3B1E31ECB5AC76675D79B4A5E'); + }); }); diff --git a/test/model/transaction/SignedTransaction.spec.ts b/test/model/transaction/SignedTransaction.spec.ts index a6c2875ea6..b5dbb57468 100644 --- a/test/model/transaction/SignedTransaction.spec.ts +++ b/test/model/transaction/SignedTransaction.spec.ts @@ -13,23 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; +import { expect } from 'chai'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {SignedTransaction} from '../../../src/model/transaction/SignedTransaction'; -import {TransactionType} from '../../../src/model/transaction/TransactionType'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { SignedTransaction } from '../../../src/model/transaction/SignedTransaction'; +import { TransactionType } from '../../../src/model/transaction/TransactionType'; describe('SignedTransaction', () => { - const hash = '8498B38D89C1DC8A448EA5824938FF828926CD9F7747B1844B59B4B6807E878B'; const publicKey = '5D58EC16F07BF00BDE9B040E7451A37F9908C59E143A01438C04345D8E9DDF39'; it('should return transfer transaction type', () => { const signedTransaction = new SignedTransaction( '9700000037FB5DD4291F2D1343B31E31D88A4392C8987BA76B329A273F51AE74E99' + - '554135DFE270D44EA8452E3E6075C6B898C26DD753D169452A115D96F6A4D7562C9' + - '0CC2F93346E27CE6AD1A9F8F5E3066F8326593A406BDF357ACB041E2F9AB402EFE0' + - '39054410000000000000000B098B7C00D000000900D8D3E65BF27ABE158BCD37C0A' + - '708BF6524A07EB09046A30030000004869', + '554135DFE270D44EA8452E3E6075C6B898C26DD753D169452A115D96F6A4D7562C9' + + '0CC2F93346E27CE6AD1A9F8F5E3066F8326593A406BDF357ACB041E2F9AB402EFE0' + + '39054410000000000000000B098B7C00D000000900D8D3E65BF27ABE158BCD37C0A' + + '708BF6524A07EB09046A30030000004869', '07901DA8A8AFE1DFB76D1A079B8E785C1186BAF2C5B98227B62BDE2C77D79481', 'C2F93346E27CE6AD1A9F8F5E3066F8326593A406BDF357ACB041E2F9AB402EFE', TransactionType.TRANSFER, @@ -41,11 +40,11 @@ describe('SignedTransaction', () => { it('should return aggregate transaction type', () => { const signedTransaction = new SignedTransaction( 'C3000000E854AA7D4466D66A7045F858F6D43022B7C72524B79A6D519431EEAC' + - 'CD020608B4672BB9B74168DAB04B55135F528187FB93E7AE6FAFB59A01C96F218' + - '0216308C2F93346E27CE6AD1A9F8F5E3066F8326593A406BDF357ACB041E2F9AB' + - '402EFE0290414100000000000000001FBFBDC00D0000004700000047000000C2F' + - '93346E27CE6AD1A9F8F5E3066F8326593A406BDF357ACB041E2F9AB402EFE0390' + - '5441900D8D3E65BF27ABE158BCD37C0A708BF6524A07EB09046A30030000004869', + 'CD020608B4672BB9B74168DAB04B55135F528187FB93E7AE6FAFB59A01C96F218' + + '0216308C2F93346E27CE6AD1A9F8F5E3066F8326593A406BDF357ACB041E2F9AB' + + '402EFE0290414100000000000000001FBFBDC00D0000004700000047000000C2F' + + '93346E27CE6AD1A9F8F5E3066F8326593A406BDF357ACB041E2F9AB402EFE0390' + + '5441900D8D3E65BF27ABE158BCD37C0A708BF6524A07EB09046A30030000004869', '231AA7700DC158CFC85606E0E2AC80F409923C6F3A845577C7D8D7A51A99E883', 'C2F93346E27CE6AD1A9F8F5E3066F8326593A406BDF357ACB041E2F9AB402EFE', TransactionType.AGGREGATE_COMPLETE, @@ -59,7 +58,7 @@ describe('SignedTransaction', () => { '8498B38D89C1DC8A448EA5824938FF828926CD9F7747B1844B59B4B6807E878', '8498B38D89C1DC8A448EA5824938FF828926CD9F7747B1844B59B4B6807E878BB', ].forEach((item) => { - it('throws exception if string hasn\'t 64 character long', () => { + it("throws exception if string hasn't 64 character long", () => { expect(() => { new SignedTransaction('', item, publicKey, TransactionType.AGGREGATE_BONDED, NetworkType.MIJIN_TEST); }).to.throw(Error); diff --git a/test/model/transaction/Transaction.spec.ts b/test/model/transaction/Transaction.spec.ts index 0f9de203b2..9902a9b4e8 100644 --- a/test/model/transaction/Transaction.spec.ts +++ b/test/model/transaction/Transaction.spec.ts @@ -31,7 +31,6 @@ import { TransferTransaction } from '../../../src/model/transaction/TransferTran import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; -// tslint:disable: no-use-before-declare describe('Transaction', () => { let account: Account; @@ -39,9 +38,31 @@ describe('Transaction', () => { account = TestingAccount; }); + class FakeTransaction extends Transaction { + public signWith(): SignedTransaction { + throw new Error('Method not implemented.'); + } + + protected generateBytes(): Uint8Array { + throw new Error('Not implemented'); + } + + public toEmbeddedTransaction(): EmbeddedTransactionBuilder { + throw new Error('Not implemented'); + } + resolveAliases(): TransferTransaction { + throw new Error('Not implemented'); + } + + setMaxFee(): TransferTransaction { + throw new Error('Not implemented'); + } + } + describe('isUnannounced', () => { it('should return true when there is no Transaction Info', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -56,7 +77,8 @@ describe('Transaction', () => { describe('isUnconfirmed', () => { it('should return true when height is 0', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -69,7 +91,8 @@ describe('Transaction', () => { }); it('should return false when height is not 0', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -84,7 +107,8 @@ describe('Transaction', () => { describe('isConfirmed', () => { it('should return true when height is not 0', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -99,7 +123,8 @@ describe('Transaction', () => { describe('hasMissingSignatures', () => { it('should return false when height is 0 and hash and markehash are different', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -114,7 +139,8 @@ describe('Transaction', () => { describe('reapplyGiven', () => { it('should throw an error if the transaction is announced', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -125,10 +151,11 @@ describe('Transaction', () => { ); expect(() => { transaction.reapplyGiven(Deadline.create()); - }).to.throws('an Announced transaction can\'t be modified'); + }).to.throws("an Announced transaction can't be modified"); }); it('should return a new transaction', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -141,7 +168,8 @@ describe('Transaction', () => { expect(newTransaction).to.not.equal(transaction); }); it('should overide deadline properly', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -162,7 +190,8 @@ describe('Transaction', () => { describe('toAggregate', () => { it('should throw exception when adding an aggregated transaction as inner transaction', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -175,7 +204,8 @@ describe('Transaction', () => { Deadline.create(), [transaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); expect(() => { aggregateTransaction.toAggregate(account.publicAccount); @@ -194,16 +224,16 @@ describe('Transaction', () => { ); const serialized = transaction.serialize(); - expect(serialized.substring( - 256, - serialized.length, - )).to.be.equal('9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D657373616765'); + expect(serialized.substring(256, serialized.length)).to.be.equal( + '9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D657373616765', + ); }); }); describe('size', () => { it('should return 128 for base transaction size', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -218,7 +248,8 @@ describe('Transaction', () => { describe('version', () => { it('should return version in hex format', () => { - const transaction = new FakeTransaction(TransactionType.TRANSFER, + const transaction = new FakeTransaction( + TransactionType.TRANSFER, NetworkType.MIJIN_TEST, 1, Deadline.create(), @@ -232,141 +263,100 @@ describe('Transaction', () => { }); describe('createTransactionHash() should', () => { - // shortcut - const knownPayload = ( - '970000000000000075DAC796D500CEFDFBD582BC6E0580401FE6DB02FBEA9367' - + '3DF47844246CDEA93715EB700F295A459E59D96A2BC6B7E36C79016A96B9FA38' - + '7E8B8937342FE30C6BE37B726EEE24C4B0E3C943E09A44691553759A89E92C4A' - + '84BBC4AD9AF5D49C0000000001984E4140420F0000000000E4B580B11A000000' - + 'A0860100000000002AD8FC018D9A49E100056576696173' - ); - - const knownAggregatePayload = ( - '0801000000000000AC1F3E0EE2C16F465CDC2E091DC44D6EB55F7FE3988A5F21' - + '309DF479BE6D3F0033E155695FB1133EA0EA64A67C1EDC2B430CFAF9722AF36B' - + 'AE84DBDB1C8F1509C2F93346E27CE6AD1A9F8F5E3066F8326593A406BDF357AC' - + 'B041E2F9AB402EFE000000000190414200000000000000006BA50FB91A000000' - + 'EA8F8301E7EDFD701F62E1DC1601ABDE22E5FCD11C9C7E7A01B87F8DFB6B62B0' - + '60000000000000005D00000000000000C2F93346E27CE6AD1A9F8F5E3066F832' - + '6593A406BDF357ACB041E2F9AB402EFE00000000019054419050B9837EFAB4BB' - + 'E8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D65' - + '7373616765000000' - ); + const knownPayload = + '970000000000000075DAC796D500CEFDFBD582BC6E0580401FE6DB02FBEA9367' + + '3DF47844246CDEA93715EB700F295A459E59D96A2BC6B7E36C79016A96B9FA38' + + '7E8B8937342FE30C6BE37B726EEE24C4B0E3C943E09A44691553759A89E92C4A' + + '84BBC4AD9AF5D49C0000000001984E4140420F0000000000E4B580B11A000000' + + 'A0860100000000002AD8FC018D9A49E100056576696173'; + + const knownAggregatePayload = + '0801000000000000AC1F3E0EE2C16F465CDC2E091DC44D6EB55F7FE3988A5F21' + + '309DF479BE6D3F0033E155695FB1133EA0EA64A67C1EDC2B430CFAF9722AF36B' + + 'AE84DBDB1C8F1509C2F93346E27CE6AD1A9F8F5E3066F8326593A406BDF357AC' + + 'B041E2F9AB402EFE000000000190414200000000000000006BA50FB91A000000' + + 'EA8F8301E7EDFD701F62E1DC1601ABDE22E5FCD11C9C7E7A01B87F8DFB6B62B0' + + '60000000000000005D00000000000000C2F93346E27CE6AD1A9F8F5E3066F832' + + '6593A406BDF357ACB041E2F9AB402EFE00000000019054419050B9837EFAB4BB' + + 'E8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D65' + + '7373616765000000'; // expected values const knownHash_sha3 = 'F0F5A62A0863D45E832B50EFF4E2F68157268A5D1674EC1068D82EC5F88D950B'; const generationHashBytes = Array.from(Convert.hexToUint8('988C4CDCE4D188013C13DE7914C7FD4D626169EF256722F61C52EFBE06BD5A2C')); const generationHashBytes_mt = Array.from(Convert.hexToUint8('17FA4747F5014B50413CCF968749604D728D7065DC504291EEE556899A534CBB')); - it ('create different hash given different signatures', () => { - const hash1 = Transaction.createTransactionHash( - knownPayload, - generationHashBytes, - NetworkType.MIJIN_TEST, - ); + it('create different hash given different signatures', () => { + const hash1 = Transaction.createTransactionHash(knownPayload, generationHashBytes); // modify signature part of the payload ; this must affect produced hash const tamperedSig = knownPayload.substr(0, 16) + '12' + knownPayload.substr(18); const hash2 = Transaction.createTransactionHash( tamperedSig, // replaced two first bytes of signature generationHashBytes, - NetworkType.MIJIN_TEST, ); expect(hash1).to.not.equal(hash2); }); - it ('create different hash given different signer public key', () => { - const hash1 = Transaction.createTransactionHash( - knownPayload, - generationHashBytes, - NetworkType.MIJIN_TEST, - ); + it('create different hash given different signer public key', () => { + const hash1 = Transaction.createTransactionHash(knownPayload, generationHashBytes); // modify signer public key part of the payload ; this must affect produced hash const tamperedSigner = knownPayload.substr(0, 16 + 128) + '12' + knownPayload.substr(16 + 128 + 2); const hash2 = Transaction.createTransactionHash( tamperedSigner, // replaced two first bytes of signer public key generationHashBytes, - NetworkType.MIJIN_TEST, ); expect(hash1).to.not.equal(hash2); }); - it ('create different hash given different generation hash', () => { - const hash1 = Transaction.createTransactionHash( - knownPayload, - generationHashBytes, - NetworkType.MIJIN_TEST, - ); + it('create different hash given different generation hash', () => { + const hash1 = Transaction.createTransactionHash(knownPayload, generationHashBytes); const hash2 = Transaction.createTransactionHash( knownPayload, generationHashBytes_mt, // uses different generation hash - NetworkType.MIJIN_TEST, ); expect(hash1).to.not.equal(hash2); }); - it ('create different hash given different transaction body', () => { - const hash1 = Transaction.createTransactionHash( - knownPayload, - generationHashBytes, - NetworkType.MIJIN_TEST, - ); + it('create different hash given different transaction body', () => { + const hash1 = Transaction.createTransactionHash(knownPayload, generationHashBytes); // modify "transaction body" part of payload ; this must affect produced transaction hash - const tamperedBody = knownAggregatePayload.substr(0, Transaction.Body_Index * 2) - + '12' + knownAggregatePayload.substr(Transaction.Body_Index * 2 + 2); + const tamperedBody = + knownAggregatePayload.substr(0, Transaction.Body_Index * 2) + + '12' + + knownAggregatePayload.substr(Transaction.Body_Index * 2 + 2); const hash2 = Transaction.createTransactionHash( tamperedBody, generationHashBytes, // uses different generation hash - NetworkType.MIJIN_TEST, ); expect(hash1).to.not.equal(hash2); }); - it ('create same hash given same payloads', () => { - const hash1 = Transaction.createTransactionHash( - knownPayload, - generationHashBytes, - NetworkType.MIJIN_TEST, - ); - const hash2 = Transaction.createTransactionHash( - knownPayload, - generationHashBytes, - NetworkType.MIJIN_TEST, - ); + it('create same hash given same payloads', () => { + const hash1 = Transaction.createTransactionHash(knownPayload, generationHashBytes); + const hash2 = Transaction.createTransactionHash(knownPayload, generationHashBytes); expect(hash1).to.equal(hash2); }); it('create correct SHA3 transaction hash given network type MIJIN or MIJIN_TEST', () => { - const hash1 = Transaction.createTransactionHash( - knownPayload, - generationHashBytes, - NetworkType.MIJIN_TEST, - ); - const hash2 = Transaction.createTransactionHash( - knownPayload, - generationHashBytes, - NetworkType.MIJIN, - ); + const hash1 = Transaction.createTransactionHash(knownPayload, generationHashBytes); + const hash2 = Transaction.createTransactionHash(knownPayload, generationHashBytes); expect(hash1).to.equal(knownHash_sha3); expect(hash2).to.equal(knownHash_sha3); }); it('hash only merkle transaction hash for aggregate transactions', () => { - const hash1 = Transaction.createTransactionHash( - knownAggregatePayload, - generationHashBytes, - NetworkType.MIJIN_TEST, - ); + const hash1 = Transaction.createTransactionHash(knownAggregatePayload, generationHashBytes); // modify end of payload ; this must not affect produced transaction hash // this test is valid only for Aggregate Transactions @@ -374,16 +364,16 @@ describe('Transaction', () => { const hashTamperedBody = Transaction.createTransactionHash( tamperedSize, // replace in size (header change should not affect hash) generationHashBytes, - NetworkType.MIJIN_TEST, ); // modify "merkle hash" part of payload ; this must affect produced transaction hash - const tamperedPayload = knownAggregatePayload.substr(0, Transaction.Body_Index * 2) - + '12' + knownAggregatePayload.substr(Transaction.Body_Index * 2 + 2); + const tamperedPayload = + knownAggregatePayload.substr(0, Transaction.Body_Index * 2) + + '12' + + knownAggregatePayload.substr(Transaction.Body_Index * 2 + 2); const hashTamperedMerkle = Transaction.createTransactionHash( tamperedPayload, // replace in merkle hash (will affect hash) generationHashBytes, - NetworkType.MIJIN_TEST, ); expect(hash1).to.equal(hashTamperedBody); @@ -391,24 +381,3 @@ describe('Transaction', () => { }); }); }); - -class FakeTransaction extends Transaction { - public signWith(account: Account): SignedTransaction { - throw new Error('Method not implemented.'); - } - - protected generateBytes(): Uint8Array { - throw new Error('Not implemented'); - } - - public toEmbeddedTransaction(): EmbeddedTransactionBuilder { - throw new Error('Not implemented'); - } - resolveAliases(): TransferTransaction { - throw new Error('Not implemented'); - } - - setMaxFee(): TransferTransaction { - throw new Error('Not implemented'); - } -} diff --git a/test/model/transaction/TransactionStatusError.spec.ts b/test/model/transaction/TransactionStatusError.spec.ts index 1d8ef285f9..ea62bcb62b 100644 --- a/test/model/transaction/TransactionStatusError.spec.ts +++ b/test/model/transaction/TransactionStatusError.spec.ts @@ -14,15 +14,14 @@ * limitations under the License. */ -import {deepEqual} from 'assert'; -import {expect} from 'chai'; -import {Address} from '../../../src/model/account/Address'; -import {Deadline} from '../../../src/model/transaction/Deadline'; -import {TransactionStatusError} from '../../../src/model/transaction/TransactionStatusError'; +import { deepEqual } from 'assert'; +import { expect } from 'chai'; +import { Address } from '../../../src/model/account/Address'; +import { Deadline } from '../../../src/model/transaction/Deadline'; +import { TransactionStatusError } from '../../../src/model/transaction/TransactionStatusError'; import { UInt64 } from '../../../src/model/UInt64'; describe('TransactionStatusError', () => { - it('should createComplete an TransactionStatusError object', () => { const statusInfoErrorDTO = { address: Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), @@ -34,7 +33,8 @@ describe('TransactionStatusError', () => { statusInfoErrorDTO.address, statusInfoErrorDTO.hash, statusInfoErrorDTO.code, - Deadline.createFromDTO(statusInfoErrorDTO.deadline)); + Deadline.createFromDTO(statusInfoErrorDTO.deadline), + ); expect(transactionStatusError.address).to.be.equal(statusInfoErrorDTO.address); expect(transactionStatusError.hash).to.be.equal(statusInfoErrorDTO.hash); diff --git a/test/model/transaction/TransactionType.spec.ts b/test/model/transaction/TransactionType.spec.ts index 4bdee13e2d..62b10910ab 100644 --- a/test/model/transaction/TransactionType.spec.ts +++ b/test/model/transaction/TransactionType.spec.ts @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {expect} from 'chai'; -import {TransactionType} from '../../../src/model/transaction/TransactionType'; +import { expect } from 'chai'; +import { TransactionType } from '../../../src/model/transaction/TransactionType'; describe('TransactionType', () => { it('Should match the specification', () => { expect(TransactionType.TRANSFER).to.be.equal(0x4154); - expect(TransactionType.NAMESPACE_REGISTRATION).to.be.equal(0x414E); - expect(TransactionType.MOSAIC_DEFINITION).to.be.equal(0x414D); - expect(TransactionType.MOSAIC_SUPPLY_CHANGE).to.be.equal(0x424D); + expect(TransactionType.NAMESPACE_REGISTRATION).to.be.equal(0x414e); + expect(TransactionType.MOSAIC_DEFINITION).to.be.equal(0x414d); + expect(TransactionType.MOSAIC_SUPPLY_CHANGE).to.be.equal(0x424d); expect(TransactionType.MULTISIG_ACCOUNT_MODIFICATION).to.be.equal(0x4155); expect(TransactionType.AGGREGATE_COMPLETE).to.be.equal(0x4141); expect(TransactionType.AGGREGATE_BONDED).to.be.equal(0x4241); diff --git a/test/model/transaction/TransferTransaction.spec.ts b/test/model/transaction/TransferTransaction.spec.ts index 19fd40c058..2d378e7e9d 100644 --- a/test/model/transaction/TransferTransaction.spec.ts +++ b/test/model/transaction/TransferTransaction.spec.ts @@ -15,7 +15,7 @@ */ import { expect } from 'chai'; -import {Convert} from '../../../src/core/format'; +import { Convert } from '../../../src/core/format'; import { CreateTransactionFromPayload } from '../../../src/infrastructure/transaction/CreateTransactionFromPayload'; import { Account } from '../../../src/model/account/Account'; import { Address } from '../../../src/model/account/Address'; @@ -33,8 +33,9 @@ import { ResolutionStatement } from '../../../src/model/receipt/ResolutionStatem import { Statement } from '../../../src/model/receipt/Statement'; import { Deadline } from '../../../src/model/transaction/Deadline'; import { TransferTransaction } from '../../../src/model/transaction/TransferTransaction'; -import {UInt64} from '../../../src/model/UInt64'; +import { UInt64 } from '../../../src/model/UInt64'; import { TestingAccount } from '../../conf/conf.spec'; +import { AggregateTransaction } from '../../../src/model/transaction/AggregateTransaction'; describe('TransferTransaction', () => { let account: Account; @@ -51,11 +52,18 @@ describe('TransferTransaction', () => { }); before(() => { account = TestingAccount; - statement = new Statement([], - [new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, - [new ResolutionEntry(account.address, new ReceiptSource(1, 0))])], - [new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, - [new ResolutionEntry(mosaicId, new ReceiptSource(1, 0))])], + statement = new Statement( + [], + [ + new ResolutionStatement(ResolutionType.Address, UInt64.fromUint(2), unresolvedAddress, [ + new ResolutionEntry(account.address, new ReceiptSource(1, 0)), + ]), + ], + [ + new ResolutionStatement(ResolutionType.Mosaic, UInt64.fromUint(2), unresolvedMosaicId, [ + new ResolutionEntry(mosaicId, new ReceiptSource(1, 0)), + ]), + ], ); }); @@ -102,19 +110,16 @@ describe('TransferTransaction', () => { const signedTransaction = transferTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D657373616765'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142000D000000000000746573742D6D657373616765', + ); }); it('should createComplete an TransferTransaction object and sign it with mosaics', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); @@ -126,12 +131,10 @@ describe('TransferTransaction', () => { const signedTransaction = transferTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal( + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( '9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142010D000000000044B262C46CEABB8500E1F' + - '5050000000000746573742D6D657373616765'); + '5050000000000746573742D6D657373616765', + ); }); it('should createComplete an TransferTransaction object with NamespaceId recipientAddress', () => { @@ -139,9 +142,7 @@ describe('TransferTransaction', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), addressAlias, - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); @@ -154,20 +155,17 @@ describe('TransferTransaction', () => { const signedTransaction = transferTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal('9151776168D24257D800000000000000000000000000000000010D000000000044B262C46CEABB8500E1F' + - '5050000000000746573742D6D657373616765'); + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( + '9151776168D24257D800000000000000000000000000000000010D000000000044B262C46CEABB8500E1F' + + '5050000000000746573742D6D657373616765', + ); }); it('should format TransferTransaction payload with 25 bytes binary address', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); @@ -177,19 +175,14 @@ describe('TransferTransaction', () => { const signedTransaction = transferTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - 306, - )).to.be.equal('9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142'); + expect(signedTransaction.payload.substring(256, 306)).to.be.equal('9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142'); }); it('should format TransferTransaction payload with 8 bytes binary namespaceId', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), new NamespaceId('nem.owner'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); @@ -199,10 +192,7 @@ describe('TransferTransaction', () => { const signedTransaction = transferTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - 306, - )).to.be.equal('9151776168D24257D800000000000000000000000000000000'); + expect(signedTransaction.payload.substring(256, 306)).to.be.equal('9151776168D24257D800000000000000000000000000000000'); }); describe('size', () => { @@ -210,9 +200,7 @@ describe('TransferTransaction', () => { const transaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('NEM'), NetworkType.MIJIN_TEST, ); @@ -225,9 +213,7 @@ describe('TransferTransaction', () => { const transferTransaction = TransferTransaction.create( Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), - [ - NetworkCurrencyLocal.createRelative(100), - ], + [NetworkCurrencyLocal.createRelative(100)], PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); @@ -239,12 +225,10 @@ describe('TransferTransaction', () => { const signedTransaction = transferTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - )).to.be.equal( + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length)).to.be.equal( '9050B9837EFAB4BBE8A4B9BB32D812F9885C00D8FC1650E142010D000000000044B262C46CEABB8500E1F' + - '5050000000000746573742D6D657373616765'); + '5050000000000746573742D6D657373616765', + ); }); it('should create Transafer transaction for persistent harvesting delegation request transaction', () => { @@ -252,8 +236,7 @@ describe('TransferTransaction', () => { Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), [], - PersistentHarvestingDelegationMessage - .create(delegatedPrivateKey, recipientPublicKey, NetworkType.MIJIN_TEST), + PersistentHarvestingDelegationMessage.create(delegatedPrivateKey, recipientPublicKey, NetworkType.MIJIN_TEST), NetworkType.MIJIN_TEST, ); @@ -265,23 +248,19 @@ describe('TransferTransaction', () => { Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), [], - PersistentHarvestingDelegationMessage - .create(delegatedPrivateKey, recipientPublicKey, NetworkType.MIJIN_TEST), + PersistentHarvestingDelegationMessage.create(delegatedPrivateKey, recipientPublicKey, NetworkType.MIJIN_TEST), NetworkType.MIJIN_TEST, ); expect(transferTransaction.message.payload.length).to.be.equal(192 + messageMarker.length); expect(transferTransaction.message.payload.includes(messageMarker)).to.be.true; expect(transferTransaction.mosaics.length).to.be.equal(0); expect(transferTransaction.recipientAddress).to.be.instanceof(Address); - expect((transferTransaction.recipientAddress as Address).plain()) - .to.be.equal('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); + expect((transferTransaction.recipientAddress as Address).plain()).to.be.equal('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'); const signedTransaction = transferTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 256, - signedTransaction.payload.length, - ).includes(transferTransaction.message.payload)).to.be.true; + expect(signedTransaction.payload.substring(256, signedTransaction.payload.length).includes(transferTransaction.message.payload)).to + .be.true; }); it('should throw exception with mosaic provided when creating persistentDelegationRequestTransaction', () => { @@ -290,8 +269,7 @@ describe('TransferTransaction', () => { Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), [NetworkCurrencyLocal.createRelative(100)], - PersistentHarvestingDelegationMessage - .create(delegatedPrivateKey, recipientPublicKey, NetworkType.MIJIN_TEST), + PersistentHarvestingDelegationMessage.create(delegatedPrivateKey, recipientPublicKey, NetworkType.MIJIN_TEST), NetworkType.MIJIN_TEST, ); }).to.throw(Error, 'PersistentDelegationRequestTransaction should be created without Mosaic'); @@ -303,7 +281,7 @@ describe('TransferTransaction', () => { Deadline.create(), Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), [NetworkCurrencyLocal.createRelative(100)], - PersistentHarvestingDelegationMessage.create('abc', recipientPublicKey, NetworkType.MIJIN_TEST), + PersistentHarvestingDelegationMessage.create('abc', recipientPublicKey, NetworkType.MIJIN_TEST), NetworkType.MIJIN_TEST, ); }).to.throw(); @@ -340,11 +318,9 @@ describe('TransferTransaction', () => { const signedTransaction = transferTransaction.signWith(account, generationHash); - expect(signedTransaction.payload.substring( - 320, - 384, - )).to.be.equal( - '64000000000000000000000000000000C8000000000000000000000000000000'); + expect(signedTransaction.payload.substring(320, 384)).to.be.equal( + '64000000000000000000000000000000C8000000000000000000000000000000', + ); const sorted = CreateTransactionFromPayload(signedTransaction.payload) as TransferTransaction; expect(sorted.mosaics[0].id.id.compact()).to.be.equal(100); @@ -375,12 +351,10 @@ describe('TransferTransaction', () => { expect(sorted.mosaics[0].id.toHex()).to.be.equal('67F2B76F28BD36BA'); expect(sorted.mosaics[1].id.toHex()).to.be.equal('77A1969932D987D7'); expect(sorted.mosaics[2].id.toHex()).to.be.equal('D525AD41D95FCF29'); - }); it('Test Serialization and Deserialization Using namespaceIds', () => { const namespaceId = new NamespaceId('testaccount2'); -​ const transferTransaction = TransferTransaction.create( Deadline.createFromDTO('1'), namespaceId, @@ -388,11 +362,9 @@ describe('TransferTransaction', () => { PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ); -​ const payload = transferTransaction.serialize(); const newTransaction = CreateTransactionFromPayload(payload) as TransferTransaction; const newPayload = newTransaction.serialize(); -​ expect(newPayload).to.be.equal(payload); expect(newTransaction.recipientToString()).to.be.equal(transferTransaction.recipientToString()); }); @@ -405,13 +377,31 @@ describe('TransferTransaction', () => { PlainMessage.create('test-message'), NetworkType.MIJIN_TEST, ).setMaxFee(2); -​ expect(transferTransaction.maxFee.compact()).to.be.equal(378); const signedTransaction = transferTransaction.signWith(account, generationHash); expect(signedTransaction.hash).not.to.be.undefined; }); + it('Test set maxFee using multiplier to throw', () => { + const transferTransaction = TransferTransaction.create( + Deadline.create(), + Address.createFromRawAddress('SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC'), + [NetworkCurrencyLocal.createAbsolute(1)], + PlainMessage.create('test-message'), + NetworkType.MIJIN_TEST, + ); + + expect(() => { + AggregateTransaction.createComplete( + Deadline.create(), + [transferTransaction.toAggregate(account.publicAccount)], + NetworkType.MIJIN_TEST, + [], + ).setMaxFee(2); + }).to.throw(); + }); + it('Test resolveAlias can resolve', () => { const transferTransaction = new TransferTransaction( NetworkType.MIJIN_TEST, @@ -423,8 +413,8 @@ describe('TransferTransaction', () => { PlainMessage.create('test'), '', account.publicAccount, - new TransactionInfo(UInt64.fromUint(2), 0, '')).resolveAliases(statement); -​ + new TransactionInfo(UInt64.fromUint(2), 0, ''), + ).resolveAliases(statement); expect(transferTransaction.recipientAddress instanceof Address).to.be.true; expect(transferTransaction.mosaics[0].id instanceof MosaicId).to.be.true; expect((transferTransaction.recipientAddress as Address).equals(account.address)).to.be.true; diff --git a/test/model/wallet/EncryptedPrivateKey.spec.ts b/test/model/wallet/EncryptedPrivateKey.spec.ts deleted file mode 100644 index 0eee3a13b8..0000000000 --- a/test/model/wallet/EncryptedPrivateKey.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2018 NEM - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import {expect} from 'chai'; -import {EncryptedPrivateKey} from '../../../src/model/wallet/EncryptedPrivateKey'; -import {Password} from '../../../src/model/wallet/Password'; - -describe('EncryptedPrivateKey', () => { - - it('should createComplete a private key encrypted object', () => { - const privateKeyEncrypted = new EncryptedPrivateKey( - 'b6edb40bae6d099f099775bc828e36961f7fbb5e3ee62236714ad1e980ac8986bd4ed690f576abb5268ba0915ae575e7', - '4344645752e57065f814b51713d05810'); - expect(privateKeyEncrypted.encryptedKey) - .to.be.equal('b6edb40bae6d099f099775bc828e36961f7fbb5e3ee62236714ad1e980ac8986bd4ed690f576abb5268ba0915ae575e7'); - expect(privateKeyEncrypted.iv).to.be.equal('4344645752e57065f814b51713d05810'); - }); - - it('should decrypt a private key encrypted object', () => { - const privateKeyEncrypted = new EncryptedPrivateKey( - 'b6edb40bae6d099f099775bc828e36961f7fbb5e3ee62236714ad1e980ac8986bd4ed690f576abb5268ba0915ae575e7', - '4344645752e57065f814b51713d05810'); - const privateKeyDecrypted = privateKeyEncrypted.decrypt(new Password('password')); - expect(privateKeyDecrypted).to.be.equal('e85467d94fdf70b5713d3b3b083597e0962f38843feb10259158a3fa6dc444b6'); - }); -}); diff --git a/test/model/wallet/Password.spec.ts b/test/model/wallet/Password.spec.ts index c072ed29ae..e36247899f 100644 --- a/test/model/wallet/Password.spec.ts +++ b/test/model/wallet/Password.spec.ts @@ -14,11 +14,10 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Password} from '../../../src/model/wallet/Password'; +import { expect } from 'chai'; +import { Password } from '../../../src/model/wallet/Password'; describe('Password', () => { - it('should throw Error if Password is empty', () => { expect(() => { new Password(''); diff --git a/test/model/wallet/SimpleWallet.spec.ts b/test/model/wallet/SimpleWallet.spec.ts index 4e5362c57d..1a4475696d 100644 --- a/test/model/wallet/SimpleWallet.spec.ts +++ b/test/model/wallet/SimpleWallet.spec.ts @@ -1,5 +1,5 @@ /* - * Copyright 2018 NEM + * Copyright 2020 NEM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,26 +14,26 @@ * limitations under the License. */ -import {expect} from 'chai'; -import {Account} from '../../../src/model/account/Account'; -import {NetworkType} from '../../../src/model/network/NetworkType'; -import {Password} from '../../../src/model/wallet/Password'; -import {SimpleWallet} from '../../../src/model/wallet/SimpleWallet'; +import { expect } from 'chai'; +import { Account } from '../../../src/model/account/Account'; +import { NetworkType } from '../../../src/model/network/NetworkType'; +import { Password } from '../../../src/model/wallet/Password'; +import { SimpleWallet } from '../../../src/model/wallet/SimpleWallet'; describe('SimpleWallet', () => { - it('should createComplete a new simple wallet', () => { + it('should create a new simple wallet', () => { const simpleWallet = SimpleWallet.create('wallet-name', new Password('password'), NetworkType.MIJIN_TEST); expect(simpleWallet.name).to.be.equal('wallet-name'); - expect(simpleWallet.network).to.be.equal(NetworkType.MIJIN_TEST); - expect(simpleWallet.schema).to.be.equal('simple_v1'); + expect(simpleWallet.networkType).to.be.equal(NetworkType.MIJIN_TEST); + expect(simpleWallet.schema).to.be.equal('simple_v2'); }); - it('should createComplete a new wallet with privateKey', () => { + it('should create a new wallet with privateKey', () => { const privateKey = '5149a02ca2b2610138376717daaff8477f1639796aa108b7eee83e99e585b250'; const account = Account.createFromPrivateKey(privateKey, NetworkType.MIJIN_TEST); const simpleWallet = SimpleWallet.createFromPrivateKey('wallet-name', new Password('password'), privateKey, NetworkType.MIJIN_TEST); expect(simpleWallet.name).to.be.equal('wallet-name'); - expect(simpleWallet.network).to.be.equal(NetworkType.MIJIN_TEST); + expect(simpleWallet.networkType).to.be.equal(NetworkType.MIJIN_TEST); expect(simpleWallet.address.plain()).to.be.equal(account.address.plain()); }); @@ -65,7 +65,7 @@ describe('SimpleWallet', () => { const privateKey = '5149a02ca2b2610138376717daaff8477f1639796aa108b7eee83e99e585b250'; const password = new Password('password'); const simpleWallet = SimpleWallet.createFromPrivateKey('wallet-name', password, privateKey, NetworkType.MIJIN_TEST); - const simpleWalletDTO = simpleWallet.toDTO() - expect(simpleWalletDTO).to.deep.equal(JSON.parse(JSON.stringify(simpleWallet))) - }) + const simpleWalletDTO = simpleWallet.toDTO(); + expect(simpleWalletDTO).to.deep.equal(JSON.parse(JSON.stringify(simpleWallet))); + }); }); diff --git a/test/resource/TestResources.ts b/test/resource/TestResources.ts index fc844192c7..2ad0c456b7 100644 --- a/test/resource/TestResources.ts +++ b/test/resource/TestResources.ts @@ -1,4 +1,4 @@ -export const getDummyNetworkProperties = () => { +export const getDummyNetworkProperties = (): any => { return JSON.parse(`{ "network": { "identifier": "public-test", @@ -88,4 +88,4 @@ export const getDummyNetworkProperties = () => { } } }`); - }; +}; diff --git a/test/service/AccountService.spec.ts b/test/service/AccountService.spec.ts new file mode 100644 index 0000000000..4a8dcc128d --- /dev/null +++ b/test/service/AccountService.spec.ts @@ -0,0 +1,190 @@ +/* + * Copyright 2020 NEM + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { expect } from 'chai'; +import { of as observableOf } from 'rxjs'; +import { deepEqual, instance, mock, when } from 'ts-mockito'; +import { RepositoryFactory } from '../../src/infrastructure/RepositoryFactory'; +import { Account } from '../../src/model/account/Account'; +import { UInt64 } from '../../src/model/UInt64'; +import { TestingAccount, MultisigAccount } from '../conf/conf.spec'; +import { AccountService } from '../../src/service/AccountService'; +import { AccountRepository } from '../../src/infrastructure/AccountRepository'; +import { NamespaceRepository } from '../../src/infrastructure/NamespaceRepository'; +import { AccountInfo } from '../../src/model/account/AccountInfo'; +import { AccountType } from '../../src/model/account/AccountType'; +import { ActivityBucket } from '../../src/model/account/ActivityBucket'; +import { NetworkCurrencyLocal } from '../../src/model/mosaic/NetworkCurrencyLocal'; +import { NetworkCurrencyPublic } from '../../src/model/mosaic/NetworkCurrencyPublic'; +import { NetworkHarvestLocal } from '../../src/model/mosaic/NetworkHarvestLocal'; +import { NamespaceInfo } from '../../src/model/namespace/NamespaceInfo'; +import { NamespaceId } from '../../src/model/namespace/NamespaceId'; +import { MosaicAlias } from '../../src/model/namespace/MosaicAlias'; +import { MosaicId } from '../../src/model/mosaic/MosaicId'; +import { NamespaceName } from '../../src/model/namespace/NamespaceName'; +import { Mosaic } from '../../src/model/mosaic/Mosaic'; + +describe('AccountService', () => { + let accountService: AccountService; + let account: Account; + let account2: Account; + + function mockAccountInfo(withMosaic = false): AccountInfo[] { + const mosaic = new Mosaic(new MosaicId('941299B2B7E1291C'), UInt64.fromUint(1)); + const mosaics = [ + NetworkCurrencyLocal.createAbsolute(1), + NetworkCurrencyPublic.createAbsolute(1), + NetworkHarvestLocal.createAbsolute(1), + ]; + if (withMosaic) { + mosaics.push(mosaic); + } + return [ + new AccountInfo( + account.address, + UInt64.fromUint(100), + account.publicKey, + UInt64.fromUint(100), + AccountType.Main, + '0', + [new ActivityBucket('0', 1, 1, 1)], + mosaics, + UInt64.fromUint(100), + UInt64.fromUint(100), + ), + ]; + } + + function mockNamespaceInfo(): NamespaceInfo[] { + return [ + new NamespaceInfo( + true, + 0, + 'id', + 1, + 1, + [NetworkCurrencyLocal.NAMESPACE_ID], + NamespaceId.createFromEncoded('0000000000000000'), + account.publicAccount, + UInt64.fromUint(10), + UInt64.fromUint(20), + new MosaicAlias(new MosaicId('30BBEA6CC462B244')), + ), + new NamespaceInfo( + true, + 0, + 'id', + 1, + 1, + [NetworkCurrencyPublic.NAMESPACE_ID], + NamespaceId.createFromEncoded('0000000000000000'), + account.publicAccount, + UInt64.fromUint(10), + UInt64.fromUint(20), + new MosaicAlias(new MosaicId('31BBEA6CC462B244')), + ), + new NamespaceInfo( + true, + 0, + 'id', + 1, + 1, + [NetworkHarvestLocal.NAMESPACE_ID], + NamespaceId.createFromEncoded('0000000000000000'), + account.publicAccount, + UInt64.fromUint(10), + UInt64.fromUint(20), + new MosaicAlias(new MosaicId('32BBEA6CC462B244')), + ), + ]; + } + + function mockNamespaceName(id: NamespaceId, name: string): NamespaceName { + return new NamespaceName(id, name); + } + + before(() => { + account = TestingAccount; + account2 = MultisigAccount; + const mockAccountRepository = mock(); + const mockNamespaceRepository = mock(); + const mockRepoFactory = mock(); + + when(mockAccountRepository.getAccountsInfo(deepEqual([account.address]))).thenReturn(observableOf(mockAccountInfo())); + when(mockAccountRepository.getAccountsInfo(deepEqual([account2.address]))).thenReturn(observableOf(mockAccountInfo(true))); + when(mockNamespaceRepository.getNamespacesFromAccounts(deepEqual([account.address]))).thenReturn(observableOf(mockNamespaceInfo())); + when(mockNamespaceRepository.getNamespacesFromAccounts(deepEqual([account2.address]))).thenReturn( + observableOf(mockNamespaceInfo()), + ); + + when(mockNamespaceRepository.getNamespacesName(deepEqual([NetworkCurrencyLocal.NAMESPACE_ID]))).thenReturn( + observableOf([mockNamespaceName(NetworkCurrencyLocal.NAMESPACE_ID, 'catapult.currency')]), + ); + when(mockNamespaceRepository.getNamespacesName(deepEqual([NetworkCurrencyPublic.NAMESPACE_ID]))).thenReturn( + observableOf([mockNamespaceName(NetworkCurrencyPublic.NAMESPACE_ID, 'symbol.xym')]), + ); + when(mockNamespaceRepository.getNamespacesName(deepEqual([NetworkHarvestLocal.NAMESPACE_ID]))).thenReturn( + observableOf([mockNamespaceName(NetworkHarvestLocal.NAMESPACE_ID, 'catapult.harvest')]), + ); + + when( + mockNamespaceRepository.getNamespacesName( + deepEqual([NetworkCurrencyLocal.NAMESPACE_ID, NetworkCurrencyPublic.NAMESPACE_ID, NetworkHarvestLocal.NAMESPACE_ID]), + ), + ).thenReturn( + observableOf([ + mockNamespaceName(NetworkCurrencyLocal.NAMESPACE_ID, 'catapult.currency'), + mockNamespaceName(NetworkCurrencyPublic.NAMESPACE_ID, 'symbol.xym'), + mockNamespaceName(NetworkHarvestLocal.NAMESPACE_ID, 'catapult.harvest'), + ]), + ); + + const accountRepository = instance(mockAccountRepository); + const namespaceRepository = instance(mockNamespaceRepository); + + when(mockRepoFactory.createAccountRepository()).thenReturn(accountRepository); + when(mockRepoFactory.createNamespaceRepository()).thenReturn(namespaceRepository); + const repoFactory = instance(mockRepoFactory); + accountService = new AccountService(repoFactory); + }); + + it('should return accountInfo with resolved mosaic name', async () => { + const result = await accountService.accountInfoWithResolvedMosaic([account.address]).toPromise(); + expect(result[0].resolvedMosaics).to.not.be.undefined; + expect(result[0].resolvedMosaics![0].namespaceName?.name).to.be.equal('catapult.currency'); + expect(result[0].resolvedMosaics![1].namespaceName?.name).to.be.equal('symbol.xym'); + expect(result[0].resolvedMosaics![2].namespaceName?.name).to.be.equal('catapult.harvest'); + }); + + it('should return accountInfo with mosaicId', async () => { + const result = await accountService.accountInfoWithResolvedMosaic([account2.address]).toPromise(); + expect(result[0].resolvedMosaics).to.not.be.undefined; + expect(result[0].resolvedMosaics![0].namespaceName?.name).to.be.equal('catapult.currency'); + expect(result[0].resolvedMosaics![1].namespaceName?.name).to.be.equal('symbol.xym'); + expect(result[0].resolvedMosaics![2].namespaceName?.name).to.be.equal('catapult.harvest'); + expect(result[0].resolvedMosaics![3]).to.not.be.undefined; + expect(result[0].resolvedMosaics![3].namespaceName).to.be.undefined; + }); + + it('should return namespaceInfo with resolved name', async () => { + const result = await accountService.accountNamespacesWithName([account.address]).toPromise(); + expect(result).to.not.be.undefined; + expect(result.length).to.be.greaterThan(0); + expect(result![0].namespaceName).to.be.equal('catapult.currency'); + expect(result![1].namespaceName).to.be.equal('symbol.xym'); + expect(result![2].namespaceName).to.be.equal('catapult.harvest'); + }); +}); diff --git a/test/service/AggregateTransactionService.spec.ts b/test/service/AggregateTransactionService.spec.ts index 5808745618..dabbfb4d85 100644 --- a/test/service/AggregateTransactionService.spec.ts +++ b/test/service/AggregateTransactionService.spec.ts @@ -16,8 +16,8 @@ import { expect } from 'chai'; import { ChronoUnit } from 'js-joda'; -import {of as observableOf} from 'rxjs'; -import {deepEqual, instance, mock, when} from 'ts-mockito'; +import { of as observableOf } from 'rxjs'; +import { deepEqual, instance, mock, when } from 'ts-mockito'; import { MultisigRepository } from '../../src/infrastructure/MultisigRepository'; import { Account } from '../../src/model/account/Account'; @@ -25,12 +25,15 @@ import { Address } from '../../src/model/account/Address'; import { MultisigAccountGraphInfo } from '../../src/model/account/MultisigAccountGraphInfo'; import { MultisigAccountInfo } from '../../src/model/account/MultisigAccountInfo'; import { PlainMessage } from '../../src/model/message/PlainMessage'; -import {NetworkType} from '../../src/model/network/NetworkType'; +import { NetworkType } from '../../src/model/network/NetworkType'; import { AggregateTransaction } from '../../src/model/transaction/AggregateTransaction'; import { Deadline } from '../../src/model/transaction/Deadline'; import { MultisigAccountModificationTransaction } from '../../src/model/transaction/MultisigAccountModificationTransaction'; import { TransferTransaction } from '../../src/model/transaction/TransferTransaction'; import { AggregateTransactionService } from '../../src/service/AggregateTransactionService'; +import { RepositoryFactory } from '../../src/infrastructure/RepositoryFactory'; +import { NetworkRepository } from '../../src/infrastructure/NetworkRepository'; +import { NetworkConfigurationDTO, PluginsPropertiesDTO, AggregateNetworkPropertiesDTO } from 'symbol-openapi-typescript-node-client'; /** * For multi level multisig scenario visit: https://github.com/nemtech/symbol-docs/issues/10 @@ -49,54 +52,126 @@ describe('AggregateTransactionService', () => { * Private Key: 8B0622C2CCFC5CCC5A74B500163E3C68F3AD3643DB12932FC931143EAC67280D */ - /** - * Test accounts: - * Multisig1 (1/1): Account2, Account3 - * Multisig2 (2/1): Account1, Multisig1 - * Multisig3 (2/2): Account2, Account3 - * Stranger Account: Account4 - */ - - const account1 = Account.createFromPrivateKey('82DB2528834C9926F0FCCE042466B24A266F5B685CB66D2869AF6648C043E950', - NetworkType.MIJIN_TEST); - const multisig1 = Account.createFromPrivateKey('8B0622C2CCFC5CCC5A74B500163E3C68F3AD3643DB12932FC931143EAC67280D', - NetworkType.MIJIN_TEST); - const multisig2 = Account.createFromPrivateKey('22A1D67F8519D1A45BD7116600BB6E857786E816FE0B45E4C5B9FFF3D64BC177', - NetworkType.MIJIN_TEST); - - const multisig3 = Account.createFromPrivateKey('5E7812AB0E709ABC45466034E1A209099F6A12C4698748A63CDCAA9B0DDE1DBD', - NetworkType.MIJIN_TEST); - const account2 = Account.createFromPrivateKey('A4D410270E01CECDCDEADCDE32EC79C8D9CDEA4DCD426CB1EB666EFEF148FBCE', - NetworkType.MIJIN_TEST); - const account3 = Account.createFromPrivateKey('336AB45EE65A6AFFC0E7ADC5342F91E34BACA0B901A1D9C876FA25A1E590077E', - NetworkType.MIJIN_TEST); - - const account4 = Account.createFromPrivateKey('4D8B3756592532753344E11E2B7541317BCCFBBCF4444274CDBF359D2C4AE0F1', - NetworkType.MIJIN_TEST); + /** + * Test accounts: + * Multisig1 (1/1): Account2, Account3 + * Multisig2 (2/1): Account1, Multisig1 + * Multisig3 (2/2): Account2, Account3 + * Stranger Account: Account4 + */ + + const account1 = Account.createFromPrivateKey( + '82DB2528834C9926F0FCCE042466B24A266F5B685CB66D2869AF6648C043E950', + NetworkType.MIJIN_TEST, + ); + const multisig1 = Account.createFromPrivateKey( + '8B0622C2CCFC5CCC5A74B500163E3C68F3AD3643DB12932FC931143EAC67280D', + NetworkType.MIJIN_TEST, + ); + const multisig2 = Account.createFromPrivateKey( + '22A1D67F8519D1A45BD7116600BB6E857786E816FE0B45E4C5B9FFF3D64BC177', + NetworkType.MIJIN_TEST, + ); + + const multisig3 = Account.createFromPrivateKey( + '5E7812AB0E709ABC45466034E1A209099F6A12C4698748A63CDCAA9B0DDE1DBD', + NetworkType.MIJIN_TEST, + ); + const account2 = Account.createFromPrivateKey( + 'A4D410270E01CECDCDEADCDE32EC79C8D9CDEA4DCD426CB1EB666EFEF148FBCE', + NetworkType.MIJIN_TEST, + ); + const account3 = Account.createFromPrivateKey( + '336AB45EE65A6AFFC0E7ADC5342F91E34BACA0B901A1D9C876FA25A1E590077E', + NetworkType.MIJIN_TEST, + ); + + const account4 = Account.createFromPrivateKey( + '4D8B3756592532753344E11E2B7541317BCCFBBCF4444274CDBF359D2C4AE0F1', + NetworkType.MIJIN_TEST, + ); const generationHash = '57F7DA205008026C776CB6AED843393F04CD458E0AA2D9F1D5F31A402072B2D6'; + function givenMultisig2AccountInfo(): MultisigAccountInfo { + return new MultisigAccountInfo(multisig2.publicAccount, 2, 1, [multisig1.publicAccount, account1.publicAccount], []); + } + function givenMultisig3AccountInfo(): MultisigAccountInfo { + return new MultisigAccountInfo(multisig3.publicAccount, 2, 2, [account2.publicAccount, account3.publicAccount], []); + } + + function givenAccount1Info(): MultisigAccountInfo { + return new MultisigAccountInfo(account1.publicAccount, 0, 0, [], [multisig2.publicAccount]); + } + function givenAccount2Info(): MultisigAccountInfo { + return new MultisigAccountInfo(account2.publicAccount, 0, 0, [], [multisig2.publicAccount, multisig3.publicAccount]); + } + function givenAccount3Info(): MultisigAccountInfo { + return new MultisigAccountInfo(account3.publicAccount, 0, 0, [], [multisig2.publicAccount, multisig3.publicAccount]); + } + function givenAccount4Info(): MultisigAccountInfo { + return new MultisigAccountInfo(account4.publicAccount, 0, 0, [], []); + } + + function givenMultisig2AccountGraphInfo(): MultisigAccountGraphInfo { + const map = new Map(); + map.set(0, [new MultisigAccountInfo(multisig2.publicAccount, 2, 1, [multisig1.publicAccount, account1.publicAccount], [])]).set(1, [ + new MultisigAccountInfo( + multisig1.publicAccount, + 1, + 1, + [account2.publicAccount, account3.publicAccount], + [multisig2.publicAccount], + ), + ]); + + return new MultisigAccountGraphInfo(map); + } + + function givenMultisig3AccountGraphInfo(): MultisigAccountGraphInfo { + const map = new Map(); + map.set(0, [new MultisigAccountInfo(multisig3.publicAccount, 2, 2, [account2.publicAccount, account3.publicAccount], [])]); + + return new MultisigAccountGraphInfo(map); + } + + function getNetworkProperties(input: string): NetworkConfigurationDTO { + const body = new NetworkConfigurationDTO(); + const plugin = new PluginsPropertiesDTO(); + plugin.aggregate = new AggregateNetworkPropertiesDTO(); + plugin.aggregate.maxCosignaturesPerAggregate = input; + body.plugins = plugin; + return body; + } + + let mockNetworkRepository: NetworkRepository; before(() => { - const mockedAccountRepository: MultisigRepository = mock(); - - when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(account1.address))) - .thenReturn(observableOf(givenAccount1Info())); - when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(account4.address))) - .thenReturn(observableOf(givenAccount4Info())); - when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(multisig2.address))) - .thenReturn(observableOf(givenMultisig2AccountInfo())); - when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(multisig3.address))) - .thenReturn(observableOf(givenMultisig3AccountInfo())); - when(mockedAccountRepository.getMultisigAccountGraphInfo(deepEqual(multisig2.address))) - .thenReturn(observableOf(givenMultisig2AccountGraphInfo())); - when(mockedAccountRepository.getMultisigAccountGraphInfo(deepEqual(multisig3.address))) - .thenReturn(observableOf(givenMultisig3AccountGraphInfo())); - when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(account2.address))) - .thenReturn(observableOf(givenAccount2Info())); - when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(account3.address))) - .thenReturn(observableOf(givenAccount3Info())); + mockNetworkRepository = mock(); + const mockRepoFactory = mock(); + const mockedAccountRepository: MultisigRepository = mock(); + + when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(account1.address))).thenReturn(observableOf(givenAccount1Info())); + when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(account4.address))).thenReturn(observableOf(givenAccount4Info())); + when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(multisig2.address))).thenReturn( + observableOf(givenMultisig2AccountInfo()), + ); + when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(multisig3.address))).thenReturn( + observableOf(givenMultisig3AccountInfo()), + ); + when(mockedAccountRepository.getMultisigAccountGraphInfo(deepEqual(multisig2.address))).thenReturn( + observableOf(givenMultisig2AccountGraphInfo()), + ); + when(mockedAccountRepository.getMultisigAccountGraphInfo(deepEqual(multisig3.address))).thenReturn( + observableOf(givenMultisig3AccountGraphInfo()), + ); + when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(account2.address))).thenReturn(observableOf(givenAccount2Info())); + when(mockedAccountRepository.getMultisigAccountInfo(deepEqual(account3.address))).thenReturn(observableOf(givenAccount3Info())); const accountRepository = instance(mockedAccountRepository); - aggregateTransactionService = new AggregateTransactionService(accountRepository); + const networkRespository = instance(mockNetworkRepository); + const repoFactory = instance(mockRepoFactory); + when(mockRepoFactory.createMultisigRepository()).thenReturn(accountRepository); + when(mockRepoFactory.createNetworkRepository()).thenReturn(networkRespository); + aggregateTransactionService = new AggregateTransactionService(repoFactory); }); it('should return isComplete: true for aggregated complete transaction - 2 levels Multisig', () => { @@ -120,12 +195,16 @@ describe('AggregateTransactionService', () => { Deadline.create(), [transferTransaction.toAggregate(multisig2.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account1, [account2], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.true; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.true; + }); }); it('should return isComplete: false for aggregated complete transaction - 2 levels Multisig', () => { @@ -149,12 +228,16 @@ describe('AggregateTransactionService', () => { Deadline.create(), [transferTransaction.toAggregate(multisig2.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account1, [], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.false; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.false; + }); }); it('should return isComplete: false for aggregated complete transaction - 2 levels Multisig', () => { @@ -178,12 +261,16 @@ describe('AggregateTransactionService', () => { Deadline.create(), [transferTransaction.toAggregate(multisig2.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account1, [account4], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.false; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.false; + }); }); it('should return correct isComplete status for aggregated complete transaction - 2 levels Multisig, multi inner transaction', () => { @@ -214,14 +301,17 @@ describe('AggregateTransactionService', () => { const aggregateTransaction = AggregateTransaction.createComplete( Deadline.create(), - [transferTransaction.toAggregate(multisig2.publicAccount), - transferTransaction2.toAggregate(account4.publicAccount)], + [transferTransaction.toAggregate(multisig2.publicAccount), transferTransaction2.toAggregate(account4.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account1, [account4], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.false; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.false; + }); }); it('should return correct isComplete status for aggregated complete transaction - 2 levels Multisig, multi inner transaction', () => { @@ -252,14 +342,17 @@ describe('AggregateTransactionService', () => { const aggregateTransaction = AggregateTransaction.createComplete( Deadline.create(), - [transferTransaction.toAggregate(multisig2.publicAccount), - transferTransaction2.toAggregate(account4.publicAccount)], + [transferTransaction.toAggregate(multisig2.publicAccount), transferTransaction2.toAggregate(account4.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account1, [account4, account2], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.true; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.true; + }); }); it('should use minRemoval for multisig account validation if inner transaction is modify multisig remove', () => { @@ -282,11 +375,15 @@ describe('AggregateTransactionService', () => { Deadline.create(), [modifyMultisigTransaction.toAggregate(multisig2.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signWith(account2, generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.true; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.true; + }); }); it('should return correct isComplete status (false) for aggregated complete transaction - none multisig', () => { @@ -308,12 +405,16 @@ describe('AggregateTransactionService', () => { Deadline.create(), [transferTransaction.toAggregate(account4.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signWith(account1, generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.false; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.false; + }); }); it('should return correct isComplete status (true) for aggregated complete transaction - none multisig', () => { @@ -336,12 +437,16 @@ describe('AggregateTransactionService', () => { Deadline.create(), [transferTransaction.toAggregate(account4.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signWith(account4, generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.true; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.true; + }); }); it('should return correct isComplete status TRUE - multiple normal account', () => { @@ -376,15 +481,18 @@ describe('AggregateTransactionService', () => { const aggregateTransaction = AggregateTransaction.createComplete( Deadline.create(), - [transferTransaction.toAggregate(account4.publicAccount), - transferTransaction2.toAggregate(account1.publicAccount)], + [transferTransaction.toAggregate(account4.publicAccount), transferTransaction2.toAggregate(account1.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account1, [account4], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.true; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.true; + }); }); it('should return correct isComplete status FALSE - multiple normal account', () => { @@ -418,15 +526,18 @@ describe('AggregateTransactionService', () => { const aggregateTransaction = AggregateTransaction.createComplete( Deadline.create(), - [transferTransaction.toAggregate(account4.publicAccount), - transferTransaction2.toAggregate(account1.publicAccount)], + [transferTransaction.toAggregate(account4.publicAccount), transferTransaction2.toAggregate(account1.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account1, [], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.false; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.false; + }); }); it('should return correct isComplete status TRUE - multisig Single Level', () => { @@ -447,12 +558,16 @@ describe('AggregateTransactionService', () => { Deadline.create(), [transferTransaction.toAggregate(multisig3.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account2, [account3], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.true; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.true; + }); }); it('should return correct isComplete status FALSE - multisig Single Level', () => { @@ -473,89 +588,42 @@ describe('AggregateTransactionService', () => { Deadline.create(), [transferTransaction.toAggregate(multisig3.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(account2, [], generationHash); - aggregateTransactionService.isComplete(signedTransaction).toPromise().then((isComplete) => { - expect(isComplete).to.be.false; - }); + aggregateTransactionService + .isComplete(signedTransaction) + .toPromise() + .then((isComplete) => { + expect(isComplete).to.be.false; + }); }); - function givenMultisig2AccountInfo(): MultisigAccountInfo { - return new MultisigAccountInfo(multisig2.publicAccount, - 2, 1, - [multisig1.publicAccount, - account1.publicAccount], - [], - ); - } - function givenMultisig3AccountInfo(): MultisigAccountInfo { - return new MultisigAccountInfo(multisig3.publicAccount, - 2, 2, - [account2.publicAccount, - account3.publicAccount], - [], - ); - } - - function givenAccount1Info(): MultisigAccountInfo { - return new MultisigAccountInfo(account1.publicAccount, - 0, 0, - [], - [multisig2.publicAccount], - ); - } - function givenAccount2Info(): MultisigAccountInfo { - return new MultisigAccountInfo(account2.publicAccount, - 0, 0, - [], - [multisig2.publicAccount, - multisig3.publicAccount], - ); - } - function givenAccount3Info(): MultisigAccountInfo { - return new MultisigAccountInfo(account3.publicAccount, - 0, 0, - [], - [multisig2.publicAccount, - multisig3.publicAccount], - ); - } - function givenAccount4Info(): MultisigAccountInfo { - return new MultisigAccountInfo(account4.publicAccount, - 0, 0, - [], - [], - ); - } - - function givenMultisig2AccountGraphInfo(): MultisigAccountGraphInfo { - const map = new Map(); - map.set(0, [new MultisigAccountInfo(multisig2.publicAccount, - 2, 1, - [multisig1.publicAccount, - account1.publicAccount], - [], - )]) - .set(1, [new MultisigAccountInfo(multisig1.publicAccount, - 1, 1, - [account2.publicAccount, account3.publicAccount], - [multisig2.publicAccount], - )]); - - return new MultisigAccountGraphInfo(map); - } + it('should call getNetworkMaxCosignaturesPerAggregate and returns', async () => { + when(mockNetworkRepository.getNetworkProperties()).thenReturn(observableOf(getNetworkProperties('15'))); + const max = await aggregateTransactionService.getNetworkMaxCosignaturesPerAggregate().toPromise(); + expect(max).to.be.equal(15); + }); - function givenMultisig3AccountGraphInfo(): MultisigAccountGraphInfo { - const map = new Map(); - map.set(0, [new MultisigAccountInfo(multisig3.publicAccount, - 2, 2, - [account2.publicAccount, - account3.publicAccount], - [], - )]); + it('should call getNetworkMaxCosignaturesPerAggregate and returns with single quote', async () => { + when(mockNetworkRepository.getNetworkProperties()).thenReturn(observableOf(getNetworkProperties(`1'000`))); + const max = await aggregateTransactionService.getNetworkMaxCosignaturesPerAggregate().toPromise(); + expect(max).to.be.equal(1000); + }); - return new MultisigAccountGraphInfo(map); - } + it('should call getNetworkMaxCosignaturesPerAggregate and throw', () => { + when(mockNetworkRepository.getNetworkProperties()).thenReturn(observableOf(getNetworkProperties(''))); + aggregateTransactionService + .getNetworkMaxCosignaturesPerAggregate() + .toPromise() + .catch((error) => { + expect(error).not.to.be.undefined; + }); + }); + it('should call getMaxCosignatures and returns', async () => { + const max = await aggregateTransactionService.getMaxCosignatures(multisig2.address).toPromise(); + expect(max).to.be.equal(4); + }); }); diff --git a/test/service/BlockService.spec.ts b/test/service/BlockService.spec.ts index 8713cb7bda..8dcdadd72a 100644 --- a/test/service/BlockService.spec.ts +++ b/test/service/BlockService.spec.ts @@ -31,29 +31,78 @@ import { BlockService } from '../../src/service/BlockService'; import { TestingAccount } from '../conf/conf.spec'; describe('BlockService', () => { - const mockBlockHash = 'D4EC16FCFE696EFDBF1820F68245C88135ACF4C6F888599C8E18BC09B9F08C7B'; const leaf = '2717C8AAB0A21896D0C56375209E761F84383C3882F37A11D9D0159007263EB2'; let blockService: BlockService; let account: Account; + + function mockBlockInfo(isFake = false): BlockInfo { + if (isFake) { + return new BlockInfo( + 'hash', + 'generationHash', + UInt64.fromNumericString('0'), + 1, + 'signature', + account.publicAccount, + NetworkType.MIJIN_TEST, + 0, + 0, + UInt64.fromUint(1), + UInt64.fromUint(0), + UInt64.fromUint(0), + 0, + 'previousHash', + 'fakeHash', + 'fakeHash', + 'stateHash', + undefined, + ); + } + return new BlockInfo( + 'hash', + 'generationHash', + UInt64.fromNumericString('0'), + 1, + 'signature', + account.publicAccount, + NetworkType.MIJIN_TEST, + 0, + 0, + UInt64.fromUint(1), + UInt64.fromUint(0), + UInt64.fromUint(0), + 0, + 'previousHash', + mockBlockHash, + mockBlockHash, + 'stateHash', + undefined, + ); + } + + function mockMerklePath(): MerkleProofInfo { + return new MerkleProofInfo([ + new MerklePathItem(PositionEnum.Left, 'CDE45D740536E5361F392025A44B26546A138958E69CD6F18D22908F8F11ECF2'), + new MerklePathItem(PositionEnum.Right, '4EF55DAB8FEF9711B23DA71D2ACC58EFFF3969C3D572E06ACB898F99BED4827A'), + new MerklePathItem(PositionEnum.Left, '1BB95470065ED69D184948A0175EDC2EAB9E86A0CEB47B648A58A02A5445AF66'), + new MerklePathItem(PositionEnum.Right, 'D96B03809B8B198EFA5824191A979F7B85C0E9B7A6623DAFF38D4B2927EFDFB5'), + new MerklePathItem(PositionEnum.Right, '9981EBDBCA8E36BA4D4D4A450072026AC8C85BA6497666219E0E049BE3362E51'), + ]); + } + before(() => { account = TestingAccount; const mockBlockRepository = mock(); const mockReceiptRepository = mock(); const mockRepoFactory = mock(); - when(mockBlockRepository.getBlockByHeight(deepEqual(UInt64.fromUint(1)))) - .thenReturn(observableOf(mockBlockInfo())); - when(mockBlockRepository.getBlockByHeight(deepEqual(UInt64.fromUint(2)))) - .thenReturn(observableOf(mockBlockInfo(true))); - when(mockBlockRepository.getMerkleTransaction(deepEqual(UInt64.fromUint(1)), leaf)) - .thenReturn(observableOf(mockMerklePath())); - when(mockBlockRepository.getMerkleTransaction(deepEqual(UInt64.fromUint(2)), leaf)) - .thenReturn(observableOf(mockMerklePath())); - when(mockReceiptRepository.getMerkleReceipts(deepEqual(UInt64.fromUint(1)), leaf)) - .thenReturn(observableOf(mockMerklePath())); - when(mockReceiptRepository.getMerkleReceipts(deepEqual(UInt64.fromUint(2)), leaf)) - .thenReturn(observableOf(mockMerklePath())); + when(mockBlockRepository.getBlockByHeight(deepEqual(UInt64.fromUint(1)))).thenReturn(observableOf(mockBlockInfo())); + when(mockBlockRepository.getBlockByHeight(deepEqual(UInt64.fromUint(2)))).thenReturn(observableOf(mockBlockInfo(true))); + when(mockBlockRepository.getMerkleTransaction(deepEqual(UInt64.fromUint(1)), leaf)).thenReturn(observableOf(mockMerklePath())); + when(mockBlockRepository.getMerkleTransaction(deepEqual(UInt64.fromUint(2)), leaf)).thenReturn(observableOf(mockMerklePath())); + when(mockReceiptRepository.getMerkleReceipts(deepEqual(UInt64.fromUint(1)), leaf)).thenReturn(observableOf(mockMerklePath())); + when(mockReceiptRepository.getMerkleReceipts(deepEqual(UInt64.fromUint(2)), leaf)).thenReturn(observableOf(mockMerklePath())); const blockRepository = instance(mockBlockRepository); const receiptRepository = instance(mockReceiptRepository); @@ -82,31 +131,4 @@ describe('BlockService', () => { const result = await blockService.validateStatementInBlock(leaf, UInt64.fromUint(2)).toPromise(); expect(result).to.be.false; }); - - function mockBlockInfo(isFake: boolean = false): BlockInfo { - if (isFake) { - return new BlockInfo( - 'hash', 'generationHash', UInt64.fromNumericString('0'), 1, 'signature', account.publicAccount, - NetworkType.MIJIN_TEST, 0, 0, UInt64.fromUint(1), UInt64.fromUint(0), UInt64.fromUint(0), 0, 'previousHash', - 'fakeHash', 'fakeHash', 'stateHash', undefined, - ); - } - return new BlockInfo( - 'hash', 'generationHash', UInt64.fromNumericString('0'), 1, 'signature', account.publicAccount, - NetworkType.MIJIN_TEST, 0, 0, UInt64.fromUint(1), UInt64.fromUint(0), UInt64.fromUint(0), 0, 'previousHash', - mockBlockHash, mockBlockHash, 'stateHash', undefined, - ); - } - - function mockMerklePath(): MerkleProofInfo { - return new MerkleProofInfo( - [ - new MerklePathItem(PositionEnum.Left, 'CDE45D740536E5361F392025A44B26546A138958E69CD6F18D22908F8F11ECF2'), - new MerklePathItem(PositionEnum.Right, '4EF55DAB8FEF9711B23DA71D2ACC58EFFF3969C3D572E06ACB898F99BED4827A'), - new MerklePathItem(PositionEnum.Left, '1BB95470065ED69D184948A0175EDC2EAB9E86A0CEB47B648A58A02A5445AF66'), - new MerklePathItem(PositionEnum.Right, 'D96B03809B8B198EFA5824191A979F7B85C0E9B7A6623DAFF38D4B2927EFDFB5'), - new MerklePathItem(PositionEnum.Right, '9981EBDBCA8E36BA4D4D4A450072026AC8C85BA6497666219E0E049BE3362E51'), - ], - ); - } }); diff --git a/test/service/MetadataTransactionservice.spec.ts b/test/service/MetadataTransactionservice.spec.ts index cc988efff8..a1f3c55a6d 100644 --- a/test/service/MetadataTransactionservice.spec.ts +++ b/test/service/MetadataTransactionservice.spec.ts @@ -42,141 +42,163 @@ describe('MetadataTransactionService', () => { const value = 'TEST'; const deltaValue = 'dalta'; const targetIdHex = '941299B2B7E1291C'; + function mockMetadata(type: MetadataType): Metadata { + let targetId; + + if (type === MetadataType.Account) { + targetId = undefined; + } else if (type === MetadataType.Mosaic) { + targetId = new MosaicId(targetIdHex); + } else if (type === MetadataType.Namespace) { + targetId = NamespaceId.createFromEncoded(targetIdHex); + } + return new Metadata( + '59DFBA84B2E9E7000135E80C', + new MetadataEntry( + '5E628EA59818D97AA4118780D9A88C5512FCE7A21C195E1574727EFCE5DF7C0D', + account.publicKey, + account.publicKey, + key, + MetadataType.Account, + value, + targetId, + ), + ); + } before(() => { account = TestingAccount; const mockMetadataRepository: MetadataRepository = mock(); - when(mockMetadataRepository - .getAccountMetadataByKeyAndSender(deepEqual(account.address), key.toHex(), account.publicKey)) - .thenReturn(observableOf(mockMetadata(MetadataType.Account))); - when(mockMetadataRepository - .getMosaicMetadataByKeyAndSender(deepEqual(new MosaicId(targetIdHex)), key.toHex(), account.publicKey)) - .thenReturn(observableOf(mockMetadata(MetadataType.Mosaic))); - when(mockMetadataRepository - .getNamespaceMetadataByKeyAndSender(deepEqual(NamespaceId.createFromEncoded(targetIdHex)), key.toHex(), account.publicKey)) - .thenReturn(observableOf(mockMetadata(MetadataType.Namespace))); + when( + mockMetadataRepository.getAccountMetadataByKeyAndSender(deepEqual(account.address), key.toHex(), account.publicKey), + ).thenReturn(observableOf(mockMetadata(MetadataType.Account))); + when( + mockMetadataRepository.getMosaicMetadataByKeyAndSender(deepEqual(new MosaicId(targetIdHex)), key.toHex(), account.publicKey), + ).thenReturn(observableOf(mockMetadata(MetadataType.Mosaic))); + when( + mockMetadataRepository.getNamespaceMetadataByKeyAndSender( + deepEqual(NamespaceId.createFromEncoded(targetIdHex)), + key.toHex(), + account.publicKey, + ), + ).thenReturn(observableOf(mockMetadata(MetadataType.Namespace))); const metadataRepository = instance(mockMetadataRepository); metadataTransactionService = new MetadataTransactionService(metadataRepository); }); it('should create AccountMetadataTransaction', (done) => { - metadataTransactionService.createMetadataTransaction(Deadline.create(), - NetworkType.MIJIN_TEST, - MetadataType.Account, - account.publicAccount, - key, - value + deltaValue, - account.publicAccount) + metadataTransactionService + .createMetadataTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + MetadataType.Account, + account.publicAccount, + key, + value + deltaValue, + account.publicAccount, + ) .subscribe((transaction: AccountMetadataTransaction) => { expect(transaction.type).to.be.equal(TransactionType.ACCOUNT_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); - expect(Convert.utf8ToHex(transaction.value)) - .to.be.equal(Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue))); + expect(Convert.utf8ToHex(transaction.value)).to.be.equal( + Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue)), + ); expect(transaction.valueSizeDelta).to.be.equal(deltaValue.length); expect(transaction.targetPublicKey).to.be.equal(account.publicKey); done(); - }); + }); }); it('should create MosaicMetadataTransaction', (done) => { - metadataTransactionService.createMetadataTransaction(Deadline.create(), - NetworkType.MIJIN_TEST, - MetadataType.Mosaic, - account.publicAccount, - key, - value + deltaValue, - account.publicAccount, - new MosaicId(targetIdHex)) + metadataTransactionService + .createMetadataTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + MetadataType.Mosaic, + account.publicAccount, + key, + value + deltaValue, + account.publicAccount, + new MosaicId(targetIdHex), + ) .subscribe((transaction: MosaicMetadataTransaction) => { expect(transaction.type).to.be.equal(TransactionType.MOSAIC_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); - expect(Convert.utf8ToHex(transaction.value)) - .to.be.equal(Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue))); + expect(Convert.utf8ToHex(transaction.value)).to.be.equal( + Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue)), + ); expect(transaction.targetMosaicId.toHex()).to.be.equal(targetIdHex); expect(transaction.valueSizeDelta).to.be.equal(deltaValue.length); expect(transaction.targetPublicKey).to.be.equal(account.publicKey); done(); - }); + }); }); it('should create NamespaceMetadataTransaction', (done) => { - metadataTransactionService.createMetadataTransaction(Deadline.create(), - NetworkType.MIJIN_TEST, - MetadataType.Namespace, - account.publicAccount, - key, - value + deltaValue, - account.publicAccount, - NamespaceId.createFromEncoded(targetIdHex)) + metadataTransactionService + .createMetadataTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + MetadataType.Namespace, + account.publicAccount, + key, + value + deltaValue, + account.publicAccount, + NamespaceId.createFromEncoded(targetIdHex), + ) .subscribe((transaction: NamespaceMetadataTransaction) => { expect(transaction.type).to.be.equal(TransactionType.NAMESPACE_METADATA); expect(transaction.scopedMetadataKey.toHex()).to.be.equal(key.toHex()); - expect(Convert.utf8ToHex(transaction.value)) - .to.be.equal(Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue))); + expect(Convert.utf8ToHex(transaction.value)).to.be.equal( + Convert.xor(Convert.utf8ToUint8(value), Convert.utf8ToUint8(value + deltaValue)), + ); expect(transaction.targetNamespaceId.toHex()).to.be.equal(targetIdHex); expect(transaction.valueSizeDelta).to.be.equal(deltaValue.length); expect(transaction.targetPublicKey).to.be.equal(account.publicKey); done(); - }); + }); }); it('should throw error with invalid metadata type', () => { expect(() => { - metadataTransactionService.createMetadataTransaction(Deadline.create(), - NetworkType.MIJIN_TEST, - 99, - account.publicAccount, - key, - value + deltaValue, - account.publicAccount); + metadataTransactionService.createMetadataTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + 99, + account.publicAccount, + key, + value + deltaValue, + account.publicAccount, + ); }).to.throw(Error, 'Metadata type invalid'); }); it('should throw error with invalid mosaicId', () => { expect(() => { - metadataTransactionService.createMetadataTransaction(Deadline.create(), - NetworkType.MIJIN_TEST, - MetadataType.Mosaic, - account.publicAccount, - key, - value + deltaValue, - account.publicAccount); + metadataTransactionService.createMetadataTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + MetadataType.Mosaic, + account.publicAccount, + key, + value + deltaValue, + account.publicAccount, + ); }).to.throw(Error, 'TargetId for MosaicMetadataTransaction is invalid'); }); it('should throw error with invalid NamespaceId', () => { expect(() => { - metadataTransactionService.createMetadataTransaction(Deadline.create(), - NetworkType.MIJIN_TEST, - MetadataType.Namespace, - account.publicAccount, - key, - value + deltaValue, - account.publicAccount); - }).to.throw(Error, 'TargetId for NamespaceMetadataTransaction is invalid'); - }); - - function mockMetadata(type: MetadataType): Metadata { - let targetId; - - if (type === MetadataType.Account) { - targetId = undefined; - } else if (type === MetadataType.Mosaic) { - targetId = new MosaicId(targetIdHex); - } else if (type === MetadataType.Namespace) { - targetId = NamespaceId.createFromEncoded(targetIdHex); - } - return new Metadata( - '59DFBA84B2E9E7000135E80C', - new MetadataEntry( - '5E628EA59818D97AA4118780D9A88C5512FCE7A21C195E1574727EFCE5DF7C0D', - account.publicKey, - account.publicKey, + metadataTransactionService.createMetadataTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + MetadataType.Namespace, + account.publicAccount, key, - MetadataType.Account, - value, - targetId), + value + deltaValue, + account.publicAccount, ); - } + }).to.throw(Error, 'TargetId for NamespaceMetadataTransaction is invalid'); + }); }); diff --git a/test/service/MosaicRestrictionTransactionservice.spec.ts b/test/service/MosaicRestrictionTransactionservice.spec.ts index 4b629431e8..8c4b4bf04d 100644 --- a/test/service/MosaicRestrictionTransactionservice.spec.ts +++ b/test/service/MosaicRestrictionTransactionservice.spec.ts @@ -51,6 +51,28 @@ describe('MosaicRestrictionTransactionService', () => { const globalRestrictionType = MosaicRestrictionType.LE; const addressRestrictionValue = '10'; + function mockGlobalRestriction(): MosaicGlobalRestriction { + return new MosaicGlobalRestriction( + '59DFBA84B2E9E7000135E80C', + MosaicRestrictionEntryType.GLOBAL, + mosaicId, + new Map().set( + key.toString(), + new MosaicGlobalRestrictionItem(referenceMosaicId, globalRestrictionValue, globalRestrictionType), + ), + ); + } + + function mockAddressRestriction(): MosaicAddressRestriction { + return new MosaicAddressRestriction( + '59DFBA84B2E9E7000135E80C', + MosaicRestrictionEntryType.GLOBAL, + mosaicId, + account.address, + new Map().set(key.toString(), addressRestrictionValue), + ); + } + before(() => { account = TestingAccount; mosaicId = new MosaicId('85BBEA6CC462B244'); @@ -61,36 +83,30 @@ describe('MosaicRestrictionTransactionService', () => { const mockRestrictionRepository = mock(); const mockNamespaceRepository = mock(); - when(mockRestrictionRepository - .getMosaicGlobalRestriction(deepEqual(mosaicId))) - .thenReturn(observableOf(mockGlobalRestriction())); - when(mockRestrictionRepository - .getMosaicGlobalRestriction(deepEqual(mosaicIdWrongKey))) - .thenThrow(new Error('Wrong mosaicId')); - when(mockRestrictionRepository - .getMosaicAddressRestriction(deepEqual(mosaicId), deepEqual(account.address))) - .thenReturn(observableOf(mockAddressRestriction())); - when(mockNamespaceRepository.getLinkedMosaicId(deepEqual(unresolvedMosaicId))) - .thenReturn(observableOf(mosaicId)); - when(mockNamespaceRepository.getLinkedMosaicId(deepEqual(unresolvedAddress))) - .thenThrow(new Error('invalid namespaceId')); - when(mockNamespaceRepository.getLinkedAddress(deepEqual(unresolvedAddress))) - .thenReturn(observableOf(account.address)); - when(mockNamespaceRepository.getLinkedAddress(deepEqual(unresolvedMosaicId))) - .thenThrow(new Error('invalid namespaceId')); + when(mockRestrictionRepository.getMosaicGlobalRestriction(deepEqual(mosaicId))).thenReturn(observableOf(mockGlobalRestriction())); + when(mockRestrictionRepository.getMosaicGlobalRestriction(deepEqual(mosaicIdWrongKey))).thenThrow(new Error('Wrong mosaicId')); + when(mockRestrictionRepository.getMosaicAddressRestriction(deepEqual(mosaicId), deepEqual(account.address))).thenReturn( + observableOf(mockAddressRestriction()), + ); + when(mockNamespaceRepository.getLinkedMosaicId(deepEqual(unresolvedMosaicId))).thenReturn(observableOf(mosaicId)); + when(mockNamespaceRepository.getLinkedMosaicId(deepEqual(unresolvedAddress))).thenThrow(new Error('invalid namespaceId')); + when(mockNamespaceRepository.getLinkedAddress(deepEqual(unresolvedAddress))).thenReturn(observableOf(account.address)); + when(mockNamespaceRepository.getLinkedAddress(deepEqual(unresolvedMosaicId))).thenThrow(new Error('invalid namespaceId')); const restrictionRepository = instance(mockRestrictionRepository); const namespaceRepository = instance(mockNamespaceRepository); mosaicRestrictionTransactionService = new MosaicRestrictionTransactionService(restrictionRepository, namespaceRepository); }); it('should create MosaicGlobalRestriction Transaction', (done) => { - mosaicRestrictionTransactionService.createMosaicGlobalRestrictionTransaction( - Deadline.create(), - NetworkType.MIJIN_TEST, - mosaicId, - key, - '2000', - MosaicRestrictionType.LE) + mosaicRestrictionTransactionService + .createMosaicGlobalRestrictionTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + mosaicId, + key, + '2000', + MosaicRestrictionType.LE, + ) .subscribe((transaction: MosaicGlobalRestrictionTransaction) => { expect(transaction.type).to.be.equal(TransactionType.MOSAIC_GLOBAL_RESTRICTION); expect(transaction.restrictionKey.toString()).to.be.equal(key.toString()); @@ -98,18 +114,20 @@ describe('MosaicRestrictionTransactionService', () => { expect(transaction.previousRestrictionValue.toString()).to.be.equal(globalRestrictionValue); expect(transaction.referenceMosaicId.toHex()).to.be.equal(new MosaicId(UInt64.fromUint(0).toDTO()).toHex()); done(); - }); + }); }); it('should create MosaicGlobalRestriction Transaction - with referenceMosaicId', (done) => { - mosaicRestrictionTransactionService.createMosaicGlobalRestrictionTransaction( - Deadline.create(), - NetworkType.MIJIN_TEST, - mosaicId, - key, - '2000', - MosaicRestrictionType.LE, - referenceMosaicId) + mosaicRestrictionTransactionService + .createMosaicGlobalRestrictionTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + mosaicId, + key, + '2000', + MosaicRestrictionType.LE, + referenceMosaicId, + ) .subscribe((transaction: MosaicGlobalRestrictionTransaction) => { expect(transaction.type).to.be.equal(TransactionType.MOSAIC_GLOBAL_RESTRICTION); expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); @@ -117,34 +135,31 @@ describe('MosaicRestrictionTransactionService', () => { expect(transaction.previousRestrictionValue.toString()).to.be.equal(globalRestrictionValue); expect(transaction.referenceMosaicId.toHex()).to.be.equal(referenceMosaicId.toHex()); done(); - }); + }); }); it('should create MosaicAddressRestriction Transaction', (done) => { - mosaicRestrictionTransactionService.createMosaicAddressRestrictionTransaction( - Deadline.create(), - NetworkType.MIJIN_TEST, - mosaicId, - key, - account.address, - '2000') + mosaicRestrictionTransactionService + .createMosaicAddressRestrictionTransaction(Deadline.create(), NetworkType.MIJIN_TEST, mosaicId, key, account.address, '2000') .subscribe((transaction: MosaicAddressRestrictionTransaction) => { expect(transaction.type).to.be.equal(TransactionType.MOSAIC_ADDRESS_RESTRICTION); expect(transaction.restrictionKey.toString()).to.be.equal(key.toString()); expect(transaction.targetAddressToString()).to.be.equal(account.address.plain()); expect(transaction.previousRestrictionValue.toString()).to.be.equal(addressRestrictionValue); done(); - }); + }); }); it('should create MosaicGlobalRestriction Transaction with unresolvedMosaicId', (done) => { - mosaicRestrictionTransactionService.createMosaicGlobalRestrictionTransaction( - Deadline.create(), - NetworkType.MIJIN_TEST, - unresolvedMosaicId, - key, - '2000', - MosaicRestrictionType.LE) + mosaicRestrictionTransactionService + .createMosaicGlobalRestrictionTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + unresolvedMosaicId, + key, + '2000', + MosaicRestrictionType.LE, + ) .subscribe((transaction: MosaicGlobalRestrictionTransaction) => { expect(transaction.type).to.be.equal(TransactionType.MOSAIC_GLOBAL_RESTRICTION); expect(transaction.restrictionKey.toHex()).to.be.equal(key.toHex()); @@ -152,24 +167,26 @@ describe('MosaicRestrictionTransactionService', () => { expect(transaction.previousRestrictionValue.toString()).to.be.equal(globalRestrictionValue); expect(transaction.referenceMosaicId.toHex()).to.be.equal(new MosaicId(UInt64.fromUint(0).toDTO()).toHex()); done(); - }); + }); }); it('should create MosaicAddressRestriction Transaction with unresolvedAddress', (done) => { - mosaicRestrictionTransactionService.createMosaicAddressRestrictionTransaction( - Deadline.create(), - NetworkType.MIJIN_TEST, - unresolvedMosaicId, - key, - unresolvedAddress, - '2000') + mosaicRestrictionTransactionService + .createMosaicAddressRestrictionTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + unresolvedMosaicId, + key, + unresolvedAddress, + '2000', + ) .subscribe((transaction: MosaicAddressRestrictionTransaction) => { expect(transaction.type).to.be.equal(TransactionType.MOSAIC_ADDRESS_RESTRICTION); expect(transaction.restrictionKey.toString()).to.be.equal(key.toString()); expect(transaction.targetAddressToString()).to.be.equal(unresolvedAddress.toHex()); expect(transaction.previousRestrictionValue.toString()).to.be.equal(addressRestrictionValue); done(); - }); + }); }); it('should throw error with invalid unresolvedMosaicId', () => { @@ -180,7 +197,8 @@ describe('MosaicRestrictionTransactionService', () => { unresolvedAddress, key, '2000', - MosaicRestrictionType.LE); + MosaicRestrictionType.LE, + ); }).to.throw(); }); @@ -192,70 +210,52 @@ describe('MosaicRestrictionTransactionService', () => { mosaicId, key, unresolvedMosaicId, - '2000'); + '2000', + ); }).to.throw(); }); it('should throw error with invalid value / key', () => { expect(() => { mosaicRestrictionTransactionService.createMosaicGlobalRestrictionTransaction( - Deadline.create(), - NetworkType.MIJIN_TEST, - mosaicId, - key, - 'wrong value', - MosaicRestrictionType.LE); + Deadline.create(), + NetworkType.MIJIN_TEST, + mosaicId, + key, + 'wrong value', + MosaicRestrictionType.LE, + ); }).to.throw(Error, 'RestrictionValue: wrong value is not a valid numeric string.'); expect(() => { mosaicRestrictionTransactionService.createMosaicAddressRestrictionTransaction( - Deadline.create(), - NetworkType.MIJIN_TEST, - mosaicId, - key, - account.address, - 'wrong value'); + Deadline.create(), + NetworkType.MIJIN_TEST, + mosaicId, + key, + account.address, + 'wrong value', + ); }).to.throw(Error, 'RestrictionValue: wrong value is not a valid numeric string.'); }); it('should throw error with invalid address restriction key - MosaicAddressRestriction', () => { - mosaicRestrictionTransactionService.createMosaicAddressRestrictionTransaction( - Deadline.create(), - NetworkType.MIJIN_TEST, - mosaicIdWrongKey, - invalidKey, - account.address, - '2000').subscribe((t) => {}, (err) => { - expect(err).not.to.be.undefined; - }); + mosaicRestrictionTransactionService + .createMosaicAddressRestrictionTransaction( + Deadline.create(), + NetworkType.MIJIN_TEST, + mosaicIdWrongKey, + invalidKey, + account.address, + '2000', + ) + .subscribe( + () => { + expect(true).to.be.false; + }, + (err) => { + expect(err).not.to.be.undefined; + }, + ); }); - - function mockGlobalRestriction(): MosaicGlobalRestriction { - return new MosaicGlobalRestriction( - '59DFBA84B2E9E7000135E80C', - MosaicRestrictionEntryType.GLOBAL, - mosaicId, - new Map() - .set(key.toString(), - new MosaicGlobalRestrictionItem( - referenceMosaicId, - globalRestrictionValue, - globalRestrictionType, - ), - ), - ); - } - - function mockAddressRestriction(): MosaicAddressRestriction { - return new MosaicAddressRestriction( - '59DFBA84B2E9E7000135E80C', - MosaicRestrictionEntryType.GLOBAL, - mosaicId, - account.address, - new Map() - .set(key.toString(), - addressRestrictionValue, - ), - ); - } }); diff --git a/test/service/MosaicService.spec.ts b/test/service/MosaicService.spec.ts index eeeab2b4e3..a00ee4dc9f 100644 --- a/test/service/MosaicService.spec.ts +++ b/test/service/MosaicService.spec.ts @@ -14,15 +14,15 @@ * limitations under the License. */ -import {expect} from 'chai'; +import { expect } from 'chai'; import { MosaicFlags, AccountInfo, AccountType } from '../../src/model/model'; -import {Mosaic} from '../../src/model/mosaic/Mosaic'; -import {MosaicId} from '../../src/model/mosaic/MosaicId'; -import {MosaicInfo} from '../../src/model/mosaic/MosaicInfo'; -import {UInt64} from '../../src/model/UInt64'; -import {MosaicAmountView} from '../../src/service/MosaicAmountView'; -import {MosaicService} from '../../src/service/MosaicService'; -import {MosaicView} from '../../src/service/MosaicView'; +import { Mosaic } from '../../src/model/mosaic/Mosaic'; +import { MosaicId } from '../../src/model/mosaic/MosaicId'; +import { MosaicInfo } from '../../src/model/mosaic/MosaicInfo'; +import { UInt64 } from '../../src/model/UInt64'; +import { MosaicAmountView } from '../../src/service/MosaicAmountView'; +import { MosaicService } from '../../src/service/MosaicService'; +import { MosaicView } from '../../src/service/MosaicView'; import { AccountRepository } from '../../src/infrastructure/AccountRepository'; import { mock, when, instance, deepEqual } from 'ts-mockito'; import { MosaicRepository } from '../../src/infrastructure/MosaicRepository'; @@ -34,11 +34,39 @@ describe('MosaicService', () => { const accountRepositoryMock = mock(); const mosaicRepositoryMock = mock(); + function buildMosaicInfo(mosaicId: MosaicId, publicAccount: PublicAccount): MosaicInfo { + return new MosaicInfo( + mosaicId, + UInt64.fromUint(10), + UInt64.fromUint(1), + publicAccount, + 0, + new MosaicFlags(1), + 6, + UInt64.fromUint(1), + ); + } + + function buildAccountInfo(mosaicId: MosaicId, isEmptyMosaic = false): AccountInfo { + return new AccountInfo( + TestingAccount.address, + UInt64.fromUint(1), + TestingAccount.publicKey, + UInt64.fromUint(1), + AccountType.Main, + '', + [], + isEmptyMosaic ? [] : [new Mosaic(mosaicId, UInt64.fromUint(100))], + UInt64.fromUint(1), + UInt64.fromUint(1), + ); + } + it('mosaicsView', () => { const mosaicId = new MosaicId([3294802500, 2243684972]); - when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( - [buildMosaicInfo(mosaicId, TestingAccount.publicAccount)] - )); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn( + observableOf([buildMosaicInfo(mosaicId, TestingAccount.publicAccount)]), + ); const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); return mosaicService.mosaicsView([mosaicId]).subscribe((mosaicsView: MosaicView[]) => { const mosaicView = mosaicsView[0]; @@ -48,9 +76,7 @@ describe('MosaicService', () => { it('mosaicsView of no existing mosaicId', () => { const mosaicId = new MosaicId([1234, 1234]); - when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( - [] - )); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf([])); const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); return mosaicService.mosaicsView([mosaicId]).subscribe((mosaicsView: MosaicView[]) => { expect(mosaicsView.length).to.be.equal(0); @@ -59,42 +85,34 @@ describe('MosaicService', () => { it('mosaicsAmountView', () => { const mosaicId = new MosaicId([3294802500, 2243684972]); - when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( - [buildMosaicInfo(mosaicId, TestingAccount.publicAccount)] - )); - when(accountRepositoryMock.getAccountInfo(deepEqual(TestingAccount.address))).thenReturn(observableOf( - buildAccountInfo(mosaicId), - )); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn( + observableOf([buildMosaicInfo(mosaicId, TestingAccount.publicAccount)]), + ); + when(accountRepositoryMock.getAccountInfo(deepEqual(TestingAccount.address))).thenReturn(observableOf(buildAccountInfo(mosaicId))); const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); - return mosaicService.mosaicsAmountViewFromAddress(TestingAccount.address) - .subscribe((mosaicsAmountView: MosaicAmountView[]) => { - const mosaicAmountView = mosaicsAmountView[0]; - expect(mosaicAmountView.mosaicInfo).to.be.an.instanceof(MosaicInfo); - }); + return mosaicService.mosaicsAmountViewFromAddress(TestingAccount.address).subscribe((mosaicsAmountView: MosaicAmountView[]) => { + const mosaicAmountView = mosaicsAmountView[0]; + expect(mosaicAmountView.mosaicInfo).to.be.an.instanceof(MosaicInfo); + }); }); it('mosaicsAmountView of no existing account', () => { const mosaicId = new MosaicId([3294802500, 2243684972]); - when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( - [] - )); - when(accountRepositoryMock.getAccountInfo(deepEqual(TestingAccount.address))).thenReturn(observableOf( - buildAccountInfo(mosaicId), - )); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf([])); + when(accountRepositoryMock.getAccountInfo(deepEqual(TestingAccount.address))).thenReturn(observableOf(buildAccountInfo(mosaicId))); const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); - return mosaicService.mosaicsAmountViewFromAddress(TestingAccount.address) - .subscribe((mosaicsAmountView: MosaicAmountView[]) => { - expect(mosaicsAmountView.length).to.be.equal(0); - }); + return mosaicService.mosaicsAmountViewFromAddress(TestingAccount.address).subscribe((mosaicsAmountView: MosaicAmountView[]) => { + expect(mosaicsAmountView.length).to.be.equal(0); + }); }); it('mosaicsAmountView', () => { const mosaicId = new MosaicId([3294802500, 2243684972]); - when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn(observableOf( - [buildMosaicInfo(mosaicId, TestingAccount.publicAccount)] - )); + when(mosaicRepositoryMock.getMosaics(deepEqual([mosaicId]))).thenReturn( + observableOf([buildMosaicInfo(mosaicId, TestingAccount.publicAccount)]), + ); const mosaicService = new MosaicService(instance(accountRepositoryMock), instance(mosaicRepositoryMock)); const mosaic = new Mosaic(mosaicId, UInt64.fromUint(1000)); @@ -104,20 +122,4 @@ describe('MosaicService', () => { expect(mosaicAmountView.amount.compact()).to.be.equal(1000); }); }); - - function buildMosaicInfo(mosaicId: MosaicId, publicAccount: PublicAccount): MosaicInfo { - return new MosaicInfo( - mosaicId, UInt64.fromUint(10), UInt64.fromUint(1), publicAccount, 0, - new MosaicFlags(1), 6, UInt64.fromUint(1) - ); - } - - function buildAccountInfo(mosaicId: MosaicId, isEmptyMosaic: boolean = false): AccountInfo { - return new AccountInfo( - TestingAccount.address, UInt64.fromUint(1), TestingAccount.publicKey, UInt64.fromUint(1), - AccountType.Main, '', [], isEmptyMosaic ? [] : [new Mosaic(mosaicId, UInt64.fromUint(100))], UInt64.fromUint(1), - UInt64.fromUint(1), - ); - } - }); diff --git a/test/service/NamespaceService.spec.ts b/test/service/NamespaceService.spec.ts index 30eda39e28..1888f274bb 100644 --- a/test/service/NamespaceService.spec.ts +++ b/test/service/NamespaceService.spec.ts @@ -28,22 +28,53 @@ import { UInt64 } from '../../src/model/UInt64'; import { NamespaceService } from '../../src/service/NamespaceService'; describe('NamespaceService', () => { + function givenRootNamespace(): NamespaceInfo { + return new NamespaceInfo( + true, + 0, + '59DFBA84B2E9E7000135E80C', + 0, + 1, + [new NamespaceId([3316183705, 3829351378])], + new NamespaceId([0, 0]), + PublicAccount.createFromPublicKey('1026D70E1954775749C6811084D6450A3184D977383F0E4282CD47118AF37755', NetworkType.MIJIN_TEST), + new UInt64([795, 0]), + new UInt64([50795, 0]), + new EmptyAlias(), + ); + } + + function givenSubnamespace(): NamespaceInfo { + return new NamespaceInfo( + true, + 0, + '5A1D85A1D53061000117D1EE', + 1, + 2, + [new NamespaceId([3316183705, 3829351378]), new NamespaceId([1781696705, 4157485863])], + new NamespaceId([3316183705, 3829351378]), + PublicAccount.createFromPublicKey('1026D70E1954775749C6811084D6450A3184D977383F0E4282CD47118AF37755', NetworkType.MIJIN_TEST), + new UInt64([795, 0]), + new UInt64([50795, 0]), + new EmptyAlias(), + ); + } it('should return the NamespaceInfo + name for a root namespace', () => { const mockedNamespaceRepository: NamespaceRepository = mock(); const rootNamespace = givenRootNamespace(); const subnamespace = givenSubnamespace(); - when(mockedNamespaceRepository.getNamespace(rootNamespace.id)) - .thenReturn(observableOf(rootNamespace)); - when(mockedNamespaceRepository.getNamespace(subnamespace.id)) - .thenReturn(observableOf(subnamespace)); - when(mockedNamespaceRepository.getNamespacesName(deepEqual([rootNamespace.id]))) - .thenReturn(observableOf([new NamespaceName(new NamespaceId([3316183705, 3829351378]), 'symboltests')])); - when(mockedNamespaceRepository.getNamespacesName(deepEqual([rootNamespace.id, subnamespace.id]))) - .thenReturn(observableOf([ + when(mockedNamespaceRepository.getNamespace(rootNamespace.id)).thenReturn(observableOf(rootNamespace)); + when(mockedNamespaceRepository.getNamespace(subnamespace.id)).thenReturn(observableOf(subnamespace)); + when(mockedNamespaceRepository.getNamespacesName(deepEqual([rootNamespace.id]))).thenReturn( + observableOf([new NamespaceName(new NamespaceId([3316183705, 3829351378]), 'symboltests')]), + ); + when(mockedNamespaceRepository.getNamespacesName(deepEqual([rootNamespace.id, subnamespace.id]))).thenReturn( + observableOf([ new NamespaceName(new NamespaceId([3316183705, 3829351378]), 'symboltests'), new NamespaceName(new NamespaceId([1781696705, 4157485863]), 'level2'), - ])); + ]), + ); const namespaceRepository = instance(mockedNamespaceRepository); const namespaceService = new NamespaceService(namespaceRepository); namespaceService.namespace(rootNamespace.id).subscribe((namespace) => { @@ -55,19 +86,20 @@ describe('NamespaceService', () => { const mockedNamespaceRepository: NamespaceRepository = mock(); const rootNamespace = givenRootNamespace(); const subnamespace = givenSubnamespace(); - when(mockedNamespaceRepository.getNamespace(rootNamespace.id)) - .thenReturn(observableOf(rootNamespace)); - when(mockedNamespaceRepository.getNamespace(subnamespace.id)) - .thenReturn(observableOf(subnamespace)); - when(mockedNamespaceRepository.getNamespacesName(deepEqual([rootNamespace.id]))) - .thenReturn(observableOf([new NamespaceName(new NamespaceId([3316183705, 3829351378]), 'symboltests')])); - when(mockedNamespaceRepository.getNamespacesName(deepEqual([subnamespace.id]))) - .thenReturn(observableOf([new NamespaceName(new NamespaceId([1781696705, 4157485863]), 'level2')])); - when(mockedNamespaceRepository.getNamespacesName(deepEqual([rootNamespace.id, subnamespace.id]))) - .thenReturn(observableOf([ + when(mockedNamespaceRepository.getNamespace(rootNamespace.id)).thenReturn(observableOf(rootNamespace)); + when(mockedNamespaceRepository.getNamespace(subnamespace.id)).thenReturn(observableOf(subnamespace)); + when(mockedNamespaceRepository.getNamespacesName(deepEqual([rootNamespace.id]))).thenReturn( + observableOf([new NamespaceName(new NamespaceId([3316183705, 3829351378]), 'symboltests')]), + ); + when(mockedNamespaceRepository.getNamespacesName(deepEqual([subnamespace.id]))).thenReturn( + observableOf([new NamespaceName(new NamespaceId([1781696705, 4157485863]), 'level2')]), + ); + when(mockedNamespaceRepository.getNamespacesName(deepEqual([rootNamespace.id, subnamespace.id]))).thenReturn( + observableOf([ new NamespaceName(new NamespaceId([3316183705, 3829351378]), 'symboltests'), new NamespaceName(new NamespaceId([1781696705, 4157485863]), 'level2'), - ])); + ]), + ); const namespaceRepository = instance(mockedNamespaceRepository); const namespaceService = new NamespaceService(namespaceRepository); @@ -75,35 +107,4 @@ describe('NamespaceService', () => { expect(namespace.name).to.be.equal('symboltests.level2'); }); }); - - function givenRootNamespace(): NamespaceInfo { - return new NamespaceInfo(true, - 0, - '59DFBA84B2E9E7000135E80C', - 0, - 1, - [new NamespaceId([ - 3316183705, - 3829351378, - ])], - new NamespaceId([0, 0]), - PublicAccount.createFromPublicKey('1026D70E1954775749C6811084D6450A3184D977383F0E4282CD47118AF37755', NetworkType.MIJIN_TEST), - new UInt64([795, 0]), - new UInt64([50795, 0]), - new EmptyAlias()); - } - - function givenSubnamespace(): NamespaceInfo { - return new NamespaceInfo(true, - 0, - '5A1D85A1D53061000117D1EE', - 1, - 2, - [new NamespaceId([3316183705, 3829351378]), new NamespaceId([1781696705, 4157485863])], - new NamespaceId([3316183705, 3829351378]), - PublicAccount.createFromPublicKey('1026D70E1954775749C6811084D6450A3184D977383F0E4282CD47118AF37755', NetworkType.MIJIN_TEST), - new UInt64([795, 0]), - new UInt64([50795, 0]), - new EmptyAlias()); - } }); diff --git a/test/service/TransactionService.spec.ts b/test/service/TransactionService.spec.ts index 3825f76c56..74515e2ba5 100644 --- a/test/service/TransactionService.spec.ts +++ b/test/service/TransactionService.spec.ts @@ -42,7 +42,6 @@ import { TransactionService } from '../../src/service/TransactionService'; * Unit test of TransactionService */ describe('TransactionService', () => { - const generationHash = '82DB2528834C9926F0FCCE042466B24A266F5B685CB66D2869AF6648C043E950'; const account = Account.generateNewAccount(NetworkType.MIJIN_TEST); const transferTransaction = TransferTransaction.create( @@ -57,19 +56,23 @@ describe('TransactionService', () => { Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); const aggregateBondedTransaction = AggregateTransaction.createBonded( Deadline.create(), [transferTransaction.toAggregate(account.publicAccount)], NetworkType.MIJIN_TEST, - []); + [], + ); - const hashLockTransaction = HashLockTransaction.create(Deadline.create(), + const hashLockTransaction = HashLockTransaction.create( + Deadline.create(), new Mosaic(new NamespaceId('cat.currency'), UInt64.fromUint(10 * Math.pow(10, NetworkCurrencyLocal.DIVISIBILITY))), UInt64.fromUint(10000), account.sign(aggregateBondedTransaction, generationHash), - NetworkType.MIJIN_TEST); + NetworkType.MIJIN_TEST, + ); let transactionRepositoryMock: TransactionRepository; let mockedReceiptRepository: ReceiptRepository; @@ -79,19 +82,18 @@ describe('TransactionService', () => { transactionRepositoryMock = mock(); mockedReceiptRepository = mock(); listener = mock(); - }); it('announce when valid transaction', async () => { - const signedTransaction = account.sign(transferTransaction, generationHash); const transactionAnnounceResponse = new TransactionAnnounceResponse('Some Message'); when(transactionRepositoryMock.announce(deepEqual(signedTransaction))).thenReturn(observableOf(transactionAnnounceResponse)); - when(listener.confirmed(deepEqual(account.address), deepEqual(signedTransaction.hash))) - .thenReturn(observableOf(transferTransaction)); + when(listener.confirmed(deepEqual(account.address), deepEqual(signedTransaction.hash))).thenReturn( + observableOf(transferTransaction), + ); when(listener.status(deepEqual(account.address))).thenReturn(EMPTY); @@ -101,11 +103,9 @@ describe('TransactionService', () => { const transaction = await announcedTransaction.toPromise(); expect(transaction).to.be.equal(transferTransaction); - }); it('announce when status error', async () => { - const signedTransaction = account.sign(transferTransaction, generationHash); const transactionAnnounceResponse = new TransactionAnnounceResponse('Some Message'); @@ -125,20 +125,20 @@ describe('TransactionService', () => { } catch (e) { expect(e.message).to.be.equal('Some Error'); } - }); it('Basic announceAggregateBonded when valid transaction', async () => { - const signedTransaction = account.sign(aggregateCompleteTransaction, generationHash); const transactionAnnounceResponse = new TransactionAnnounceResponse('Some Message'); - when(transactionRepositoryMock.announceAggregateBonded(deepEqual(signedTransaction))) - .thenReturn(observableOf(transactionAnnounceResponse)); + when(transactionRepositoryMock.announceAggregateBonded(deepEqual(signedTransaction))).thenReturn( + observableOf(transactionAnnounceResponse), + ); - when(listener.aggregateBondedAdded(deepEqual(account.address), deepEqual(signedTransaction.hash))) - .thenReturn(observableOf(aggregateCompleteTransaction)); + when(listener.aggregateBondedAdded(deepEqual(account.address), deepEqual(signedTransaction.hash))).thenReturn( + observableOf(aggregateCompleteTransaction), + ); when(listener.status(deepEqual(account.address))).thenReturn(EMPTY); const service = new TransactionService(instance(transactionRepositoryMock), instance(mockedReceiptRepository)); @@ -150,14 +150,13 @@ describe('TransactionService', () => { }); it('announceAggregateBonded when status error', async () => { - - const signedTransaction = account.sign(aggregateCompleteTransaction, - generationHash); + const signedTransaction = account.sign(aggregateCompleteTransaction, generationHash); const transactionAnnounceResponse = new TransactionAnnounceResponse('Some Message'); - when(transactionRepositoryMock.announceAggregateBonded(deepEqual(signedTransaction))) - .thenReturn(observableOf(transactionAnnounceResponse)); + when(transactionRepositoryMock.announceAggregateBonded(deepEqual(signedTransaction))).thenReturn( + observableOf(transactionAnnounceResponse), + ); when(listener.aggregateBondedAdded(deepEqual(account.address), deepEqual(signedTransaction.hash))).thenReturn(EMPTY); const statusError = new TransactionStatusError(account.address, signedTransaction.hash, 'Some Error', Deadline.create()); @@ -172,39 +171,42 @@ describe('TransactionService', () => { } catch (e) { expect(e.message).to.be.equal('Some Error'); } - }); it('announceHashLockAggregateBonded when ok', async () => { - const aggregateBondedSignedTransaction = account.sign(aggregateBondedTransaction, generationHash); const hashLockSignedTransaction = account.sign(hashLockTransaction, generationHash); const transactionAnnounceResponse = new TransactionAnnounceResponse('Some Message'); - when(transactionRepositoryMock.announceAggregateBonded(deepEqual(aggregateBondedSignedTransaction))) - .thenReturn(observableOf(transactionAnnounceResponse)); + when(transactionRepositoryMock.announceAggregateBonded(deepEqual(aggregateBondedSignedTransaction))).thenReturn( + observableOf(transactionAnnounceResponse), + ); - when(transactionRepositoryMock.announce(deepEqual(hashLockSignedTransaction))) - .thenReturn(observableOf(transactionAnnounceResponse)); + when(transactionRepositoryMock.announce(deepEqual(hashLockSignedTransaction))).thenReturn( + observableOf(transactionAnnounceResponse), + ); - when(listener.confirmed(deepEqual(account.address), deepEqual(hashLockSignedTransaction.hash))) - .thenReturn(observableOf(hashLockTransaction)); + when(listener.confirmed(deepEqual(account.address), deepEqual(hashLockSignedTransaction.hash))).thenReturn( + observableOf(hashLockTransaction), + ); - when(listener.aggregateBondedAdded(deepEqual(account.address), deepEqual(aggregateBondedSignedTransaction.hash))) - .thenReturn(observableOf(aggregateBondedTransaction)); + when(listener.aggregateBondedAdded(deepEqual(account.address), deepEqual(aggregateBondedSignedTransaction.hash))).thenReturn( + observableOf(aggregateBondedTransaction), + ); when(listener.status(deepEqual(account.address))).thenReturn(EMPTY); const service = new TransactionService(instance(transactionRepositoryMock), instance(mockedReceiptRepository)); - const announcedTransaction = service.announceHashLockAggregateBonded(hashLockSignedTransaction, aggregateBondedSignedTransaction, - instance(listener)); + const announcedTransaction = service.announceHashLockAggregateBonded( + hashLockSignedTransaction, + aggregateBondedSignedTransaction, + instance(listener), + ); const transaction = await announcedTransaction.toPromise(); expect(transaction).to.be.equal(aggregateBondedTransaction); - }); - }); diff --git a/tslint.json b/tslint.json deleted file mode 100644 index ded366576a..0000000000 --- a/tslint.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "defaultSeverity": "error", - "extends": [ - "tslint:recommended" - ], - "rulesDirectory": [ - ], - "rules": { - "arrow-return-shorthand": true, - "callable-types": true, - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "curly": true, - "eofline": true, - "forin": true, - "import-blacklist": [ - true, - "rxjs/Rx" - ], - "import-spacing": true, - "indent": [ - true, - "spaces" - ], - "interface-over-type-literal": true, - "interface-name": ["never-prefix"], - "label-position": true, - "max-line-length": [ - true, - 140 - ], - "member-access": false, - "member-ordering": [ - true, - { - "order": [ - "static-field", - "instance-field", - "static-method", - "instance-method" - ] - } - ], - "no-arg": true, - "no-bitwise": false, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], - "no-construct": true, - "no-debugger": true, - "no-duplicate-super": true, - "no-empty": false, - "no-empty-interface": true, - "no-eval": true, - "no-inferrable-types": [ - true, - "ignore-params" - ], - "no-misused-new": true, - "no-non-null-assertion": false, - "no-shadowed-variable": true, - "no-string-literal": false, - "no-string-throw": true, - "no-switch-case-fall-through": true, - "no-trailing-whitespace": true, - "no-unnecessary-initializer": true, - "no-unused-expression": false, - "no-use-before-declare": true, - "no-var-keyword": true, - "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "prefer-const": true, - "quotemark": [ - true, - "single" - ], - "radix": true, - "semicolon": [ - true, - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "typeof-compare": true, - "unified-signatures": true, - "variable-name": false, - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ], - "directive-selector": [ - true, - "attribute", - "app", - "camelCase" - ], - "component-selector": [ - true, - "element", - "app", - "kebab-case" - ], - "use-input-property-decorator": true, - "use-output-property-decorator": true, - "use-host-property-decorator": true, - "no-input-rename": true, - "no-output-rename": true, - "use-life-cycle-interface": true, - "use-pipe-transform-interface": true, - "component-class-suffix": true, - "directive-class-suffix": true, - "invoke-injectable": true - } -} From b3d5abf8897049b71a8509788da38928101552e9 Mon Sep 17 00:00:00 2001 From: Travis CI User Date: Mon, 20 Apr 2020 20:20:24 +0000 Subject: [PATCH 5/5] Creating new version 0.18.1 --- package-lock.json | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6286f3c703..4c987b5ae1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "symbol-sdk", - "version": "0.18.0", + "version": "0.18.1", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 80c2f5dbb2..aa01f1254a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "symbol-sdk", - "version": "0.18.0", + "version": "0.18.1", "description": "Reactive symbol sdk for typescript and javascript", "scripts": { "pretest": "npm run build",