From 36fe73199011bef3e8188aab95bfac55ce35a0dc Mon Sep 17 00:00:00 2001 From: marcohefti Date: Thu, 22 Dec 2022 20:10:36 +0700 Subject: [PATCH 01/13] Replace default export with named exports in utils package to enable tree shaking (fixes #1015) This change replaces the default export in the utils package with named exports, which allows for better tree shaking and smaller build sizes in user code applications. It also enforces the no-default-export ESLint rule to ensure consistent code style --- packages/utils/.eslintrc | 5 + packages/utils/src/amount.ts | 6 +- packages/utils/src/bignumber.ts | 2 +- packages/utils/src/cached-throttle.ts | 4 +- packages/utils/src/crypto.ts | 10 +- packages/utils/src/crypto/crypto-wrapper.ts | 2 +- packages/utils/src/crypto/ec-utils.ts | 2 +- packages/utils/src/encryption.ts | 18 ++-- packages/utils/src/estimate-gas-fees.ts | 8 +- packages/utils/src/identity.ts | 2 +- packages/utils/src/index.ts | 100 +++++++++++++----- packages/utils/src/providers.ts | 2 +- packages/utils/src/retry.ts | 4 +- packages/utils/src/signature.ts | 22 ++-- packages/utils/src/simple-logger.ts | 2 +- packages/utils/src/utils.ts | 8 +- packages/utils/test/amount.test.ts | 40 +++---- packages/utils/test/bignumber.test.ts | 18 ++-- packages/utils/test/cached-thottle.test.ts | 4 +- packages/utils/test/crypto.test.ts | 38 ++++--- .../utils/test/crypto/crypto-wrapper.test.ts | 5 +- packages/utils/test/crypto/ec-utils.test.ts | 46 ++++---- packages/utils/test/encryption.test.ts | 30 +++--- packages/utils/test/identity.test.ts | 10 +- packages/utils/test/retry.test.ts | 2 +- packages/utils/test/signature.test.ts | 23 ++-- packages/utils/test/simple-logger.test.ts | 2 +- packages/utils/test/utils.test.ts | 48 +++++---- 28 files changed, 265 insertions(+), 198 deletions(-) create mode 100644 packages/utils/.eslintrc diff --git a/packages/utils/.eslintrc b/packages/utils/.eslintrc new file mode 100644 index 000000000..f465e15ad --- /dev/null +++ b/packages/utils/.eslintrc @@ -0,0 +1,5 @@ +{ + "rules": { + "import/no-default-export": "error" + } +} diff --git a/packages/utils/src/amount.ts b/packages/utils/src/amount.ts index 9982f1e9d..424cf51e5 100644 --- a/packages/utils/src/amount.ts +++ b/packages/utils/src/amount.ts @@ -1,12 +1,12 @@ import { RequestLogicTypes } from '@requestnetwork/types'; -import Utils from './utils'; +import { isString } from './utils'; import { BigNumber } from 'ethers'; /** * Function to manage amounts */ -export default { +export { add, isValid, reduce, @@ -23,7 +23,7 @@ const regexInteger = RegExp(/^[\d]+$/); */ function isValid(amount: RequestLogicTypes.Amount | BigNumber): boolean { return ( - (Utils.isString(amount) && regexInteger.test(amount as string)) || + (isString(amount) && regexInteger.test(amount as string)) || (typeof amount === 'number' && Number.isSafeInteger(Number(amount)) && Number(amount) >= 0) ); } diff --git a/packages/utils/src/bignumber.ts b/packages/utils/src/bignumber.ts index 876db4126..68e7053b9 100644 --- a/packages/utils/src/bignumber.ts +++ b/packages/utils/src/bignumber.ts @@ -8,4 +8,4 @@ const min = (a: BigNumberish, b: BigNumberish): BigNumber => const max = (a: BigNumberish, b: BigNumberish): BigNumber => BigNumber.from(a).gt(b) ? BigNumber.from(a) : BigNumber.from(b); -export default { min, max }; +export { min, max }; diff --git a/packages/utils/src/cached-throttle.ts b/packages/utils/src/cached-throttle.ts index 175f9bd40..cd98bc061 100644 --- a/packages/utils/src/cached-throttle.ts +++ b/packages/utils/src/cached-throttle.ts @@ -5,7 +5,7 @@ * @param target The target function * @param minimumDelay The minimum delay between calls to the target function in milliseconds */ -export const cachedThrottle = ( +const cachedThrottle = ( target: (...params: TParams) => Promise, minimumDelay: number, ): ((...params: TParams) => Promise) => { @@ -29,4 +29,4 @@ export const cachedThrottle = ( }; }; -export default cachedThrottle; +export { cachedThrottle }; diff --git a/packages/utils/src/crypto.ts b/packages/utils/src/crypto.ts index 11acb1f3e..8f74190ab 100644 --- a/packages/utils/src/crypto.ts +++ b/packages/utils/src/crypto.ts @@ -1,13 +1,13 @@ import { MultiFormatTypes } from '@requestnetwork/types'; import { ethers } from 'ethers'; -import CryptoWrapper from './crypto/crypto-wrapper'; -import EcUtils from './crypto/ec-utils'; -import Utils from './utils'; +import { CryptoWrapper } from './crypto/crypto-wrapper'; +import { EcUtils } from './crypto/ec-utils'; +import { deepSort } from './utils'; /** * manages crypto functions */ -export default { +export { CryptoWrapper, EcUtils, generate32BufferKey, @@ -45,7 +45,7 @@ function normalize(data: unknown): string { } // deeply sort data keys - const sortedData = Utils.deepSort(data); + const sortedData = deepSort(data); // convert to string and lowerCase it, to be case insensitive (e.g: avoid ethereum address casing checksum) return JSON.stringify(sortedData).toLowerCase(); diff --git a/packages/utils/src/crypto/crypto-wrapper.ts b/packages/utils/src/crypto/crypto-wrapper.ts index a102e47fd..8517f6d38 100644 --- a/packages/utils/src/crypto/crypto-wrapper.ts +++ b/packages/utils/src/crypto/crypto-wrapper.ts @@ -3,7 +3,7 @@ import { createCipheriv, createDecipheriv, randomBytes as cryptoRandomBytes } fr /** * Functions to manage native crypto functions of nodeJs */ -export default { +export const CryptoWrapper = { decryptWithAes256cbc, decryptWithAes256gcm, encryptWithAes256cbc, diff --git a/packages/utils/src/crypto/ec-utils.ts b/packages/utils/src/crypto/ec-utils.ts index 3030d9b51..78c097b1d 100644 --- a/packages/utils/src/crypto/ec-utils.ts +++ b/packages/utils/src/crypto/ec-utils.ts @@ -4,7 +4,7 @@ import { ethers } from 'ethers'; /** * Function to manage Elliptic-curve cryptography */ -export default { +export const EcUtils = { decrypt, encrypt, getAddressFromPrivateKey, diff --git a/packages/utils/src/encryption.ts b/packages/utils/src/encryption.ts index feddb5c62..1f2ffd054 100644 --- a/packages/utils/src/encryption.ts +++ b/packages/utils/src/encryption.ts @@ -1,10 +1,10 @@ import { EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Crypto from './crypto'; +import { CryptoWrapper, EcUtils } from './crypto'; /** * Functions to manage encryption */ -export default { +export { decrypt, encrypt, getIdentityFromEncryptionParams, @@ -23,7 +23,7 @@ function getIdentityFromEncryptionParams( if (encryptionParams.method === EncryptionTypes.METHOD.ECIES) { return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, - value: Crypto.EcUtils.getAddressFromPublicKey(encryptionParams.key), + value: EcUtils.getAddressFromPublicKey(encryptionParams.key), }; } @@ -42,7 +42,7 @@ async function encrypt( encryptionParams: EncryptionTypes.IEncryptionParameters, ): Promise { if (encryptionParams.method === EncryptionTypes.METHOD.ECIES) { - const encryptedData = await Crypto.EcUtils.encrypt(encryptionParams.key, data); + const encryptedData = await EcUtils.encrypt(encryptionParams.key, data); return { type: EncryptionTypes.METHOD.ECIES, value: encryptedData, @@ -50,7 +50,7 @@ async function encrypt( } if (encryptionParams.method === EncryptionTypes.METHOD.AES256_CBC) { - const encryptedDataBuffer = await Crypto.CryptoWrapper.encryptWithAes256cbc( + const encryptedDataBuffer = await CryptoWrapper.encryptWithAes256cbc( Buffer.from(data, 'utf-8'), Buffer.from(encryptionParams.key, 'base64'), ); @@ -61,7 +61,7 @@ async function encrypt( } if (encryptionParams.method === EncryptionTypes.METHOD.AES256_GCM) { - const encryptedDataBuffer = await Crypto.CryptoWrapper.encryptWithAes256gcm( + const encryptedDataBuffer = await CryptoWrapper.encryptWithAes256gcm( Buffer.from(data, 'utf-8'), Buffer.from(encryptionParams.key, 'base64'), ); @@ -91,14 +91,14 @@ async function decrypt( if (decryptionParams.method !== EncryptionTypes.METHOD.ECIES) { throw new Error(`decryptionParams.method should be ${EncryptionTypes.METHOD.ECIES}`); } - return Crypto.EcUtils.decrypt(decryptionParams.key, encryptedData.value); + return EcUtils.decrypt(decryptionParams.key, encryptedData.value); } if (encryptedData.type === EncryptionTypes.METHOD.AES256_CBC) { if (decryptionParams.method !== EncryptionTypes.METHOD.AES256_CBC) { throw new Error(`decryptionParams.method should be ${EncryptionTypes.METHOD.AES256_CBC}`); } - const dataBuffer = await Crypto.CryptoWrapper.decryptWithAes256cbc( + const dataBuffer = await CryptoWrapper.decryptWithAes256cbc( // remove the multi-format padding and decode from the base64 to a buffer Buffer.from(encryptedData.value, 'base64'), Buffer.from(decryptionParams.key, 'base64'), @@ -111,7 +111,7 @@ async function decrypt( throw new Error(`decryptionParams.method should be ${EncryptionTypes.METHOD.AES256_GCM}`); } - const dataBuffer = await Crypto.CryptoWrapper.decryptWithAes256gcm( + const dataBuffer = await CryptoWrapper.decryptWithAes256gcm( // remove the multi-format padding and decode from the base64 to a buffer Buffer.from(encryptedData.value, 'base64'), Buffer.from(decryptionParams.key, 'base64'), diff --git a/packages/utils/src/estimate-gas-fees.ts b/packages/utils/src/estimate-gas-fees.ts index 15f4ebce1..ce8496290 100644 --- a/packages/utils/src/estimate-gas-fees.ts +++ b/packages/utils/src/estimate-gas-fees.ts @@ -1,6 +1,6 @@ import { BigNumber, constants, providers } from 'ethers'; import { suggestFees } from 'eip1559-fee-suggestions-ethers'; -import Utils from './index'; +import { max } from './index'; /** * The function estimates gas fee with EIP-1559. @@ -25,9 +25,9 @@ async function estimateGasFees({ }> { const suggestedFee = await suggestFees(provider as providers.JsonRpcProvider); - const baseFee = Utils.max(suggestedFee.baseFeeSuggestion, gasPriceMin || constants.Zero); + const baseFee = max(suggestedFee.baseFeeSuggestion, gasPriceMin || constants.Zero); - const maxPriorityFeePerGas = Utils.max( + const maxPriorityFeePerGas = max( suggestedFee.maxPriorityFeeSuggestions.urgent, gasPriceMin || constants.Zero, ); @@ -43,4 +43,4 @@ async function estimateGasFees({ }; } -export default estimateGasFees; +export { estimateGasFees }; diff --git a/packages/utils/src/identity.ts b/packages/utils/src/identity.ts index dc0b52c97..31c8abd14 100644 --- a/packages/utils/src/identity.ts +++ b/packages/utils/src/identity.ts @@ -8,7 +8,7 @@ const supportedIdentities: IdentityTypes.TYPE[] = [ /** * Module to manage Request Logic Identity */ -export default { +export { areEqual, hasError, normalizeIdentityValue, diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 71289d729..a4f173775 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -1,30 +1,78 @@ -import amount from './amount'; -import cachedThrottle from './cached-throttle'; -import crypto from './crypto'; -import encryption from './encryption'; -import identity from './identity'; -import retry from './retry'; -import signature from './signature'; -import SimpleLogger from './simple-logger'; -import utils from './utils'; -import providers from './providers'; -import bignumbers from './bignumber'; -import estimateGasFees from './estimate-gas-fees'; - /** * Collection of general purpose utility function */ -export default { - SimpleLogger, - amount, + +export { + add, + isValid, + reduce, +} from './amount'; + +export { + min, + max, +} from './bignumber'; + +export { cachedThrottle, - crypto, - encryption, - identity, - retry, - signature, - ...providers, - ...utils, - ...bignumbers, - estimateGasFees, -}; +} from './cached-throttle'; + +export { + CryptoWrapper, + EcUtils, + generate32BufferKey, + generate8randomBytes, + keccak256Hash, + last20bytesOfNormalizedKeccak256Hash, + normalize, + normalizeKeccak256Hash, +} from './crypto'; + +export { + decrypt, + encrypt, + getIdentityFromEncryptionParams, +} from './encryption'; + +export { estimateGasFees } from './estimate-gas-fees'; + +export { + areEqual, + hasError, + normalizeIdentityValue, + supportedIdentities, +} from './identity'; + +export { + setProviderFactory, + initPaymentDetectionApiKeys, + getDefaultProvider, + getCeloProvider, + networkRpcs, +} from './providers'; + +export { retry } from './retry'; + +export { + getIdentityFromSignatureParams, + recover, + sign, +} from './signature'; + +export { + SimpleLogger, +} from './simple-logger'; + +export { + deepCopy, + deepSort, + flatten2DimensionsArray, + getCurrentTimestampInSecond, + isString, + timeoutPromise, + unique, + uniqueByProperty, + notNull, +} from './utils'; + + diff --git a/packages/utils/src/providers.ts b/packages/utils/src/providers.ts index 6eb2b3fa1..0748e6c5f 100644 --- a/packages/utils/src/providers.ts +++ b/packages/utils/src/providers.ts @@ -146,7 +146,7 @@ const getCeloProvider = (): providers.Provider => { return provider; }; -export default { +export { setProviderFactory, initPaymentDetectionApiKeys, getDefaultProvider, diff --git a/packages/utils/src/retry.ts b/packages/utils/src/retry.ts index 10a20e21d..fe534442c 100644 --- a/packages/utils/src/retry.ts +++ b/packages/utils/src/retry.ts @@ -13,7 +13,7 @@ const DEFAULT_RETRY_DELAY = 100; * @param [options.maxRetries=DEFAULT_MAX_RETRIES] The maximum amount of retries for the function * @param [options.retryDelay=DEFAULT_RETRY_DELAY] The delay between retries */ -export const retry = ( +const retry = ( target: (...params: TParams) => TReturn | Promise, { context, @@ -57,4 +57,4 @@ export const retry = ( }; }; -export default retry; +export { retry }; diff --git a/packages/utils/src/signature.ts b/packages/utils/src/signature.ts index 0ec39b24b..2ff396645 100644 --- a/packages/utils/src/signature.ts +++ b/packages/utils/src/signature.ts @@ -1,11 +1,11 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import { ethers } from 'ethers'; -import Crypto from './crypto'; +import { EcUtils, normalize, normalizeKeccak256Hash } from './crypto'; /** * Function to manage Request Logic Signature */ -export default { +export { getIdentityFromSignatureParams, recover, sign, @@ -27,7 +27,7 @@ function getIdentityFromSignatureParams( if (signatureParams.method === SignatureTypes.METHOD.ECDSA) { return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, - value: Crypto.EcUtils.getAddressFromPrivateKey(signatureParams.privateKey), + value: EcUtils.getAddressFromPrivateKey(signatureParams.privateKey), }; } @@ -49,16 +49,16 @@ function sign( ): SignatureTypes.ISignedData { let value: string; if (signatureParams.method === SignatureTypes.METHOD.ECDSA) { - value = Crypto.EcUtils.sign( + value = EcUtils.sign( signatureParams.privateKey, - Crypto.normalizeKeccak256Hash(data).value, + normalizeKeccak256Hash(data).value, ); return { data, signature: { method: signatureParams.method, value } }; } if (signatureParams.method === SignatureTypes.METHOD.ECDSA_ETHEREUM) { - const normalizedData = Crypto.normalize(data); - value = Crypto.EcUtils.sign( + const normalizedData = normalize(data); + value = EcUtils.sign( signatureParams.privateKey, ethers.utils.hashMessage(normalizedData), ); @@ -80,9 +80,9 @@ function sign( function recover(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentity { let value: string; if (signedData.signature.method === SignatureTypes.METHOD.ECDSA) { - value = Crypto.EcUtils.recover( + value = EcUtils.recover( signedData.signature.value, - Crypto.normalizeKeccak256Hash(signedData.data).value, + normalizeKeccak256Hash(signedData.data).value, ); return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, @@ -101,8 +101,8 @@ function recover(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentit } else if (v.toLowerCase() === '01') { signature = `${signedData.signature.value.slice(0, V_POSITION_FROM_END_IN_ECDSA_HEX)}1b`; } - const normalizedData = ethers.utils.hashMessage(Crypto.normalize(signedData.data)); - value = Crypto.EcUtils.recover(signature, normalizedData).toLowerCase(); + const normalizedData = ethers.utils.hashMessage(normalize(signedData.data)); + value = EcUtils.recover(signature, normalizedData).toLowerCase(); return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, diff --git a/packages/utils/src/simple-logger.ts b/packages/utils/src/simple-logger.ts index 45b2595e4..a2f709d10 100644 --- a/packages/utils/src/simple-logger.ts +++ b/packages/utils/src/simple-logger.ts @@ -7,7 +7,7 @@ const DEFAULT_LOG_LEVEL = LogTypes.LogLevel.QUIET; /** * Simple logger that outputs content to the console. */ -export default class SimpleLogger implements LogTypes.ILogger { +export class SimpleLogger implements LogTypes.ILogger { /** * maxLogLevel, the maximum log level to display */ diff --git a/packages/utils/src/utils.ts b/packages/utils/src/utils.ts index 5e8f622f4..f512a539e 100644 --- a/packages/utils/src/utils.ts +++ b/packages/utils/src/utils.ts @@ -1,9 +1,9 @@ -import crypto from './crypto'; +import { normalizeKeccak256Hash } from './crypto'; /** * Collection of general purpose utility function */ -export default { +export { deepCopy, deepSort, flatten2DimensionsArray, @@ -77,7 +77,7 @@ function unique(array: T[]): { uniqueItems: T[]; duplicates: T[] } { accumulator: { uniqueItems: T[]; duplicates: T[]; uniqueItemsHashes: string[] }, element: T, ) => { - const hash = crypto.normalizeKeccak256Hash(element); + const hash = normalizeKeccak256Hash(element); if (accumulator.uniqueItemsHashes.includes(hash.value)) { // if already included, adds it to the array of duplicates @@ -109,7 +109,7 @@ function uniqueByProperty(array: T[], property: keyof T): { uniqueItems: T[]; accumulator: { uniqueItems: T[]; duplicates: T[]; uniqueItemsHashes: string[] }, element: T, ) => { - const hash = crypto.normalizeKeccak256Hash(element[property]); + const hash = normalizeKeccak256Hash(element[property]); if (accumulator.uniqueItemsHashes.includes(hash.value)) { // if already included, adds it to the array of duplicates diff --git a/packages/utils/test/amount.test.ts b/packages/utils/test/amount.test.ts index 4d8892487..e43c6823c 100644 --- a/packages/utils/test/amount.test.ts +++ b/packages/utils/test/amount.test.ts @@ -1,6 +1,6 @@ import { BigNumber } from 'ethers'; -import Amount from '../src/amount'; +import { add, isValid, reduce } from '../src'; const magicIntegerSmall = 10000; const magicIntegerBig = 1000000000000000000000000000000; @@ -19,67 +19,67 @@ describe('Amount', () => { describe('isValid', () => { it('can valid amount as small integer', () => { // 'integer should be valid' - expect(Amount.isValid(magicIntegerSmall)).toBe(true); + expect(isValid(magicIntegerSmall)).toBe(true); }); it('cannot valid amount as big integer', () => { // 'Big integer should not be valid' - expect(Amount.isValid(magicIntegerBig)).toBe(false); + expect(isValid(magicIntegerBig)).toBe(false); }); it('cannot valid amount as bn', () => { // 'BN should not be valid' - expect(Amount.isValid(BigNumber.from('1000000000000000000000000'))).toBe(false); + expect(isValid(BigNumber.from('1000000000000000000000000'))).toBe(false); }); it('can valid amount as string representing integer', () => { // 'integer as string should be valid' - expect(Amount.isValid('10000')).toBe(true); + expect(isValid('10000')).toBe(true); }); it('cannot valid amount as a small decimal', () => { // 'decimal should not be valid' - expect(Amount.isValid(magicFloatSmall)).toBe(false); + expect(isValid(magicFloatSmall)).toBe(false); }); it('cannot valid amount as a big decimal', () => { // 'decimal should not be valid' - expect(Amount.isValid(magicFloatBig)).toBe(false); + expect(isValid(magicFloatBig)).toBe(false); }); it('cannot valid amount as string representing small decimal', () => { // 'decimal as string should not be valid' - expect(Amount.isValid('10000.01')).toBe(false); + expect(isValid('10000.01')).toBe(false); }); it('cannot valid amount as string representing big decimal', () => { // 'decimal as string should not be valid' - expect(Amount.isValid('1000000000000000000000000000000000.01')).toBe(false); + expect(isValid('1000000000000000000000000000000000.01')).toBe(false); }); it('cannot valid amount as not number', () => { // 'Not number should not be valid' - expect(Amount.isValid('Not a number')).toBe(false); + expect(isValid('Not a number')).toBe(false); }); it('cannot valid amount as small integer', () => { // 'integer should not be valid' - expect(Amount.isValid(-magicIntegerSmall)).toBe(false); + expect(isValid(-magicIntegerSmall)).toBe(false); }); it('cannot valid amount as big integer negative', () => { // 'Big integer should not be valid' - expect(Amount.isValid(-magicIntegerBig)).toBe(false); + expect(isValid(-magicIntegerBig)).toBe(false); }); it('cannot valid an empty string', () => { // 'Empty string should not be valid' - expect(Amount.isValid('')).toBe(false); + expect(isValid('')).toBe(false); }); }); describe('add', () => { it('cannot add amounts not number', () => { - expect(() => Amount.add('Not a number', '1000000000000000000')).toThrowError( + expect(() => add('Not a number', '1000000000000000000')).toThrowError( 'amount must represent a positive integer', ); - expect(() => Amount.add('1000000000000000000', 'Not a number')).toThrowError( + expect(() => add('1000000000000000000', 'Not a number')).toThrowError( 'delta must represent a positive integer', ); }); it('can add two amounts', () => { // 'add() result is wrong' - expect(Amount.add(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( + expect(add(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( arbitraryExpectedAmountPlusDelta, ); }); @@ -87,22 +87,22 @@ describe('Amount', () => { describe('reduce', () => { it('cannot reduce amounts not number', () => { - expect(() => Amount.reduce('Not a number', '1000000000000000000')).toThrowError( + expect(() => reduce('Not a number', '1000000000000000000')).toThrowError( 'amount must represent a positive integer', ); - expect(() => Amount.reduce('1000000000000000000', 'Not a number')).toThrowError( + expect(() => reduce('1000000000000000000', 'Not a number')).toThrowError( 'delta must represent a positive integer', ); }); it('can reduce two amounts', () => { // 'reduce() result is wrong' - expect(Amount.reduce(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( + expect(reduce(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( arbitraryExpectedAmountMinusDelta, ); }); it('cannot reduce lower zero', () => { - expect(() => Amount.reduce(arbitraryDeltaAmount, arbitraryExpectedAmount)).toThrowError( + expect(() => reduce(arbitraryDeltaAmount, arbitraryExpectedAmount)).toThrowError( 'result of reduce is not valid', ); }); diff --git a/packages/utils/test/bignumber.test.ts b/packages/utils/test/bignumber.test.ts index 73135f12b..62a640591 100644 --- a/packages/utils/test/bignumber.test.ts +++ b/packages/utils/test/bignumber.test.ts @@ -1,26 +1,26 @@ import { BigNumber } from '@ethersproject/bignumber'; -import Utils from '../src'; +import { max, min } from '../src'; describe('min', () => { it('returns the min of 2 big numbers', () => { - expect(Utils.min(1, 2)).toMatchObject(BigNumber.from(1)); - expect(Utils.min(2, 1)).toMatchObject(BigNumber.from(1)); + expect(min(1, 2)).toMatchObject(BigNumber.from(1)); + expect(min(2, 1)).toMatchObject(BigNumber.from(1)); }); it('supports 0', () => { - expect(Utils.min(1, 0)).toMatchObject(BigNumber.from(0)); - expect(Utils.min(0, 1)).toMatchObject(BigNumber.from(0)); + expect(min(1, 0)).toMatchObject(BigNumber.from(0)); + expect(min(0, 1)).toMatchObject(BigNumber.from(0)); }); }); describe('max', () => { it('returns the max of 2 big numbers', () => { - expect(Utils.max(1, 2)).toMatchObject(BigNumber.from(2)); - expect(Utils.max(2, 1)).toMatchObject(BigNumber.from(2)); + expect(max(1, 2)).toMatchObject(BigNumber.from(2)); + expect(max(2, 1)).toMatchObject(BigNumber.from(2)); }); it('supports 0', () => { - expect(Utils.max(1, 0)).toMatchObject(BigNumber.from(1)); - expect(Utils.max(0, 1)).toMatchObject(BigNumber.from(1)); + expect(max(1, 0)).toMatchObject(BigNumber.from(1)); + expect(max(0, 1)).toMatchObject(BigNumber.from(1)); }); }); diff --git a/packages/utils/test/cached-thottle.test.ts b/packages/utils/test/cached-thottle.test.ts index 59ca968b0..fed1d7b67 100644 --- a/packages/utils/test/cached-thottle.test.ts +++ b/packages/utils/test/cached-thottle.test.ts @@ -1,6 +1,6 @@ -import cachedThrottle from '../src/cached-throttle'; - /* eslint-disable no-magic-numbers */ +import { cachedThrottle } from '../src'; + describe('Cached Throttle', () => { it('throttles a function', async () => { jest.useFakeTimers('modern'); diff --git a/packages/utils/test/crypto.test.ts b/packages/utils/test/crypto.test.ts index 085020ffe..add011527 100644 --- a/packages/utils/test/crypto.test.ts +++ b/packages/utils/test/crypto.test.ts @@ -1,5 +1,11 @@ import { MultiFormatTypes } from '@requestnetwork/types'; -import crypto from '../src/crypto'; +import { + generate32BufferKey, + generate8randomBytes, + last20bytesOfNormalizedKeccak256Hash, + normalize, + normalizeKeccak256Hash, +} from '../src'; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('Utils.crypto', () => { @@ -10,7 +16,7 @@ describe('Utils.crypto', () => { param3: 'valA', }; // 'normalizeKeccak256Hash(arbitraryObject) error' - expect(crypto.normalizeKeccak256Hash(arbitraryObject)).toEqual({ + expect(normalizeKeccak256Hash(arbitraryObject)).toEqual({ type: MultiFormatTypes.HashTypes.TYPE.KECCAK256, value: '0xaf91330fe78ccde898f10a39d6088568e24275a6cfbe9e80f4c2f42a4308f907', }); @@ -31,12 +37,12 @@ describe('Utils.crypto', () => { }; /* eslint-enable */ // 'normalizeKeccak256Hash(arbitraryObject) error' - expect(crypto.normalizeKeccak256Hash(arbitraryObject)).toEqual({ + expect(normalizeKeccak256Hash(arbitraryObject)).toEqual({ type: MultiFormatTypes.HashTypes.TYPE.KECCAK256, value: '0xaf91330fe78ccde898f10a39d6088568e24275a6cfbe9e80f4c2f42a4308f907', }); // 'normalizeKeccak256Hash(arbitraryObjectSame) error' - expect(crypto.normalizeKeccak256Hash(arbitraryObjectSame)).toEqual({ + expect(normalizeKeccak256Hash(arbitraryObjectSame)).toEqual({ type: MultiFormatTypes.HashTypes.TYPE.KECCAK256, value: '0xaf91330fe78ccde898f10a39d6088568e24275a6cfbe9e80f4c2f42a4308f907', }); @@ -71,27 +77,27 @@ describe('Utils.crypto', () => { }; /* eslint-enable */ // 'normalizeKeccak256Hash(arbitraryObject) error' - expect(crypto.normalizeKeccak256Hash(arbitraryObject)).toEqual({ + expect(normalizeKeccak256Hash(arbitraryObject)).toEqual({ type: MultiFormatTypes.HashTypes.TYPE.KECCAK256, value: '0x7c36b5b8c7c5e787838a8ad5b083f3c9326bf364aa9e35691140f15c9a94f786', }); // 'normalizeKeccak256Hash(arbitraryObjectSame) error' - expect(crypto.normalizeKeccak256Hash(arbitraryObjectSame)).toEqual({ + expect(normalizeKeccak256Hash(arbitraryObjectSame)).toEqual({ type: MultiFormatTypes.HashTypes.TYPE.KECCAK256, value: '0x7c36b5b8c7c5e787838a8ad5b083f3c9326bf364aa9e35691140f15c9a94f786', }); }); it('can normalize integer, null, string, undefined', () => { - expect(crypto.normalize('TesT')).toBe('"test"'); + expect(normalize('TesT')).toBe('"test"'); // eslint-disable-next-line no-magic-numbers - expect(crypto.normalize(12345)).toBe('12345'); - expect(crypto.normalize(null)).toBe('null'); - expect(crypto.normalize(undefined)).toBe('undefined'); + expect(normalize(12345)).toBe('12345'); + expect(normalize(null)).toBe('null'); + expect(normalize(undefined)).toBe('undefined'); }); it('can generate32BufferKey()', async () => { - const randomKey = await crypto.generate32BufferKey(); + const randomKey = await generate32BufferKey(); // 'random32Bytes() error' expect(Buffer.from(randomKey, 'base64').length).toBe(32); }); @@ -102,7 +108,7 @@ describe('Utils.crypto', () => { param2: 'valB', param3: 'valA', }; - expect(crypto.last20bytesOfNormalizedKeccak256Hash(arbitraryObject)).toEqual( + expect(last20bytesOfNormalizedKeccak256Hash(arbitraryObject)).toEqual( '0xd6088568e24275a6cfbe9e80f4c2f42a4308f907', ); }); @@ -113,7 +119,7 @@ describe('Utils.crypto', () => { it('generates a 16 characters long string', async () => { // Do it 20 times because it's random. It's ok, it takes a few milliseconds for (let i = 0; i < 100; i++) { - expect((await crypto.generate8randomBytes()).length).toBe(16); + expect((await generate8randomBytes()).length).toBe(16); } }); @@ -123,13 +129,13 @@ describe('Utils.crypto', () => { // Do it 20 times because it's random. It's ok, it takes a few milliseconds for (let i = 0; i < 100; i++) { - expect(eightHexRegex.test(await crypto.generate8randomBytes())).toBe(true); + expect(eightHexRegex.test(await generate8randomBytes())).toBe(true); } }); it('generates unique strings', async () => { - const first = await crypto.generate8randomBytes(); - const second = await crypto.generate8randomBytes(); + const first = await generate8randomBytes(); + const second = await generate8randomBytes(); expect(first).not.toBe(second); }); }); diff --git a/packages/utils/test/crypto/crypto-wrapper.test.ts b/packages/utils/test/crypto/crypto-wrapper.test.ts index 80c63d325..4b1cb647a 100644 --- a/packages/utils/test/crypto/crypto-wrapper.test.ts +++ b/packages/utils/test/crypto/crypto-wrapper.test.ts @@ -1,5 +1,4 @@ -import CryptoWrapper from '../../src/crypto/crypto-wrapper'; -import utils from '../../src/utils'; +import { CryptoWrapper, unique } from '../../src'; const anyData = 'this is any data!'; const arbitraryKey = '12345678901234567890123456789012'; @@ -21,7 +20,7 @@ describe('Utils.cryptoWrapper', () => { const promises = new Array(1000).fill('').map(async () => CryptoWrapper.random32Bytes()); const randomBytes1000 = await Promise.all(promises); // 'randomBytes gives duplicate' - expect(utils.unique(randomBytes1000).duplicates.length).toBe(0); + expect(unique(randomBytes1000).duplicates.length).toBe(0); }); }); diff --git a/packages/utils/test/crypto/ec-utils.test.ts b/packages/utils/test/crypto/ec-utils.test.ts index 2b0c9f50d..1770e079c 100644 --- a/packages/utils/test/crypto/ec-utils.test.ts +++ b/packages/utils/test/crypto/ec-utils.test.ts @@ -1,4 +1,4 @@ -import ecUtils from '../../src/crypto/ec-utils'; +import { EcUtils } from '../../src'; const rawId = { address: '0x818B6337657A23F58581715Fc610577292e521D0', @@ -14,22 +14,22 @@ const rawId = { const anyData = 'this is any data!'; /* eslint-disable @typescript-eslint/no-unused-expressions */ -describe('Utils.ecUtils', () => { +describe('Utils.EcUtils', () => { describe('getAddressFromPrivateKey', () => { it('can get Address From PrivateKey', () => { - const identity = ecUtils.getAddressFromPrivateKey(rawId.privateKey); + const identity = EcUtils.getAddressFromPrivateKey(rawId.privateKey); // 'getAddressFromPrivateKey() error' expect(identity).toBe(rawId.address); }); it('cannot get Address From PrivateKey if the private key is wrong', () => { // 'getAddressFromPrivateKey() error' - expect(() => ecUtils.getAddressFromPrivateKey('aa')).toThrowError( + expect(() => EcUtils.getAddressFromPrivateKey('aa')).toThrowError( 'The private key must be a string representing 32 bytes', ); }); it('can get an address from a private key without 0x', () => { expect( - ecUtils.getAddressFromPrivateKey( + EcUtils.getAddressFromPrivateKey( 'af16c10a33bd8c2a0d55551080c3eb248ab727e5ff17d052c95f9d92b7e6528e', ), ).toBe('0xe011e28aBAa005223a2d4AEfFD5c2fF8D7B5291c'); @@ -38,13 +38,13 @@ describe('Utils.ecUtils', () => { describe('getAddressFromPublicKey', () => { it('can get Address From Public Key', () => { - const identity = ecUtils.getAddressFromPublicKey(rawId.publicKey); + const identity = EcUtils.getAddressFromPublicKey(rawId.publicKey); // 'getAddressFromPublicKey() error' expect(identity).toBe(rawId.address); }); it('cannot get Address From Public Key if the Public key is wrong', () => { // 'getAddressFromPrivateKey() error' - expect(() => ecUtils.getAddressFromPublicKey('aa')).toThrowError( + expect(() => EcUtils.getAddressFromPublicKey('aa')).toThrowError( 'The public key must be a string representing 64 bytes', ); }); @@ -52,7 +52,7 @@ describe('Utils.ecUtils', () => { describe('sign', () => { it('can sign', () => { - const signature = ecUtils.sign( + const signature = EcUtils.sign( rawId.privateKey, '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f', ); @@ -64,14 +64,14 @@ describe('Utils.ecUtils', () => { it('cannot signs if the private key is wrong', () => { // 'sign() error' expect(() => - ecUtils.sign('aa', '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f'), + EcUtils.sign('aa', '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f'), ).toThrowError('The private key must be a string representing 32 bytes'); }); }); describe('recover', () => { it('can recover address from a signature', () => { - const id = ecUtils.recover( + const id = EcUtils.recover( '0xdf4d49c7c01e00a970378e5a400dd4168aed6c43a1c510b124026467c78a3566048549c6ab5e0f618e2939c518e9fbe52e07836d4cb07fa44186fa3ffe3b3b981b', '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f', ); @@ -81,7 +81,7 @@ describe('Utils.ecUtils', () => { it('cannot recover address from signature if signature is not well formatted', () => { // 'sign() error' expect(() => - ecUtils.recover( + EcUtils.recover( '0xaa', '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f', ), @@ -91,15 +91,15 @@ describe('Utils.ecUtils', () => { describe('encrypt', () => { it('can encrypt', async () => { - const encryptedData = await ecUtils.encrypt(rawId.publicKey, anyData); + const encryptedData = await EcUtils.encrypt(rawId.publicKey, anyData); // 'encrypt() error' expect(encryptedData.length).toBe(226); // 'decrypt() error' - expect(await ecUtils.decrypt(rawId.privateKey, encryptedData)).toBe(anyData); + expect(await EcUtils.decrypt(rawId.privateKey, encryptedData)).toBe(anyData); }); it('can encrypt with other public key formats', async () => { - const encryptedData = await ecUtils.encrypt( + const encryptedData = await EcUtils.encrypt( '0396212fc129c2f78771218b2e93da7a5aac63490a42bb41b97848c39c14fe65cd', anyData, ); @@ -107,7 +107,7 @@ describe('Utils.ecUtils', () => { }); it('cannot encrypt data with a wrong public key', async () => { - await expect(ecUtils.encrypt('cf4a', anyData)).rejects.toThrowError( + await expect(EcUtils.encrypt('cf4a', anyData)).rejects.toThrowError( 'The public key must be a string representing 64 bytes', ); }); @@ -115,7 +115,7 @@ describe('Utils.ecUtils', () => { describe('decrypt', () => { it('can decrypt', async () => { - const data = await ecUtils.decrypt( + const data = await EcUtils.decrypt( rawId.privateKey, '307bac038efaa5bf8a0ac8db53fd4de8024a0c0baf37283a9e6671589eba18edc12b3915ff0df66e6ffad862440228a65ead99e3320e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc70a', ); @@ -125,7 +125,7 @@ describe('Utils.ecUtils', () => { it('cannot decrypt data with a wrong private key', async () => { await expect( - ecUtils.decrypt( + EcUtils.decrypt( '0xaa', '307bac038efaa5bf8a0ac8db53fd4de8024a0c0baf37283a9e6671589eba18edc12b3915ff0df66e6ffad862440228a65ead99e3320e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc70a', ), @@ -133,14 +133,14 @@ describe('Utils.ecUtils', () => { }); it('cannot decrypt data with a wrong encrypted data: public key too short', async () => { - await expect(ecUtils.decrypt(rawId.privateKey, 'aa')).rejects.toThrowError( + await expect(EcUtils.decrypt(rawId.privateKey, 'aa')).rejects.toThrowError( 'The encrypted data is not well formatted', ); }); it('cannot decrypt data with a wrong encrypted data: public key not parsable', async () => { await expect( - ecUtils.decrypt( + EcUtils.decrypt( rawId.privateKey, 'e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc7', ), @@ -149,7 +149,7 @@ describe('Utils.ecUtils', () => { it('cannot decrypt data with a wrong encrypted data: bad MAC', async () => { await expect( - ecUtils.decrypt( + EcUtils.decrypt( rawId.privateKey, '307bac038efaa5bf8a0ac8db53fd4de8024a0c0baf37283a9e6671589eba18edc12b3915ff0df66e6ffad862440228a65ead99e3320e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc7', ), @@ -158,15 +158,15 @@ describe('Utils.ecUtils', () => { }); it('can encrypt()', async () => { - const encryptedData = await ecUtils.encrypt(rawId.publicKey, anyData); + const encryptedData = await EcUtils.encrypt(rawId.publicKey, anyData); // 'encrypt() error' expect(encryptedData.length).toBe(226); // 'decrypt() error' - expect(await ecUtils.decrypt(rawId.privateKey, encryptedData)).toBe(anyData); + expect(await EcUtils.decrypt(rawId.privateKey, encryptedData)).toBe(anyData); }); it('can decrypt()', async () => { - const data = await ecUtils.decrypt( + const data = await EcUtils.decrypt( rawId.privateKey, '307bac038efaa5bf8a0ac8db53fd4de8024a0c0baf37283a9e6671589eba18edc12b3915ff0df66e6ffad862440228a65ead99e3320e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc70a', ); diff --git a/packages/utils/test/encryption.test.ts b/packages/utils/test/encryption.test.ts index 696496c91..8ecd6ed6d 100644 --- a/packages/utils/test/encryption.test.ts +++ b/packages/utils/test/encryption.test.ts @@ -1,5 +1,5 @@ import { EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Encryption from '../src/encryption'; +import { getIdentityFromEncryptionParams, encrypt, decrypt } from '../src'; const otherIdRaw = { address: '0x818B6337657A23F58581715Fc610577292e521D0', @@ -39,7 +39,7 @@ const data = { describe('Encryption', () => { describe('getIdentityFromEncryptionParams', () => { it('can getIdentityFromEncryptionParams()', () => { - const identity = Encryption.getIdentityFromEncryptionParams(otherIdRaw.encryptionParams); + const identity = getIdentityFromEncryptionParams(otherIdRaw.encryptionParams); // 'getIdentityFromEncryptionParams() error' expect(identity).toEqual(otherIdRaw.identity); }); @@ -49,7 +49,7 @@ describe('Encryption', () => { method: 'notECIES', publicKey: otherIdRaw.publicKey, }; - expect(() => Encryption.getIdentityFromEncryptionParams(params)).toThrowError( + expect(() => getIdentityFromEncryptionParams(params)).toThrowError( 'encryptionParams.method not supported', ); }); @@ -57,7 +57,7 @@ describe('Encryption', () => { describe('encrypt', () => { it('can encrypt with ECIES', async () => { - const encryptedData = await Encryption.encrypt( + const encryptedData = await encrypt( JSON.stringify(data), otherIdRaw.encryptionParams, ); @@ -66,13 +66,13 @@ describe('Encryption', () => { // 'encrypt() error' expect(encryptedData.type).toBe(EncryptionTypes.METHOD.ECIES); // 'decrypt() error' - expect(await Encryption.decrypt(encryptedData, otherIdRaw.decryptionParams)).toEqual( + expect(await decrypt(encryptedData, otherIdRaw.decryptionParams)).toEqual( JSON.stringify(data), ); }); it('can encrypt with AES256-cbc', async () => { - const encryptedData = await Encryption.encrypt( + const encryptedData = await encrypt( JSON.stringify(data), arbitraryAES256cbcEncryptionParams, ); @@ -81,13 +81,13 @@ describe('Encryption', () => { // 'encrypt() error' expect(encryptedData.type).toBe(EncryptionTypes.METHOD.AES256_CBC); // 'decrypt() error' - expect(await Encryption.decrypt(encryptedData, arbitraryAES256cbcEncryptionParams)).toEqual( + expect(await decrypt(encryptedData, arbitraryAES256cbcEncryptionParams)).toEqual( JSON.stringify(data), ); }); it('can encrypt with AES256-gcm', async () => { - const encryptedData = await Encryption.encrypt( + const encryptedData = await encrypt( JSON.stringify(data), arbitraryAES256gcmEncryptionParams, ); @@ -96,7 +96,7 @@ describe('Encryption', () => { // 'encrypt() error' expect(encryptedData.type).toBe(EncryptionTypes.METHOD.AES256_GCM); // 'decrypt() error' - expect(await Encryption.decrypt(encryptedData, arbitraryAES256gcmEncryptionParams)).toEqual( + expect(await decrypt(encryptedData, arbitraryAES256gcmEncryptionParams)).toEqual( JSON.stringify(data), ); }); @@ -107,7 +107,7 @@ describe('Encryption', () => { publicKey: otherIdRaw.publicKey, }; - await expect(Encryption.encrypt(JSON.stringify(data), params)).rejects.toThrowError( + await expect(encrypt(JSON.stringify(data), params)).rejects.toThrowError( 'encryptionParams.method not supported', ); }); @@ -115,7 +115,7 @@ describe('Encryption', () => { describe('decrypt', () => { it('can decrypt encrypted data', async () => { - const dataDecrypted = await Encryption.decrypt( + const dataDecrypted = await decrypt( { type: EncryptionTypes.METHOD.ECIES, value: @@ -129,7 +129,7 @@ describe('Encryption', () => { it('cannot decrypt with an encryption method not supported', async () => { await expect( - Encryption.decrypt( + decrypt( { type: 'not supported' as any, value: @@ -142,7 +142,7 @@ describe('Encryption', () => { it('cannot decrypt with the wrong decryption method', async () => { await expect( - Encryption.decrypt( + decrypt( { type: EncryptionTypes.METHOD.ECIES, value: 'c9a9', @@ -152,7 +152,7 @@ describe('Encryption', () => { ).rejects.toThrowError('decryptionParams.method should be ecies'); await expect( - Encryption.decrypt( + decrypt( { type: EncryptionTypes.METHOD.AES256_CBC, value: 'c9a9', @@ -162,7 +162,7 @@ describe('Encryption', () => { ).rejects.toThrowError('decryptionParams.method should be aes256-cbc'); await expect( - Encryption.decrypt( + decrypt( { type: EncryptionTypes.METHOD.AES256_GCM, value: 'c9a9', diff --git a/packages/utils/test/identity.test.ts b/packages/utils/test/identity.test.ts index 9d06a0b75..ca77dda8f 100644 --- a/packages/utils/test/identity.test.ts +++ b/packages/utils/test/identity.test.ts @@ -1,11 +1,11 @@ import { IdentityTypes } from '@requestnetwork/types'; -import Identity from '../src/identity'; +import { areEqual, normalizeIdentityValue } from '../src'; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('Identity', () => { it('can normalizeIdentityValue()', () => { // 'normalizeIdentityValue("") error' - expect(Identity.normalizeIdentityValue('0xe241d3757DAd0Ef86D0FCc5fE90e20f955743eD5')).toBe( + expect(normalizeIdentityValue('0xe241d3757DAd0Ef86D0FCc5fE90e20f955743eD5')).toBe( '0xe241d3757dad0ef86d0fcc5fe90e20f955743ed5', ); }); @@ -20,7 +20,7 @@ describe('Identity', () => { value: '0xe241d3757DAd0Ef86D0FCc5fE90e20f955743eD5', }; // 'areEqual() error' - expect(Identity.areEqual(id1, id2)).toBe(true); + expect(areEqual(id1, id2)).toBe(true); }); it('can areEqual() two identities with different cases', () => { @@ -33,7 +33,7 @@ describe('Identity', () => { value: '0xe241d3757dad0ef86d0fcc5fe90e20f955743ed5', }; // 'areEqual() error' - expect(Identity.areEqual(id1, id2)).toBe(true); + expect(areEqual(id1, id2)).toBe(true); }); it('cannot areEqual() two identities with differents values', () => { @@ -46,6 +46,6 @@ describe('Identity', () => { value: '0xFFFFFFFFFFFFFFf86D0FCc5fE90e20f955743eD5', }; // 'areEqual() error' - expect(Identity.areEqual(id1, id2)).toBe(false); + expect(areEqual(id1, id2)).toBe(false); }); }); diff --git a/packages/utils/test/retry.test.ts b/packages/utils/test/retry.test.ts index 566769947..5d143033b 100644 --- a/packages/utils/test/retry.test.ts +++ b/packages/utils/test/retry.test.ts @@ -1,4 +1,4 @@ -import retry from '../src/retry'; +import { retry } from '../src'; class TestClass { private value = 'private'; diff --git a/packages/utils/test/signature.test.ts b/packages/utils/test/signature.test.ts index e6a2f008e..f94b14f53 100644 --- a/packages/utils/test/signature.test.ts +++ b/packages/utils/test/signature.test.ts @@ -1,6 +1,5 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; -import Crypto from '../src/crypto'; -import Signature from '../src/signature'; +import { getIdentityFromSignatureParams, normalizeKeccak256Hash, recover, sign } from '../src'; const otherIdRaw = { address: '0x818B6337657A23F58581715Fc610577292e521D0', @@ -31,7 +30,7 @@ const dataDiffCase = { describe('Signature', () => { describe('getIdentityFromSignatureParams', () => { it('can getIdentityFromSignatureParams()', () => { - const identity = Signature.getIdentityFromSignatureParams({ + const identity = getIdentityFromSignatureParams({ method: SignatureTypes.METHOD.ECDSA, privateKey: otherIdRaw.privateKey, }); @@ -44,7 +43,7 @@ describe('Signature', () => { method: 'notECDSA', privateKey: otherIdRaw.privateKey, }; - expect(() => Signature.getIdentityFromSignatureParams(params)).toThrowError( + expect(() => getIdentityFromSignatureParams(params)).toThrowError( 'signatureParams.method not supported', ); }); @@ -52,7 +51,7 @@ describe('Signature', () => { describe('sign', () => { it('can sign() with ECDSA', () => { - const signature = Signature.sign(data, { + const signature = sign(data, { method: SignatureTypes.METHOD.ECDSA, privateKey: otherIdRaw.privateKey, }); @@ -68,7 +67,7 @@ describe('Signature', () => { }); it('can sign() with ECDSA_ETHEREUM', () => { - const signature = Signature.sign(data, { + const signature = sign(data, { method: SignatureTypes.METHOD.ECDSA_ETHEREUM, privateKey: otherIdRaw.privateKey, }); @@ -84,7 +83,7 @@ describe('Signature', () => { }); it('can sign() with different case', () => { - const signature = Signature.sign(dataDiffCase, { + const signature = sign(dataDiffCase, { method: SignatureTypes.METHOD.ECDSA, privateKey: otherIdRaw.privateKey, }); @@ -104,7 +103,7 @@ describe('Signature', () => { method: 'notECDSA', privateKey: otherIdRaw.privateKey, }; - expect(() => Signature.sign(Crypto.normalizeKeccak256Hash(data), params)).toThrowError( + expect(() => sign(normalizeKeccak256Hash(data), params)).toThrowError( 'signatureParams.method not supported', ); }); @@ -112,7 +111,7 @@ describe('Signature', () => { describe('recover', () => { it('can recover() ECDSA signature', () => { - const id = Signature.recover({ + const id = recover({ data, signature: { method: SignatureTypes.METHOD.ECDSA, @@ -125,7 +124,7 @@ describe('Signature', () => { }); it('can recover() ECDSA_ETHEREUM signature', () => { - const id = Signature.recover({ + const id = recover({ data, signature: { method: SignatureTypes.METHOD.ECDSA_ETHEREUM, @@ -140,7 +139,7 @@ describe('Signature', () => { }); it('can recover() with different case', () => { - const id = Signature.recover({ + const id = recover({ data: dataDiffCase, signature: { method: SignatureTypes.METHOD.ECDSA, @@ -157,7 +156,7 @@ describe('Signature', () => { method: 'notECDSA', value: '0x00000000000000000000', }; - expect(() => Signature.recover({ data, signature: params })).toThrowError( + expect(() => recover({ data, signature: params })).toThrowError( 'signatureParams.method not supported', ); }); diff --git a/packages/utils/test/simple-logger.test.ts b/packages/utils/test/simple-logger.test.ts index fcd2fd65e..245026c05 100644 --- a/packages/utils/test/simple-logger.test.ts +++ b/packages/utils/test/simple-logger.test.ts @@ -1,5 +1,5 @@ import { LogTypes } from '@requestnetwork/types'; -import SimpleLogger from '../src/simple-logger'; +import { SimpleLogger } from '../src'; const LogLevel = LogTypes.LogLevel; diff --git a/packages/utils/test/utils.test.ts b/packages/utils/test/utils.test.ts index cda4f810e..9e500675c 100644 --- a/packages/utils/test/utils.test.ts +++ b/packages/utils/test/utils.test.ts @@ -1,4 +1,13 @@ -import Utils from '../src/utils'; +import { + deepCopy, + deepSort, + flatten2DimensionsArray, + getCurrentTimestampInSecond, + isString, + timeoutPromise, + unique, + uniqueByProperty, +} from '../src'; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('Utils', () => { @@ -37,7 +46,7 @@ describe('Utils', () => { }; /* eslint-enable */ // 'deepSort(arbitraryObject) error' - expect(JSON.stringify(Utils.deepSort(arbitraryObjectNotSorted))).toBe( + expect(JSON.stringify(deepSort(arbitraryObjectNotSorted))).toBe( JSON.stringify(arbitraryObjectSorted), ); }); @@ -55,7 +64,7 @@ describe('Utils', () => { }, attribut3: 'valeurA', }; - const arbitraryObjectDeepCopy = Utils.deepCopy(arbitraryObject); + const arbitraryObjectDeepCopy = deepCopy(arbitraryObject); // 'deepCopy(arbitraryObject) error' expect(arbitraryObjectDeepCopy).toEqual(arbitraryObject); arbitraryObjectDeepCopy.attribut1 = 'new value'; @@ -71,17 +80,17 @@ describe('Utils', () => { it('can return true if variable is String or string', () => { // 'istring("") error' - expect(Utils.isString('this is a string')).toBe(true); + expect(isString('this is a string')).toBe(true); // 'istring("") error' - expect(Utils.isString(String('this is a string'))).toBe(true); + expect(isString(String('this is a string'))).toBe(true); }); it('cannot return true if variable is not a string', () => { /* eslint-disable no-magic-numbers */ // 'istring("") error' - expect(Utils.isString(1234)).toBe(false); + expect(isString(1234)).toBe(false); // 'istring("") error' - expect(Utils.isString({ var: 'plop' })).toBe(false); + expect(isString({ var: 'plop' })).toBe(false); }); it('getCurrentTimestampInSecond()', () => { @@ -89,7 +98,7 @@ describe('Utils', () => { const time = Math.floor(Date.now() / 1000); // 'getCurrentTimestampInSecond() error' - expect(Utils.getCurrentTimestampInSecond()).toBe(time); + expect(getCurrentTimestampInSecond()).toBe(time); // Cleanup jest.useRealTimers(); @@ -106,7 +115,7 @@ describe('Utils', () => { /* eslint-disable */ // 'unique(arbitraryArray) error' - expect(Utils.unique(arbitraryArray)).toEqual({ + expect(unique(arbitraryArray)).toEqual({ uniqueItems: [ { att1: 'value1', att2: 'value2' }, { att3: 'value3', att4: 'value4' }, @@ -128,7 +137,7 @@ describe('Utils', () => { /* eslint-disable */ // 'unique(arbitraryArray) error' - expect(Utils.unique(arbitraryArray)).toEqual({ + expect(unique(arbitraryArray)).toEqual({ uniqueItems: [ { att1: 'value1', att2: 'value2' }, { att1: 'value1', Att2: 'Value2' }, @@ -148,7 +157,7 @@ describe('Utils', () => { /* eslint-disable */ // 'unique(arbitraryArray) error' - expect(Utils.unique(arbitraryArray)).toEqual({ + expect(unique(arbitraryArray)).toEqual({ uniqueItems: [ { att1: 'value1', att2: 'value2' }, { att1: 'value1', Att2: 'Value2' }, @@ -171,7 +180,7 @@ describe('Utils', () => { /* eslint-disable */ // 'uniqueByProperty(arbitraryArray) error' - expect(Utils.uniqueByProperty(arbitraryArray, 'att1')).toEqual({ + expect(uniqueByProperty(arbitraryArray, 'att1')).toEqual({ uniqueItems: [ { att1: 'value1', att2: 'value2' }, { att1: 'value3', att4: 'value4' }, @@ -193,7 +202,7 @@ describe('Utils', () => { /* eslint-disable */ // 'unique(arbitraryArray) error' - expect(Utils.uniqueByProperty(arbitraryArray, 'att1')).toEqual({ + expect(uniqueByProperty(arbitraryArray, 'att1')).toEqual({ uniqueItems: [ { att1: 'value1', att2: 'value2' }, { att1: 'value12', Att2: 'Value2' }, @@ -208,28 +217,28 @@ describe('Utils', () => { describe('flatten2DimensionsArray', () => { it('can flatten2DimensionsArray() 1 dimension array', () => { const arbitraryArray: any[] = [1, 2, 3, 4, 5]; - const flattenArray = Utils.flatten2DimensionsArray(arbitraryArray); + const flattenArray = flatten2DimensionsArray(arbitraryArray); // 'flatten2DimensionsArray(twoDimensionsArray) error' expect(flattenArray).toEqual([1, 2, 3, 4, 5]); }); it('can flatten2DimensionsArray() 3 dimensions array', () => { const arbitraryArray: any[] = [[1, 2], [3], [4, [5, 6]]]; - const flattenArray = Utils.flatten2DimensionsArray(arbitraryArray); + const flattenArray = flatten2DimensionsArray(arbitraryArray); // 'flatten2DimensionsArray(twoDimensionsArray) error' expect(flattenArray).toEqual([1, 2, 3, 4, [5, 6]]); }); it('can flatten2DimensionsArray() empty array', () => { const emptyArray: any[] = []; - const flattenArray = Utils.flatten2DimensionsArray(emptyArray); + const flattenArray = flatten2DimensionsArray(emptyArray); // 'flatten2DimensionsArray(twoDimensionsArray) error' expect(flattenArray).toEqual([]); }); it('can flatten2DimensionsArray() two dimensionals array', () => { const twoDimensionsArray = [[1, 2], [3], [4, 5]]; - const flattenArray = Utils.flatten2DimensionsArray(twoDimensionsArray); + const flattenArray = flatten2DimensionsArray(twoDimensionsArray); // 'flatten2DimensionsArray(twoDimensionsArray) error' expect(flattenArray).toEqual([1, 2, 3, 4, 5]); }); @@ -250,8 +259,9 @@ describe('Utils', () => { expect.assertions(3); - const promise = new Promise(() => {}); - Utils.timeoutPromise(promise, 1000, errorMessage) + const promise = new Promise(() => { + }); + timeoutPromise(promise, 1000, errorMessage) .then(() => { fail('timeoutPromise should not be fulfilled'); }) From 052cf3f80b4c6deed2ffa8e9f1c90c5a1439f02f Mon Sep 17 00:00:00 2001 From: marcohefti Date: Fri, 23 Dec 2022 00:27:45 +0700 Subject: [PATCH 02/13] running refactored files through prehook (#1015) --- packages/utils/src/amount.ts | 6 +--- packages/utils/src/encryption.ts | 6 +--- packages/utils/src/estimate-gas-fees.ts | 2 +- packages/utils/src/identity.ts | 7 +---- packages/utils/src/index.ts | 40 +++++-------------------- packages/utils/src/signature.ts | 16 ++-------- packages/utils/test/encryption.test.ts | 15 ++-------- packages/utils/test/utils.test.ts | 3 +- 8 files changed, 18 insertions(+), 77 deletions(-) diff --git a/packages/utils/src/amount.ts b/packages/utils/src/amount.ts index 424cf51e5..d54410e1b 100644 --- a/packages/utils/src/amount.ts +++ b/packages/utils/src/amount.ts @@ -6,11 +6,7 @@ import { BigNumber } from 'ethers'; /** * Function to manage amounts */ -export { - add, - isValid, - reduce, -}; +export { add, isValid, reduce }; const regexInteger = RegExp(/^[\d]+$/); diff --git a/packages/utils/src/encryption.ts b/packages/utils/src/encryption.ts index 1f2ffd054..195470d6f 100644 --- a/packages/utils/src/encryption.ts +++ b/packages/utils/src/encryption.ts @@ -4,11 +4,7 @@ import { CryptoWrapper, EcUtils } from './crypto'; /** * Functions to manage encryption */ -export { - decrypt, - encrypt, - getIdentityFromEncryptionParams, -}; +export { decrypt, encrypt, getIdentityFromEncryptionParams }; /** * Function to get the identity from the encryption parameters diff --git a/packages/utils/src/estimate-gas-fees.ts b/packages/utils/src/estimate-gas-fees.ts index ce8496290..068a6b367 100644 --- a/packages/utils/src/estimate-gas-fees.ts +++ b/packages/utils/src/estimate-gas-fees.ts @@ -43,4 +43,4 @@ async function estimateGasFees({ }; } -export { estimateGasFees }; +export { estimateGasFees }; diff --git a/packages/utils/src/identity.ts b/packages/utils/src/identity.ts index 31c8abd14..02b8cea97 100644 --- a/packages/utils/src/identity.ts +++ b/packages/utils/src/identity.ts @@ -8,12 +8,7 @@ const supportedIdentities: IdentityTypes.TYPE[] = [ /** * Module to manage Request Logic Identity */ -export { - areEqual, - hasError, - normalizeIdentityValue, - supportedIdentities, -}; +export { areEqual, hasError, normalizeIdentityValue, supportedIdentities }; /** * Checks if two identities are equals diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index a4f173775..d534ade67 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -2,20 +2,11 @@ * Collection of general purpose utility function */ -export { - add, - isValid, - reduce, -} from './amount'; +export { add, isValid, reduce } from './amount'; -export { - min, - max, -} from './bignumber'; +export { min, max } from './bignumber'; -export { - cachedThrottle, -} from './cached-throttle'; +export { cachedThrottle } from './cached-throttle'; export { CryptoWrapper, @@ -28,20 +19,11 @@ export { normalizeKeccak256Hash, } from './crypto'; -export { - decrypt, - encrypt, - getIdentityFromEncryptionParams, -} from './encryption'; +export { decrypt, encrypt, getIdentityFromEncryptionParams } from './encryption'; export { estimateGasFees } from './estimate-gas-fees'; -export { - areEqual, - hasError, - normalizeIdentityValue, - supportedIdentities, -} from './identity'; +export { areEqual, hasError, normalizeIdentityValue, supportedIdentities } from './identity'; export { setProviderFactory, @@ -53,15 +35,9 @@ export { export { retry } from './retry'; -export { - getIdentityFromSignatureParams, - recover, - sign, -} from './signature'; +export { getIdentityFromSignatureParams, recover, sign } from './signature'; -export { - SimpleLogger, -} from './simple-logger'; +export { SimpleLogger } from './simple-logger'; export { deepCopy, @@ -74,5 +50,3 @@ export { uniqueByProperty, notNull, } from './utils'; - - diff --git a/packages/utils/src/signature.ts b/packages/utils/src/signature.ts index 2ff396645..d1c807308 100644 --- a/packages/utils/src/signature.ts +++ b/packages/utils/src/signature.ts @@ -5,11 +5,7 @@ import { EcUtils, normalize, normalizeKeccak256Hash } from './crypto'; /** * Function to manage Request Logic Signature */ -export { - getIdentityFromSignatureParams, - recover, - sign, -}; +export { getIdentityFromSignatureParams, recover, sign }; // Use to localize the parameter V in an ECDSA signature in hex format const V_POSITION_FROM_END_IN_ECDSA_HEX = -2; @@ -49,19 +45,13 @@ function sign( ): SignatureTypes.ISignedData { let value: string; if (signatureParams.method === SignatureTypes.METHOD.ECDSA) { - value = EcUtils.sign( - signatureParams.privateKey, - normalizeKeccak256Hash(data).value, - ); + value = EcUtils.sign(signatureParams.privateKey, normalizeKeccak256Hash(data).value); return { data, signature: { method: signatureParams.method, value } }; } if (signatureParams.method === SignatureTypes.METHOD.ECDSA_ETHEREUM) { const normalizedData = normalize(data); - value = EcUtils.sign( - signatureParams.privateKey, - ethers.utils.hashMessage(normalizedData), - ); + value = EcUtils.sign(signatureParams.privateKey, ethers.utils.hashMessage(normalizedData)); return { data, signature: { method: signatureParams.method, value } }; } diff --git a/packages/utils/test/encryption.test.ts b/packages/utils/test/encryption.test.ts index 8ecd6ed6d..dd6bfaaa1 100644 --- a/packages/utils/test/encryption.test.ts +++ b/packages/utils/test/encryption.test.ts @@ -57,10 +57,7 @@ describe('Encryption', () => { describe('encrypt', () => { it('can encrypt with ECIES', async () => { - const encryptedData = await encrypt( - JSON.stringify(data), - otherIdRaw.encryptionParams, - ); + const encryptedData = await encrypt(JSON.stringify(data), otherIdRaw.encryptionParams); // 'encrypt() error' expect(encryptedData.value.length).toBe(258); // 'encrypt() error' @@ -72,10 +69,7 @@ describe('Encryption', () => { }); it('can encrypt with AES256-cbc', async () => { - const encryptedData = await encrypt( - JSON.stringify(data), - arbitraryAES256cbcEncryptionParams, - ); + const encryptedData = await encrypt(JSON.stringify(data), arbitraryAES256cbcEncryptionParams); // 'encrypt() error' expect(encryptedData.value.length).toBe(88); // 'encrypt() error' @@ -87,10 +81,7 @@ describe('Encryption', () => { }); it('can encrypt with AES256-gcm', async () => { - const encryptedData = await encrypt( - JSON.stringify(data), - arbitraryAES256gcmEncryptionParams, - ); + const encryptedData = await encrypt(JSON.stringify(data), arbitraryAES256gcmEncryptionParams); // 'encrypt() error' expect(encryptedData.value.length).toBe(100); // 'encrypt() error' diff --git a/packages/utils/test/utils.test.ts b/packages/utils/test/utils.test.ts index 9e500675c..6177dedb7 100644 --- a/packages/utils/test/utils.test.ts +++ b/packages/utils/test/utils.test.ts @@ -259,8 +259,7 @@ describe('Utils', () => { expect.assertions(3); - const promise = new Promise(() => { - }); + const promise = new Promise(() => {}); timeoutPromise(promise, 1000, errorMessage) .then(() => { fail('timeoutPromise should not be fulfilled'); From d886e69b1fd1080d6f94f18b80838684ff1f8681 Mon Sep 17 00:00:00 2001 From: marcohefti Date: Sun, 25 Dec 2022 14:29:29 +0700 Subject: [PATCH 03/13] Apply changes to utils package to monorepo This commit applies the changes made to the utils package to the rest of the monorepo. The changes include replacing the default export with named exports and enforcing the no-default-export ESLint rule. NOTE: Not all changes could be tested (#1029, #1030, #1031) --- .../src/extensions/abstract-extension.ts | 5 +- .../payment-network/address-based.ts | 10 +- .../extensions/payment-network/declarative.ts | 41 +++--- .../payment-network/erc777/stream.ts | 6 +- .../payment-network/fee-reference-based.ts | 20 +-- .../test/advanced-logic.test.ts | 12 +- .../test/extensions/content-data.test.ts | 4 +- .../any-to-erc20-proxy.test.ts | 54 +++---- .../payment-network/any-to-eth-proxy.test.ts | 46 +++--- .../payment-network/any-to-near.test.ts | 4 +- .../bitcoin/mainnet-address-based.test.ts | 36 ++--- .../bitcoin/testnet-address-based.test.ts | 36 ++--- .../payment-network/declarative.test.ts | 50 +++---- .../erc20/address-based.test.ts | 37 ++--- .../erc20/fee-proxy-contract.test.ts | 32 ++--- .../erc20/proxy-contract.test.ts | 32 ++--- .../payment-network/erc777/stream.test.ts | 28 ++-- .../ethereum/fee-proxy-contract.test.ts | 32 ++--- .../ethereum/input-data.test.ts | 32 ++--- packages/currency/src/getHash.ts | 4 +- packages/data-access/src/block.ts | 4 +- packages/data-access/src/data-access.ts | 14 +- .../transaction-index/location-by-topic.ts | 4 +- .../2-request-client/6-signature-provider.md | 8 +- ...thereum-private-key-decryption-provider.ts | 8 +- ...um-private-key-decryption-provider.test.ts | 17 +-- ...ethereum-private-key-signature-provider.ts | 10 +- ...eum-private-key-signature-provider.test.ts | 7 +- .../ethereum-storage/src/ethereum-blocks.ts | 14 +- .../src/ethereum-storage-ethers.ts | 6 +- .../ethereum-storage/src/ethereum-storage.ts | 6 +- .../src/ethereum-tx-submitter.ts | 4 +- .../ethereum-storage/src/gas-fee-definer.ts | 4 +- .../ethereum-storage/src/gas-price-definer.ts | 4 +- .../etherchain-provider.ts | 4 +- .../gas-price-providers/etherscan-provider.ts | 4 +- .../ethgasstation-provider.ts | 4 +- packages/ethereum-storage/src/ipfs-manager.ts | 6 +- packages/ethereum-storage/src/ipfs-storage.ts | 4 +- .../src/smart-contract-manager.ts | 19 ++- .../ethereum-entries-to-ipfs-content.test.ts | 14 +- .../test/ethereum-storage.test.ts | 4 +- packages/integration-test/test/layers.test.ts | 7 +- .../integration-test/test/node-client.test.ts | 20 +-- .../src/any-to-any-detector.ts | 5 +- .../src/any/any-to-erc20-proxy.ts | 5 +- .../src/any/retrievers/any-to-any-proxy.ts | 4 +- .../btc/default-providers/blockchain-info.ts | 6 +- .../btc/default-providers/blockcypher-com.ts | 4 +- .../btc/default-providers/blockstream-info.ts | 6 +- .../src/btc/default-providers/chain-so.ts | 4 +- packages/payment-detection/src/declarative.ts | 4 +- .../src/erc20/address-based-info-retriever.ts | 4 +- .../payment-detection/src/erc20/currency.ts | 11 +- .../src/erc20/escrow-info-retriever.ts | 4 +- .../src/erc20/proxy-info-retriever.ts | 4 +- .../src/erc777/superfluid-retriever.ts | 4 +- .../src/eth/proxy-info-retriever.ts | 4 +- .../src/fee-reference-based-detector.ts | 4 +- packages/payment-detection/src/index.ts | 10 +- .../src/payment-network-factory.ts | 4 +- .../src/payment-reference-calculator.ts | 5 +- .../src/reference-based-detector.ts | 4 +- .../payment/any-to-erc20-batch-proxy.test.ts | 12 +- .../test/payment/any-to-erc20-proxy.test.ts | 7 +- .../test/payment/any-to-eth-proxy.test.ts | 8 +- .../test/payment/erc20-batch-proxy.test.ts | 10 +- .../test/payment/erc20-escrow-payment.test.ts | 22 +-- .../test/payment/erc20-fee-proxy.test.ts | 10 +- .../test/payment/erc20-proxy.test.ts | 10 +- .../test/payment/erc777-stream.test.ts | 10 +- .../test/payment/eth-batch-proxy.test.ts | 10 +- .../test/payment/eth-fee-proxy.test.ts | 10 +- .../test/payment/eth-input-data.test.ts | 8 +- .../test/payment/eth-proxy.test.ts | 8 +- .../test/payment/swap-any-to-erc20.test.ts | 6 +- .../test/payment/swap-erc20-fee-proxy.test.ts | 10 +- .../prototype-estimator/src/mock-storage.ts | 8 +- .../src/api/request-network.ts | 6 +- packages/request-client.js/src/api/request.ts | 7 +- packages/request-client.js/src/api/utils.ts | 4 +- .../request-client.js/src/http-data-access.ts | 6 +- .../src/http-metamask-data-access.ts | 4 +- .../request-client.js/src/mock-storage.ts | 12 +- .../test/api/request-network.test.ts | 8 +- .../test/data-test-real-btc.ts | 4 +- packages/request-client.js/test/data-test.ts | 28 ++-- .../test/declarative-payments.test.ts | 4 +- packages/request-client.js/test/index.test.ts | 16 +-- .../request-logic/specs/example/example.ts | 6 +- packages/request-logic/src/action.ts | 8 +- packages/request-logic/src/actions/accept.ts | 4 +- .../src/actions/addExtensionsData.ts | 4 +- packages/request-logic/src/actions/cancel.ts | 4 +- packages/request-logic/src/actions/create.ts | 34 +++-- .../src/actions/increaseExpectedAmount.ts | 13 +- .../src/actions/reduceExpectedAmount.ts | 10 +- packages/request-logic/src/request-logic.ts | 26 ++-- packages/request-logic/src/request.ts | 4 +- .../request-logic/src/requestLogicCore.ts | 4 +- packages/request-logic/src/role.ts | 6 +- packages/request-logic/test/index.test.ts | 136 ++++++++---------- .../request-logic/test/unit/action.test.ts | 10 +- .../test/unit/actions/accept.test.ts | 32 ++--- .../unit/actions/addExtensionsData.test.ts | 14 +- .../test/unit/actions/cancel.test.ts | 28 ++-- .../test/unit/actions/create.test.ts | 22 +-- .../actions/increaseExpectedAmount.test.ts | 28 ++-- .../unit/actions/reduceExpectedAmount.test.ts | 32 ++--- .../test/unit/requestLogicCore.test.ts | 18 ++- .../test/unit/utils/test-data-generator.ts | 8 +- packages/request-node/src/logger.ts | 4 +- .../src/request/persistTransaction.ts | 4 +- packages/request-node/src/requestNode.ts | 4 +- packages/request-node/src/requestNodeBase.ts | 4 +- packages/request-node/src/thegraph-node.ts | 4 +- .../test/getConfirmedTransaction.test.ts | 4 +- packages/smart-contracts/hardhat.config.ts | 5 +- .../scripts-create2/check-deployer.ts | 6 +- .../contract-setup/adminTasks.ts | 8 +- .../scripts-create2/xdeployer.ts | 8 +- .../contracts/BatchConversionPayments.test.ts | 18 +-- .../BatchNoConversionEthPayments.test.ts | 8 +- .../contracts/ChainlinkConversionPath.test.ts | 4 +- .../thegraph-data-access/src/data-access.ts | 8 +- .../src/chainlinkConversionPathTools.ts | 13 +- .../src/clear-transaction.ts | 4 +- .../src/encrypted-transaction.ts | 6 +- .../src/transaction-manager.ts | 6 +- .../src/transactions-factory.ts | 20 +-- .../transaction-manager/test/index.test.ts | 6 +- .../test/unit/channel-parser.test.ts | 6 +- .../test/unit/clear-transaction.test.ts | 4 +- .../test/unit/encryption-transaction.test.ts | 6 +- .../test/unit/utils/test-data.ts | 8 +- .../usage-examples/src/mock/mock-storage.ts | 8 +- packages/utils/README.md | 22 +-- packages/utils/test/crypto.test.ts | 2 +- .../utils/test/crypto/crypto-wrapper.test.ts | 2 +- .../src/web3-signature-provider.ts | 6 +- .../test/web3-signature-provider.test.ts | 9 +- 141 files changed, 783 insertions(+), 946 deletions(-) diff --git a/packages/advanced-logic/src/extensions/abstract-extension.ts b/packages/advanced-logic/src/extensions/abstract-extension.ts index b0c0f847b..1b545a454 100644 --- a/packages/advanced-logic/src/extensions/abstract-extension.ts +++ b/packages/advanced-logic/src/extensions/abstract-extension.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; /** * Abstract class to create extension @@ -53,8 +53,7 @@ export abstract class AbstractExtension implements Extensio ): RequestLogicTypes.IExtensionStates { this.validate(requestState, extensionAction); - const copiedExtensionState: RequestLogicTypes.IExtensionStates = - Utils.deepCopy(extensionsState); + const copiedExtensionState: RequestLogicTypes.IExtensionStates = deepCopy(extensionsState); if (extensionAction.action === ExtensionTypes.PnFeeReferenceBased.ACTION.CREATE) { if (requestState.extensions[extensionAction.id]) { diff --git a/packages/advanced-logic/src/extensions/payment-network/address-based.ts b/packages/advanced-logic/src/extensions/payment-network/address-based.ts index 15df7d9fa..2588f8a57 100644 --- a/packages/advanced-logic/src/extensions/payment-network/address-based.ts +++ b/packages/advanced-logic/src/extensions/payment-network/address-based.ts @@ -1,6 +1,6 @@ import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { areEqual, deepCopy } from '@requestnetwork/utils'; import DeclarativePaymentNetwork from './declarative'; /** @@ -194,11 +194,11 @@ export default abstract class AddressBasedPaymentNetwork< if (!requestState.payee) { throw Error(`The request must have a payee`); } - if (!Utils.identity.areEqual(actionSigner, requestState.payee)) { + if (!areEqual(actionSigner, requestState.payee)) { throw Error(`The signer must be the payee`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // update payment address copiedExtensionState.values.paymentAddress = extensionAction.parameters.paymentAddress; @@ -241,11 +241,11 @@ export default abstract class AddressBasedPaymentNetwork< if (!requestState.payer) { throw Error(`The request must have a payer`); } - if (!Utils.identity.areEqual(actionSigner, requestState.payer)) { + if (!areEqual(actionSigner, requestState.payer)) { throw Error(`The signer must be the payer`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // update refund address copiedExtensionState.values.refundAddress = extensionAction.parameters.refundAddress; diff --git a/packages/advanced-logic/src/extensions/payment-network/declarative.ts b/packages/advanced-logic/src/extensions/payment-network/declarative.ts index 231a18bd7..114e79453 100644 --- a/packages/advanced-logic/src/extensions/payment-network/declarative.ts +++ b/packages/advanced-logic/src/extensions/payment-network/declarative.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { add, areEqual, deepCopy, isValid } from '@requestnetwork/utils'; import { AbstractExtension } from '../abstract-extension'; const CURRENT_VERSION = '0.1.0'; @@ -239,14 +239,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER); - if (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValid(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment sentPaymentAmount - copiedExtensionState.values.sentPaymentAmount = Utils.amount.add( + copiedExtensionState.values.sentPaymentAmount = add( copiedExtensionState.values.sentPaymentAmount, extensionAction.parameters.amount, ); @@ -285,14 +285,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE); - if (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValid(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment sentRefundAmount - copiedExtensionState.values.sentRefundAmount = Utils.amount.add( + copiedExtensionState.values.sentRefundAmount = add( copiedExtensionState.values.sentRefundAmount, extensionAction.parameters.amount, ); @@ -331,14 +331,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE); - if (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValid(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment receivedPaymentAmount - copiedExtensionState.values.receivedPaymentAmount = Utils.amount.add( + copiedExtensionState.values.receivedPaymentAmount = add( copiedExtensionState.values.receivedPaymentAmount, extensionAction.parameters.amount, ); @@ -377,14 +377,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER); - if (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValid(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment receivedRefundAmount - copiedExtensionState.values.receivedRefundAmount = Utils.amount.add( + copiedExtensionState.values.receivedRefundAmount = add( copiedExtensionState.values.receivedRefundAmount, extensionAction.parameters.amount, ); @@ -427,7 +427,7 @@ export default class DeclarativePaymentNetwork< } this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE); - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // assign paymentInfo copiedExtensionState.values.paymentInfo = extensionAction.parameters.paymentInfo; @@ -463,9 +463,9 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { let delegateStr: string; - if (Utils.identity.areEqual(actionSigner, requestState.payee)) { + if (areEqual(actionSigner, requestState.payee)) { delegateStr = 'payeeDelegate'; - } else if (Utils.identity.areEqual(actionSigner, requestState.payer)) { + } else if (areEqual(actionSigner, requestState.payer)) { delegateStr = 'payerDelegate'; } else { throw Error(`The signer must be the payee or the payer`); @@ -475,7 +475,7 @@ export default class DeclarativePaymentNetwork< throw Error(`The ${delegateStr} is already assigned`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // assign payeeDelegate or payerDelegate copiedExtensionState.values[delegateStr] = extensionAction.parameters.delegate; @@ -515,7 +515,7 @@ export default class DeclarativePaymentNetwork< } this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER); - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // assign refundInfo copiedExtensionState.values.refundInfo = extensionAction.parameters.refundInfo; @@ -566,10 +566,7 @@ export default class DeclarativePaymentNetwork< if (!requestRole) { throw Error(`The request must have a ${requestRoleStr}`); } - if ( - !Utils.identity.areEqual(actionSigner, requestRole) && - !Utils.identity.areEqual(actionSigner, requestRoleDelegate) - ) { + if (!areEqual(actionSigner, requestRole) && !areEqual(actionSigner, requestRoleDelegate)) { throw Error(`The signer must be the ${requestRoleStr} or the ${requestRoleStr}Delegate`); } } diff --git a/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts b/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts index e64f24787..2ceda2206 100644 --- a/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts +++ b/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts @@ -1,6 +1,6 @@ import { ExtensionTypes, RequestLogicTypes, TypesUtils } from '@requestnetwork/types'; import ReferenceBasedPaymentNetwork from '../reference-based'; -import Utils from '@requestnetwork/utils'; +import { isValid } from '@requestnetwork/utils'; const CURRENT_VERSION = '0.1.0'; /** @@ -92,7 +92,7 @@ export default class Erc777StreamPaymentNetwork< if ( !extensionAction.parameters.expectedStartDate || (extensionAction.parameters.expectedStartDate && - !Utils.amount.isValid(extensionAction.parameters.expectedStartDate)) + !isValid(extensionAction.parameters.expectedStartDate)) ) { throw Error('expectedStartDate is empty or invalid'); } @@ -100,7 +100,7 @@ export default class Erc777StreamPaymentNetwork< if ( !extensionAction.parameters.expectedFlowRate || (extensionAction.parameters.expectedFlowRate && - !Utils.amount.isValid(extensionAction.parameters.expectedFlowRate)) + !isValid(extensionAction.parameters.expectedFlowRate)) ) { throw Error('expectedFlowRate is empty or invalid'); } diff --git a/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts b/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts index 26ff07ef8..e4defca02 100644 --- a/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts +++ b/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts @@ -1,6 +1,6 @@ import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; import ReferenceBasedPaymentNetwork from './reference-based'; -import Utils from '@requestnetwork/utils'; +import { areEqual, deepCopy, isValid } from '@requestnetwork/utils'; /** * Core of the reference based with fee payment networks @@ -35,7 +35,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< throw Error('feeAddress is not a valid address'); } - if (creationParameters.feeAmount && !Utils.amount.isValid(creationParameters.feeAmount)) { + if (creationParameters.feeAmount && !isValid(creationParameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -65,7 +65,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< throw Error('feeAddress is not a valid address'); } - if (addFeeParameters.feeAmount && !Utils.amount.isValid(addFeeParameters.feeAmount)) { + if (addFeeParameters.feeAmount && !isValid(addFeeParameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -101,10 +101,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< ) { throw Error('feeAddress is not a valid address'); } - if ( - extensionAction.parameters.feeAmount && - !Utils.amount.isValid(extensionAction.parameters.feeAmount) - ) { + if (extensionAction.parameters.feeAmount && !isValid(extensionAction.parameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -160,10 +157,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< if (extensionState.values.feeAddress) { throw Error(`Fee address already given`); } - if ( - extensionAction.parameters.feeAmount && - !Utils.amount.isValid(extensionAction.parameters.feeAmount) - ) { + if (extensionAction.parameters.feeAmount && !isValid(extensionAction.parameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } if (extensionState.values.feeAmount) { @@ -172,11 +166,11 @@ export abstract class FeeReferenceBasedPaymentNetwork< if (!requestState.payee) { throw Error(`The request must have a payee`); } - if (!Utils.identity.areEqual(actionSigner, requestState.payee)) { + if (!areEqual(actionSigner, requestState.payee)) { throw Error(`The signer must be the payee`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // update fee address and amount copiedExtensionState.values.feeAddress = extensionAction.parameters.feeAddress; diff --git a/packages/advanced-logic/test/advanced-logic.test.ts b/packages/advanced-logic/test/advanced-logic.test.ts index 87bc868c7..53cba4d37 100644 --- a/packages/advanced-logic/test/advanced-logic.test.ts +++ b/packages/advanced-logic/test/advanced-logic.test.ts @@ -4,7 +4,7 @@ import * as DataBTCCreate from './utils/payment-network/bitcoin/generator-data-c import * as DataDeclarativeCreate from './utils/payment-network/any/generator-data-create'; import * as DataTestnetBTCCreate from './utils/payment-network/bitcoin/testnet-generator-data-create'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { AdvancedLogic } from '../src/index'; @@ -19,7 +19,7 @@ describe('advanced-logic.ts', () => { }); describe('applyActionToExtensions', () => { it('can applyActionToExtensions', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy(TestData.requestCreatedNoExtension); + const requestCreatedNoExtensionBefore = deepCopy(TestData.requestCreatedNoExtension); const previousState = {}; const newExtensionState = advancedLogic.applyActionToExtensions( @@ -39,9 +39,7 @@ describe('advanced-logic.ts', () => { }); it('can applyActionToExtensions with pn bitcoin address based', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy( - DataBTCCreate.requestStateNoExtensions, - ); + const requestCreatedNoExtensionBefore = deepCopy(DataBTCCreate.requestStateNoExtensions); const newExtensionState = advancedLogic.applyActionToExtensions( requestCreatedNoExtensionBefore.extensions, @@ -58,7 +56,7 @@ describe('advanced-logic.ts', () => { }); it('can applyActionToExtensions with pn testnet bitcoin address based', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy( + const requestCreatedNoExtensionBefore = deepCopy( DataTestnetBTCCreate.requestStateNoExtensions, ); @@ -79,7 +77,7 @@ describe('advanced-logic.ts', () => { }); it('can applyActionToExtensions with declarative payment network', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy( + const requestCreatedNoExtensionBefore = deepCopy( DataDeclarativeCreate.requestStateNoExtensions, ); diff --git a/packages/advanced-logic/test/extensions/content-data.test.ts b/packages/advanced-logic/test/extensions/content-data.test.ts index f832ef72e..a23d9629d 100644 --- a/packages/advanced-logic/test/extensions/content-data.test.ts +++ b/packages/advanced-logic/test/extensions/content-data.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import ContentData from '../../src/extensions/content-data'; @@ -11,7 +11,7 @@ const contentData = new ContentData(); describe('content-data', () => { describe('applyActionToExtension', () => { it('can applyActionToExtensions', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy(TestData.requestCreatedNoExtension); + const requestCreatedNoExtensionBefore = deepCopy(TestData.requestCreatedNoExtension); const previousState = {}; const newExtensionState = contentData.applyActionToExtension( previousState, diff --git a/packages/advanced-logic/test/extensions/payment-network/any-to-erc20-proxy.test.ts b/packages/advanced-logic/test/extensions/payment-network/any-to-erc20-proxy.test.ts index 6efd8bd62..7975ba1d6 100644 --- a/packages/advanced-logic/test/extensions/payment-network/any-to-erc20-proxy.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/any-to-erc20-proxy.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import AnyToErc20Proxy from '../../../src/extensions/payment-network/any-to-erc20-proxy'; @@ -171,7 +171,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -179,7 +179,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () value: 'ETH', }; - const action: ExtensionTypes.IAction = Utils.deepCopy( + const action: ExtensionTypes.IAction = deepCopy( DataConversionERC20FeeCreate.actionCreationFull, ); action.parameters.network = 'invalid network'; @@ -197,7 +197,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -205,7 +205,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () value: 'invalid value', }; - const action: ExtensionTypes.IAction = Utils.deepCopy( + const action: ExtensionTypes.IAction = deepCopy( DataConversionERC20FeeCreate.actionCreationFull, ); @@ -312,7 +312,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataConversionERC20FeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataConversionERC20FeeAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -327,7 +327,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataConversionERC20FeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataConversionERC20FeeAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -357,7 +357,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('can applyActionToExtensions of creation when address is checksumed', () => { - const request = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateNoExtensions); + const request = deepCopy(DataConversionERC20FeeCreate.requestStateNoExtensions); request.currency = { type: RequestLogicTypes.CURRENCY.ERC20, value: '0x4E15361FD6b4BB609Fa63C81A2be19d873717870', // FTM @@ -389,7 +389,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -411,9 +411,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionERC20FeeCreate.actionCreationFull, - ); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataConversionERC20FeeAddData.invalidAddress; // 'must throw' @@ -431,9 +429,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with no tokens accepted', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionERC20FeeCreate.actionCreationFull, - ); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeCreate.actionCreationFull); testnetPaymentAddress.parameters.acceptedTokens = []; // 'must throw' expect(() => { @@ -448,9 +444,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with token address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionERC20FeeCreate.actionCreationFull, - ); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeCreate.actionCreationFull); testnetPaymentAddress.parameters.acceptedTokens = ['invalid address']; // 'must throw' expect(() => { @@ -465,9 +459,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataConversionERC20FeeCreate.actionCreationFull, - ); + const testnetRefundAddress = deepCopy(DataConversionERC20FeeCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataConversionERC20FeeAddData.invalidAddress; // 'must throw' @@ -535,7 +527,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -550,7 +542,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { anyToErc20Proxy.applyActionToExtension( @@ -577,7 +569,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( + const testnetPaymentAddress = deepCopy( DataConversionERC20FeeAddData.actionAddPaymentAddress, ); testnetPaymentAddress.parameters.paymentAddress = @@ -625,7 +617,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -640,7 +632,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { anyToErc20Proxy.applyActionToExtension( @@ -667,7 +659,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( + const testnetPaymentAddress = deepCopy( DataConversionERC20FeeAddData.actionAddRefundAddress, ); testnetPaymentAddress.parameters.refundAddress = @@ -712,7 +704,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee without a payee', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; expect(() => { anyToErc20Proxy.applyActionToExtension( @@ -726,7 +718,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); expect(() => { anyToErc20Proxy.applyActionToExtension( previousState.extensions, @@ -751,7 +743,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee with fee address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionERC20FeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAddress = DataConversionERC20FeeAddData.invalidAddress; expect(() => { anyToErc20Proxy.applyActionToExtension( @@ -765,7 +757,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee with fee amount not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionERC20FeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAmount = 'invalid amount'; expect(() => { anyToErc20Proxy.applyActionToExtension( diff --git a/packages/advanced-logic/test/extensions/payment-network/any-to-eth-proxy.test.ts b/packages/advanced-logic/test/extensions/payment-network/any-to-eth-proxy.test.ts index 95329b82e..9c33c9d56 100644 --- a/packages/advanced-logic/test/extensions/payment-network/any-to-eth-proxy.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/any-to-eth-proxy.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import AnyToEthProxy from '../../../src/extensions/payment-network/any-to-eth-proxy'; @@ -112,7 +112,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with an invalid network/currency pair', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -120,7 +120,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () value: 'ETH', }; - const action: ExtensionTypes.IAction = Utils.deepCopy( + const action: ExtensionTypes.IAction = deepCopy( DataConversionETHFeeCreate.actionCreationFull, ); action.parameters.network = 'invalid network'; @@ -140,7 +140,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -149,7 +149,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () network: 'invalid network', }; - const action: ExtensionTypes.IAction = Utils.deepCopy( + const action: ExtensionTypes.IAction = deepCopy( DataConversionETHFeeCreate.actionCreationFull, ); @@ -256,7 +256,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -271,7 +271,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -301,7 +301,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('can applyActionToExtensions of creation when address is checksumed', () => { - const request = Utils.deepCopy(DataConversionETHFeeCreate.requestStateNoExtensions); + const request = deepCopy(DataConversionETHFeeCreate.requestStateNoExtensions); request.currency = { type: RequestLogicTypes.CURRENCY.ERC20, @@ -334,7 +334,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -355,7 +355,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionETHFeeCreate.actionCreationFull); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataConversionETHFeeAddData.invalidAddress; // 'must throw' @@ -373,7 +373,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy(DataConversionETHFeeCreate.actionCreationFull); + const testnetRefundAddress = deepCopy(DataConversionETHFeeCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataConversionETHFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -442,7 +442,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -457,7 +457,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { anyToEthProxy.applyActionToExtension( @@ -484,9 +484,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionETHFeeAddData.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataConversionETHFeeAddData.invalidAddress; // 'must throw' @@ -534,7 +532,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -549,7 +547,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { anyToEthProxy.applyActionToExtension( @@ -576,9 +574,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionETHFeeAddData.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeAddData.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataConversionETHFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -622,7 +618,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee without a payee', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; expect(() => { anyToEthProxy.applyActionToExtension( @@ -636,7 +632,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); expect(() => { anyToEthProxy.applyActionToExtension( previousState.extensions, @@ -661,7 +657,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee with fee address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionETHFeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAddress = DataConversionETHFeeAddData.invalidAddress; expect(() => { anyToEthProxy.applyActionToExtension( @@ -675,7 +671,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee with fee amount not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionETHFeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAmount = 'invalid amount'; expect(() => { anyToEthProxy.applyActionToExtension( diff --git a/packages/advanced-logic/test/extensions/payment-network/any-to-near.test.ts b/packages/advanced-logic/test/extensions/payment-network/any-to-near.test.ts index c9eaef8ad..b9e099d1c 100644 --- a/packages/advanced-logic/test/extensions/payment-network/any-to-near.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/any-to-near.test.ts @@ -12,7 +12,7 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; import AnyToNearPaymentNetwork from '../../../src/extensions/payment-network/near/any-to-near'; import AnyToNativeTokenPaymentNetwork from '../../../src/extensions/payment-network/any-to-native'; import { CurrencyManager } from '@requestnetwork/currency'; -import utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import AnyToNearTestnetPaymentNetwork from '../../../src/extensions/payment-network/near/any-to-near-testnet'; const salt = arbitrarySalt; @@ -272,7 +272,7 @@ describe('extensions/payment-network/any-to-native-token', () => { ...requestStateNoExtensions, currency: validCurrency, }; - creationAction = utils.deepCopy(actionCreationWithAnyToNativeTokenPayment); + creationAction = deepCopy(actionCreationWithAnyToNativeTokenPayment); }); describe('applyActionToExtension/create action', () => { it('works with valid parameters', () => { diff --git a/packages/advanced-logic/test/extensions/payment-network/bitcoin/mainnet-address-based.test.ts b/packages/advanced-logic/test/extensions/payment-network/bitcoin/mainnet-address-based.test.ts index 5e62bb790..167162523 100644 --- a/packages/advanced-logic/test/extensions/payment-network/bitcoin/mainnet-address-based.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/bitcoin/mainnet-address-based.test.ts @@ -1,7 +1,5 @@ import MainnetBitcoinAddressBasedPN from '../../../../src/extensions/payment-network/bitcoin/mainnet-address-based'; - -import Utils from '@requestnetwork/utils'; - +import { deepCopy } from '@requestnetwork/utils'; import * as DataBTCAddPaymentAddress from '../../../utils/payment-network/bitcoin/generator-data-add-payment-address'; import * as DataBTCCreate from '../../../utils/payment-network/bitcoin/generator-data-create'; import * as TestData from '../../../utils/test-data-generator'; @@ -25,7 +23,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( mainnetBitcoinAddressBasedPN.createCreationAction({ paymentAddress: DataBTCCreate.paymentBTCAddress, }), @@ -36,7 +34,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( mainnetBitcoinAddressBasedPN.createCreationAction({ refundAddress: DataBTCCreate.refundBTCAddress, }), @@ -46,7 +44,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { it('can createCreationAction with nothing', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' - expect(Utils.deepCopy(mainnetBitcoinAddressBasedPN.createCreationAction({}))).toEqual( + expect(deepCopy(mainnetBitcoinAddressBasedPN.createCreationAction({}))).toEqual( DataBTCCreate.actionCreationEmpty, ); }); @@ -119,7 +117,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -173,9 +171,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCCreate.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataBTCCreate.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataBTCAddPaymentAddress.paymentTestnetBTCAddress; // 'must throw' @@ -193,9 +189,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataBTCCreate.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataBTCCreate.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataBTCAddPaymentAddress.refundTestnetBTCAddress; // 'must throw' @@ -262,7 +256,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -276,7 +270,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { mainnetBitcoinAddressBasedPN.applyActionToExtension( @@ -301,9 +295,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCAddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataBTCAddPaymentAddress.paymentTestnetBTCAddress; // 'must throw' @@ -347,7 +339,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -361,7 +353,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { mainnetBitcoinAddressBasedPN.applyActionToExtension( @@ -386,9 +378,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCAddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataBTCAddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataBTCAddPaymentAddress.paymentTestnetBTCAddress; // 'must throw' diff --git a/packages/advanced-logic/test/extensions/payment-network/bitcoin/testnet-address-based.test.ts b/packages/advanced-logic/test/extensions/payment-network/bitcoin/testnet-address-based.test.ts index 3b193bcc9..7133bad54 100644 --- a/packages/advanced-logic/test/extensions/payment-network/bitcoin/testnet-address-based.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/bitcoin/testnet-address-based.test.ts @@ -1,7 +1,5 @@ import TestnetBitcoinAddressBasedPN from '../../../../src/extensions/payment-network/bitcoin/testnet-address-based'; - -import Utils from '@requestnetwork/utils'; - +import { deepCopy } from '@requestnetwork/utils'; import * as DataBTCAddPaymentAddress from '../../../utils/payment-network/bitcoin/testnet-generator-data-add-payment-address'; import * as DataBTCCreate from '../../../utils/payment-network/bitcoin/testnet-generator-data-create'; import * as TestData from '../../../utils/test-data-generator'; @@ -25,7 +23,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( testnetBitcoinAddressBasedPN.createCreationAction({ paymentAddress: DataBTCCreate.paymentTestnetBTCAddress, }), @@ -36,7 +34,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( testnetBitcoinAddressBasedPN.createCreationAction({ refundAddress: DataBTCCreate.refundTestnetBTCAddress, }), @@ -46,7 +44,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { it('can createCreationAction with nothing', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' - expect(Utils.deepCopy(testnetBitcoinAddressBasedPN.createCreationAction({}))).toEqual( + expect(deepCopy(testnetBitcoinAddressBasedPN.createCreationAction({}))).toEqual( DataBTCCreate.actionCreationEmpty, ); }); @@ -111,7 +109,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -165,9 +163,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCCreate.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataBTCCreate.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataBTCAddPaymentAddress.paymentBTCAddress; // 'must throw' @@ -185,9 +181,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataBTCCreate.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataBTCCreate.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataBTCAddPaymentAddress.refundBTCAddress; // 'must throw' expect(() => { @@ -253,7 +247,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -267,7 +261,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { testnetBitcoinAddressBasedPN.applyActionToExtension( @@ -292,9 +286,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCAddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataBTCAddPaymentAddress.paymentBTCAddress; // 'must throw' @@ -338,7 +330,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -352,7 +344,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { testnetBitcoinAddressBasedPN.applyActionToExtension( @@ -377,9 +369,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCAddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataBTCAddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataBTCAddPaymentAddress.refundBTCAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/declarative.test.ts b/packages/advanced-logic/test/extensions/payment-network/declarative.test.ts index 6628872c8..e500322d4 100644 --- a/packages/advanced-logic/test/extensions/payment-network/declarative.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/declarative.test.ts @@ -1,6 +1,6 @@ import PnAnyDeclarative from '../../../src/extensions/payment-network/declarative'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { ExtensionTypes } from '@requestnetwork/types'; import * as TestDataDeclarative from '../../utils/payment-network/any/generator-data-create'; @@ -26,7 +26,7 @@ describe('extensions/payment-network/any/declarative', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( pnAnyDeclarative.createCreationAction({ paymentInfo: TestDataDeclarative.paymentInfo, }), @@ -37,7 +37,7 @@ describe('extensions/payment-network/any/declarative', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( pnAnyDeclarative.createCreationAction({ refundInfo: TestDataDeclarative.refundInfo, }), @@ -49,7 +49,7 @@ describe('extensions/payment-network/any/declarative', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( pnAnyDeclarative.createCreationAction({ payeeDelegate: TestDataDeclarative.payeeDelegate, }), @@ -150,7 +150,7 @@ describe('extensions/payment-network/any/declarative', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(TestDataDeclarative.actionCreationEmpty); + const unknownAction = deepCopy(TestDataDeclarative.actionCreationEmpty); unknownAction.action = 'unknown action' as any; expect(() => { @@ -226,7 +226,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStatePaymentInstructionAdded); }); it('can applyActionToExtensions of addPaymentInstruction from payeeDelegate', () => { - const expectedFromPayeeDelegate = Utils.deepCopy( + const expectedFromPayeeDelegate = deepCopy( TestDataDeclarative.extensionStatePaymentInstructionAdded, ); expectedFromPayeeDelegate[ @@ -255,7 +255,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentInstruction without a payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -272,7 +272,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentInstruction signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -310,7 +310,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStateRefundInstructionAdded); }); it('can applyActionToExtensions of addRefundInstruction from payerDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy( + const expectedFromThirdParty = deepCopy( TestDataDeclarative.extensionStateRefundInstructionAdded, ); expectedFromThirdParty[ @@ -345,7 +345,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundInstruction without a payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -362,7 +362,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundInstruction signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -400,9 +400,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStateDeclaredSent); }); it('can applyActionToExtensions of declareSentPayment from payerDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy( - TestDataDeclarative.extensionStateDeclaredSent, - ); + const expectedFromThirdParty = deepCopy(TestDataDeclarative.extensionStateDeclaredSent); expectedFromThirdParty[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payerDelegate; @@ -432,7 +430,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareSentPayment without a payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -449,7 +447,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of declareSentPayment signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -489,7 +487,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.declarativeExtStateRefundDeclared); }); it('can applyActionToExtensions of declareReceivedRefund from payerDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy( + const expectedFromThirdParty = deepCopy( TestDataDeclarative.declarativeExtStateRefundDeclared, ); expectedFromThirdParty[ @@ -521,7 +519,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareReceivedRefund without a payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -538,7 +536,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of declareReceivedRefund signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -578,7 +576,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStateSentRefund); }); it('can applyActionToExtensions of declareSentRefund from payeeDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy(TestDataDeclarative.extensionStateSentRefund); + const expectedFromThirdParty = deepCopy(TestDataDeclarative.extensionStateSentRefund); expectedFromThirdParty[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payeeDelegate; @@ -605,7 +603,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareSentRefund without a payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -622,7 +620,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of declareSentRefund signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -662,9 +660,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStateReceivedPayment); }); it('can applyActionToExtensions of declareReceivedPayment from payeeDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy( - TestDataDeclarative.extensionStateReceivedPayment, - ); + const expectedFromThirdParty = deepCopy(TestDataDeclarative.extensionStateReceivedPayment); expectedFromThirdParty[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payeeDelegate; @@ -691,7 +687,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareReceivedPayment without a payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -708,7 +704,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of declareReceivedPayment signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( diff --git a/packages/advanced-logic/test/extensions/payment-network/erc20/address-based.test.ts b/packages/advanced-logic/test/extensions/payment-network/erc20/address-based.test.ts index 7a8c3306c..f55fbe41c 100644 --- a/packages/advanced-logic/test/extensions/payment-network/erc20/address-based.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/erc20/address-based.test.ts @@ -1,10 +1,9 @@ import Erc20AddressBasedPaymentNetwork from '../../../../src/extensions/payment-network/erc20/address-based'; -import Utils from '@requestnetwork/utils'; - import * as DataERC20AddPaymentAddress from '../../../utils/payment-network/erc20/address-based-add-payment-address-data-generator'; import * as DataERC20Create from '../../../utils/payment-network/erc20/address-based-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; +import { deepCopy } from '@requestnetwork/utils'; const erc20AddressBasedPaymentNetwork = new Erc20AddressBasedPaymentNetwork(); /* eslint-disable @typescript-eslint/no-unused-expressions */ @@ -24,7 +23,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( erc20AddressBasedPaymentNetwork.createCreationAction({ paymentAddress: DataERC20Create.paymentAddress, }), @@ -35,7 +34,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( erc20AddressBasedPaymentNetwork.createCreationAction({ refundAddress: DataERC20Create.refundAddress, }), @@ -45,7 +44,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { it('can createCreationAction with nothing', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' - expect(Utils.deepCopy(erc20AddressBasedPaymentNetwork.createCreationAction({}))).toEqual( + expect(deepCopy(erc20AddressBasedPaymentNetwork.createCreationAction({}))).toEqual( DataERC20Create.actionCreationEmpty, ); }); @@ -110,7 +109,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -124,7 +123,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError('Unknown action: unknown action'); }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -178,9 +177,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20Create.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataERC20Create.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -197,9 +194,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataERC20Create.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataERC20Create.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -265,7 +260,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -279,7 +274,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20AddressBasedPaymentNetwork.applyActionToExtension( @@ -304,9 +299,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20AddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -349,7 +342,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -363,7 +356,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20AddressBasedPaymentNetwork.applyActionToExtension( @@ -388,9 +381,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20AddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC20AddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/erc20/fee-proxy-contract.test.ts b/packages/advanced-logic/test/extensions/payment-network/erc20/fee-proxy-contract.test.ts index b7c007945..824f0a3f8 100644 --- a/packages/advanced-logic/test/extensions/payment-network/erc20/fee-proxy-contract.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/erc20/fee-proxy-contract.test.ts @@ -1,11 +1,11 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Erc20FeeProxyContract from '../../../../src/extensions/payment-network/erc20/fee-proxy-contract'; import * as DataERC20FeeAddData from '../../../utils/payment-network/erc20/fee-proxy-contract-add-data-generator'; import * as DataERC20FeeCreate from '../../../utils/payment-network/erc20/fee-proxy-contract-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; +import { deepCopy } from '@requestnetwork/utils'; const erc20FeeProxyContract = new Erc20FeeProxyContract(); @@ -205,7 +205,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -220,7 +220,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -263,7 +263,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation on a non ERC20 request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -283,7 +283,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeCreate.actionCreationFull); + const testnetPaymentAddress = deepCopy(DataERC20FeeCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -300,7 +300,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy(DataERC20FeeCreate.actionCreationFull); + const testnetRefundAddress = deepCopy(DataERC20FeeCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -368,7 +368,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -383,7 +383,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20FeeProxyContract.applyActionToExtension( @@ -410,7 +410,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); + const testnetPaymentAddress = deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -455,7 +455,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -470,7 +470,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20FeeProxyContract.applyActionToExtension( @@ -497,7 +497,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddRefundAddress); + const testnetPaymentAddress = deepCopy(DataERC20FeeAddData.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -540,7 +540,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee without a payee', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -555,7 +555,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20FeeProxyContract.applyActionToExtension( @@ -582,7 +582,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee with fee address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataERC20FeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -597,7 +597,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee with fee amount not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataERC20FeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAmount = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/erc20/proxy-contract.test.ts b/packages/advanced-logic/test/extensions/payment-network/erc20/proxy-contract.test.ts index 822f168fa..af4e4e420 100644 --- a/packages/advanced-logic/test/extensions/payment-network/erc20/proxy-contract.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/erc20/proxy-contract.test.ts @@ -1,11 +1,11 @@ import { ExtensionTypes, RequestLogicTypes, IdentityTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Erc20ProxyContract from '../../../../src/extensions/payment-network/erc20/proxy-contract'; import * as DataERC20AddPaymentAddress from '../../../utils/payment-network/erc20/proxy-contract-add-payment-address-data-generator'; import * as DataERC20Create from '../../../utils/payment-network/erc20/proxy-contract-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; +import { deepCopy } from '@requestnetwork/utils'; const erc20ProxyContract = new Erc20ProxyContract(); @@ -125,7 +125,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -140,7 +140,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -183,7 +183,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }); it('cannot applyActionToExtensions of creation on a not Eth request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -203,9 +203,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20Create.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataERC20Create.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -222,9 +220,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataERC20Create.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataERC20Create.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -290,7 +286,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -304,7 +300,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20ProxyContract.applyActionToExtension( @@ -340,9 +336,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20AddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -385,7 +379,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -399,7 +393,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20ProxyContract.applyActionToExtension( @@ -424,9 +418,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20AddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC20AddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/erc777/stream.test.ts b/packages/advanced-logic/test/extensions/payment-network/erc777/stream.test.ts index d45766ad1..640eec554 100644 --- a/packages/advanced-logic/test/extensions/payment-network/erc777/stream.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/erc777/stream.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import Erc777StreamPaymentNetwork from '../../../../src/extensions/payment-network/erc777/stream'; @@ -88,7 +88,7 @@ describe('extensions/payment-network/erc777/stream', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -103,7 +103,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -146,7 +146,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of creation on a non ERC777 request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -166,7 +166,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC777StreamCreate.actionCreationFull); + const testnetPaymentAddress = deepCopy(DataERC777StreamCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { @@ -183,7 +183,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy(DataERC777StreamCreate.actionCreationFull); + const testnetRefundAddress = deepCopy(DataERC777StreamCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { @@ -251,7 +251,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -266,7 +266,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( @@ -293,9 +293,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC777StreamAddData.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { @@ -340,7 +338,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -355,7 +353,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( @@ -382,9 +380,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC777StreamAddData.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC777StreamAddData.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/ethereum/fee-proxy-contract.test.ts b/packages/advanced-logic/test/extensions/payment-network/ethereum/fee-proxy-contract.test.ts index 226c27f6e..8bfd5557b 100644 --- a/packages/advanced-logic/test/extensions/payment-network/ethereum/fee-proxy-contract.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/ethereum/fee-proxy-contract.test.ts @@ -1,11 +1,11 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import EthereumFeeProxyContract from '../../../../src/extensions/payment-network/ethereum/fee-proxy-contract'; import * as DataEthFeeAddData from '../../../utils/payment-network/ethereum/fee-proxy-contract-add-data-generator'; import * as DataEthFeeCreate from '../../../utils/payment-network/ethereum/fee-proxy-contract-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; +import { deepCopy } from '@requestnetwork/utils'; const ethFeeProxyContract = new EthereumFeeProxyContract(); @@ -205,7 +205,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataEthFeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataEthFeeAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -220,7 +220,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataEthFeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataEthFeeAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -263,7 +263,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation on a non ETH request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -283,7 +283,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeCreate.actionCreationFull); + const testnetPaymentAddress = deepCopy(DataEthFeeCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -300,7 +300,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy(DataEthFeeCreate.actionCreationFull); + const testnetRefundAddress = deepCopy(DataEthFeeCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -368,7 +368,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -383,7 +383,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethFeeProxyContract.applyActionToExtension( @@ -410,7 +410,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeAddData.actionAddPaymentAddress); + const testnetPaymentAddress = deepCopy(DataEthFeeAddData.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -455,7 +455,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -470,7 +470,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethFeeProxyContract.applyActionToExtension( @@ -497,7 +497,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeAddData.actionAddRefundAddress); + const testnetPaymentAddress = deepCopy(DataEthFeeAddData.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -540,7 +540,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee without a payee', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -555,7 +555,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethFeeProxyContract.applyActionToExtension( @@ -582,7 +582,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee with fee address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataEthFeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -597,7 +597,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee with fee amount not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataEthFeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAmount = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/ethereum/input-data.test.ts b/packages/advanced-logic/test/extensions/payment-network/ethereum/input-data.test.ts index dba01e5d3..a29f0e2d7 100644 --- a/packages/advanced-logic/test/extensions/payment-network/ethereum/input-data.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/ethereum/input-data.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import EthereumInputDataPaymentNetwork from '../../../../src/extensions/payment-network/ethereum/input-data'; @@ -125,7 +125,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -140,7 +140,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -183,7 +183,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }); it('cannot applyActionToExtensions of creation on a not Eth request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -203,9 +203,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataEthCreate.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataEthCreate.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataEthAddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -222,9 +220,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataEthCreate.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataEthCreate.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataEthAddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -290,7 +286,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataEthCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -304,7 +300,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataEthCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethereumInputDataPaymentNetwork.applyActionToExtension( @@ -329,9 +325,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataEthAddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataEthAddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -374,7 +368,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataEthCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -388,7 +382,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataEthCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethereumInputDataPaymentNetwork.applyActionToExtension( @@ -413,9 +407,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataEthAddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataEthAddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataEthAddPaymentAddress.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/currency/src/getHash.ts b/packages/currency/src/getHash.ts index de53e5a98..66e970df6 100644 --- a/packages/currency/src/getHash.ts +++ b/packages/currency/src/getHash.ts @@ -1,11 +1,11 @@ import { RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { last20bytesOfNormalizedKeccak256Hash } from '@requestnetwork/utils'; export const getHash = (curr: RequestLogicTypes.ICurrency): string => { return curr.type === RequestLogicTypes.CURRENCY.ERC20 || curr.type === RequestLogicTypes.CURRENCY.ERC777 ? curr.value - : Utils.crypto.last20bytesOfNormalizedKeccak256Hash({ + : last20bytesOfNormalizedKeccak256Hash({ type: curr.type, value: curr.value, // FIXME network should be included for native tokens. diff --git a/packages/data-access/src/block.ts b/packages/data-access/src/block.ts index 4232f5dd6..b12f63de0 100644 --- a/packages/data-access/src/block.ts +++ b/packages/data-access/src/block.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; import { DataAccessTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; /** * Module to manage a block in the data access-layer @@ -125,7 +125,7 @@ function pushTransaction( throw new Error('The transaction is missing the data property or encryptedData property'); } // we don't want to modify the original block state - const copiedBlock: DataAccessTypes.IBlock = Utils.deepCopy(block); + const copiedBlock: DataAccessTypes.IBlock = deepCopy(block); const newTransactionPosition = copiedBlock.transactions.length; copiedBlock.transactions.push(transaction); diff --git a/packages/data-access/src/data-access.ts b/packages/data-access/src/data-access.ts index df9ddf872..47a961b89 100644 --- a/packages/data-access/src/data-access.ts +++ b/packages/data-access/src/data-access.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; import { DataAccessTypes, LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy, getCurrentTimestampInSecond, SimpleLogger, unique } from '@requestnetwork/utils'; import * as Bluebird from 'bluebird'; import { EventEmitter } from 'events'; @@ -96,7 +96,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { public constructor(storage: StorageTypes.IStorage, options?: Partial) { const defaultOptions: IDataAccessOptions = { ignoredLocationIndex: new IgnoredLocationIndex(), - logger: new Utils.SimpleLogger(), + logger: new SimpleLogger(), synchronizationIntervalTime: DEFAULT_INTERVAL_TIME, transactionIndex: new TransactionIndex(), autoStartSynchronization: false, @@ -140,7 +140,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { // if transaction index already has data, then sync from the last available timestamp const lastSynced = await this.transactionIndex.getLastTransactionTimestamp(); - const now = Utils.getCurrentTimestampInSecond(); + const now = getCurrentTimestampInSecond(); // initialize the dataId topic with the previous block const allDataWithMeta = await this.storage.getData( @@ -368,7 +368,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { channelIdAndTransactions.transactionsWithMeta.result.transactions; return finalResult; - }, Utils.deepCopy(emptyChannelsWithTopics)); + }, deepCopy(emptyChannelsWithTopics)); } /** @@ -420,7 +420,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { channelIdAndTransactions.transactionsWithMeta.result.transactions; return finalResult; - }, Utils.deepCopy(emptyChannelsWithTopics)); + }, deepCopy(emptyChannelsWithTopics)); } /** @@ -428,7 +428,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { */ public async synchronizeNewDataIds(): Promise { this.checkInitialized(); - const synchronizationTo = Utils.getCurrentTimestampInSecond(); + const synchronizationTo = getCurrentTimestampInSecond(); // We increment lastSyncStorageTimestamp because the data located at lastSyncStorageTimestamp // 0 means it's the first synchronization @@ -592,7 +592,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { // Gets the transaction from the positions const transactions: DataAccessTypes.ITimestampedTransaction[] = // first remove de duplicates - Utils.unique(transactionPositions).uniqueItems.map( + unique(transactionPositions).uniqueItems.map( // Get the transaction from their position and add the timestamp (position: number) => ({ state: diff --git a/packages/data-access/src/transaction-index/location-by-topic.ts b/packages/data-access/src/transaction-index/location-by-topic.ts index 93c626384..c84cc6d84 100644 --- a/packages/data-access/src/transaction-index/location-by-topic.ts +++ b/packages/data-access/src/transaction-index/location-by-topic.ts @@ -1,7 +1,7 @@ import { DataAccessTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Keyv from 'keyv'; +import { flatten2DimensionsArray, unique } from '@requestnetwork/utils'; // Serialize function used for keyv to serialize a Set data structure into a string // There is no way to directly stringify a Set, we need to convert it to an array before @@ -105,7 +105,7 @@ export default class LocationByTopicTransactionIndex { const channelIds = await Promise.all(channelIdsPromises); // flatten the array of array and remove the duplicates - return Utils.unique(Utils.flatten2DimensionsArray(channelIds)).uniqueItems; + return unique(flatten2DimensionsArray(channelIds)).uniqueItems; } /** * Function to get storage locations from a channel id diff --git a/packages/docs/docs/guides/2-request-client/6-signature-provider.md b/packages/docs/docs/guides/2-request-client/6-signature-provider.md index e293092f3..534477d0d 100644 --- a/packages/docs/docs/guides/2-request-client/6-signature-provider.md +++ b/packages/docs/docs/guides/2-request-client/6-signature-provider.md @@ -37,7 +37,7 @@ Your signature provider would look like: ```typescript import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; // Your package import mySignaturePackage from 'mySignaturePackage'; @@ -68,7 +68,7 @@ export default class MySignatureProvider implements SignatureProviderTypes.ISign } // Hash the normalized data (e.g. avoid case sensitivity) - const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; + const hashData = normalizeKeccak256Hash(data).value; // use your signature package const signatureValue = mySignaturePackage.sign(hashData, signer.value); @@ -118,7 +118,7 @@ Your signature provider would look like: ```typescript import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; // Your package import mySignaturePackage from 'mySignaturePackage'; @@ -170,7 +170,7 @@ export default class MySignatureProvider implements SignatureProviderTypes.ISign } // Hash the normalized data (e.g. avoid case sensitivity) - const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; + const hashData = normalizeKeccak256Hash(data).value; // convert the hash from a string '0x...' to a Buffer const hashDataBuffer = Buffer.from(hashData.slice(2), 'hex'); diff --git a/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts b/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts index 974fec219..95f5aacef 100644 --- a/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts +++ b/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts @@ -1,6 +1,6 @@ import { DecryptionProviderTypes, EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { decrypt, EcUtils } from '@requestnetwork/utils'; /** Type of the dictionary of decryptionParameters (private keys) indexed by ethereum address */ type IDecryptionParametersDictionary = Map; @@ -55,7 +55,7 @@ export default class EthereumPrivateKeyDecryptionProvider throw Error(`private key unknown for the identity: ${identity.value}`); } - return Utils.encryption.decrypt(encryptedData, decryptionParameters); + return decrypt(encryptedData, decryptionParameters); } /** @@ -87,9 +87,7 @@ export default class EthereumPrivateKeyDecryptionProvider // compute the address from private key // toLowerCase to avoid mismatch because of case - const address = Utils.crypto.EcUtils.getAddressFromPrivateKey( - decryptionParameters.key, - ).toLowerCase(); + const address = EcUtils.getAddressFromPrivateKey(decryptionParameters.key).toLowerCase(); this.decryptionParametersDictionary.set(address, decryptionParameters); diff --git a/packages/epk-decryption/test/ethereum-private-key-decryption-provider.test.ts b/packages/epk-decryption/test/ethereum-private-key-decryption-provider.test.ts index 786909824..da1183180 100644 --- a/packages/epk-decryption/test/ethereum-private-key-decryption-provider.test.ts +++ b/packages/epk-decryption/test/ethereum-private-key-decryption-provider.test.ts @@ -1,7 +1,7 @@ import { EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import EthereumPrivateKeyDecryptionProvider from '../src/ethereum-private-key-decryption-provider'; +import { encrypt } from '@requestnetwork/utils'; export const id1Raw = { address: '0xaf083f77f1ffd54218d91491afd06c9296eac3ce', @@ -153,10 +153,7 @@ describe('ethereum-private-key-decryption-provider', () => { describe('decrypt', () => { it('can decrypt', async () => { - const encryptedData = await Utils.encryption.encrypt( - decryptedDataExpected, - id1Raw.encryptionParams, - ); + const encryptedData = await encrypt(decryptedDataExpected, id1Raw.encryptionParams); const decryptionProvider = new EthereumPrivateKeyDecryptionProvider(id1Raw.decryptionParams); @@ -179,10 +176,7 @@ describe('ethereum-private-key-decryption-provider', () => { }); it('cannot decrypt if identity not supported', async () => { - const encryptedData = await Utils.encryption.encrypt( - decryptedDataExpected, - id1Raw.encryptionParams, - ); + const encryptedData = await encrypt(decryptedDataExpected, id1Raw.encryptionParams); const decryptionProvider = new EthereumPrivateKeyDecryptionProvider(id1Raw.decryptionParams); const arbitraryIdentity: any = { type: 'unknown type', value: '0x000' }; @@ -192,10 +186,7 @@ describe('ethereum-private-key-decryption-provider', () => { }); it('cannot decrypt if private key of the identity not given', async () => { - const encryptedData = await Utils.encryption.encrypt( - decryptedDataExpected, - id1Raw.encryptionParams, - ); + const encryptedData = await encrypt(decryptedDataExpected, id1Raw.encryptionParams); const decryptionProvider = new EthereumPrivateKeyDecryptionProvider(id1Raw.decryptionParams); const arbitraryIdentity: IdentityTypes.IIdentity = { diff --git a/packages/epk-signature/src/ethereum-private-key-signature-provider.ts b/packages/epk-signature/src/ethereum-private-key-signature-provider.ts index 3991ac105..07414f04e 100644 --- a/packages/epk-signature/src/ethereum-private-key-signature-provider.ts +++ b/packages/epk-signature/src/ethereum-private-key-signature-provider.ts @@ -1,6 +1,6 @@ import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** Type of the dictionary of signatureParameters (private keys) indexed by ethereum address */ type ISignatureParametersDictionary = Map; @@ -55,8 +55,8 @@ export default class EthereumPrivateKeySignatureProvider } // the hash format in request start by 01 but the ec-utils need a hash starting by 0x - const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; - const signatureValue = Utils.crypto.EcUtils.sign(signatureParameter.privateKey, hashData); + const hashData = normalizeKeccak256Hash(data).value; + const signatureValue = EcUtils.sign(signatureParameter.privateKey, hashData); return { data, @@ -83,9 +83,7 @@ export default class EthereumPrivateKeySignatureProvider // compute the address from private key // toLowerCase to avoid mismatch because of case - const address = Utils.crypto.EcUtils.getAddressFromPrivateKey( - signatureParams.privateKey, - ).toLowerCase(); + const address = EcUtils.getAddressFromPrivateKey(signatureParams.privateKey).toLowerCase(); this.signatureParametersDictionary.set(address, signatureParams); diff --git a/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts b/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts index fbf75dc8f..451de7200 100644 --- a/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts +++ b/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts @@ -1,8 +1,7 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import EthereumPrivateKeySignatureProvider from '../src/ethereum-private-key-signature-provider'; - -import Utils from '@requestnetwork/utils'; +import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; const id1Raw = { address: '0xaf083f77f1ffd54218d91491afd06c9296eac3ce', @@ -35,8 +34,8 @@ export const id2Raw = { }; const data = { What: 'ever', the: 'data', are: true }; -const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; -const signatureValueExpected = Utils.crypto.EcUtils.sign(id1Raw.privateKey, hashData); +const hashData = normalizeKeccak256Hash(data).value; +const signatureValueExpected = EcUtils.sign(id1Raw.privateKey, hashData); const signedDataExpected = { data, signature: { diff --git a/packages/ethereum-storage/src/ethereum-blocks.ts b/packages/ethereum-storage/src/ethereum-blocks.ts index 249d69509..01623fe03 100644 --- a/packages/ethereum-storage/src/ethereum-blocks.ts +++ b/packages/ethereum-storage/src/ethereum-blocks.ts @@ -1,5 +1,5 @@ import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { cachedThrottle, retry, SimpleLogger } from '@requestnetwork/utils'; /** * Manages every info linked to the ethereum blocks (blockNumber, blockTimestamp, confirmations ... ) @@ -61,16 +61,16 @@ export default class EthereumBlocks { this.getLastBlockNumberMinDelay = getLastBlockNumberMinDelay; - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); // Get retry parameter values from config this.retryDelay = retryDelay; this.maxRetries = maxRetries; // Setup the throttled and retriable getLastBlockNumber function - this.getLastBlockNumber = Utils.cachedThrottle( + this.getLastBlockNumber = cachedThrottle( () => - Utils.retry( + retry( () => { this.logger.debug(`Getting last block number`, ['ethereum', 'ethereum-blocks']); return this.eth.getBlockNumber(); @@ -96,8 +96,8 @@ export default class EthereumBlocks { } // if we don't know the information, let's get it - // Use Utils.retry to rerun if getBlock fails - const block = await Utils.retry((bn: number) => this.eth.getBlock(bn), { + // Use retry to rerun if getBlock fails + const block = await retry((bn: number) => this.eth.getBlock(bn), { maxRetries: this.maxRetries, retryDelay: this.retryDelay, })(blockNumber); @@ -194,7 +194,7 @@ export default class EthereumBlocks { * @returns An Ethereum block */ public async getBlock(blockNumber: number | string): Promise { - return Utils.retry(this.eth.getBlock, { + return retry(this.eth.getBlock, { context: this.eth, maxRetries: this.maxRetries, retryDelay: this.retryDelay, diff --git a/packages/ethereum-storage/src/ethereum-storage-ethers.ts b/packages/ethereum-storage/src/ethereum-storage-ethers.ts index c7a687886..05e7737dd 100644 --- a/packages/ethereum-storage/src/ethereum-storage-ethers.ts +++ b/packages/ethereum-storage/src/ethereum-storage-ethers.ts @@ -1,10 +1,10 @@ import { EventEmitter } from 'events'; import { BigNumber, ContractReceipt, providers, Signer } from 'ethers'; import TypedEmitter from 'typed-emitter'; -import Utils from '@requestnetwork/utils'; import { LogTypes, StorageTypes } from '@requestnetwork/types'; import { requestHashSubmitterArtifact } from '@requestnetwork/smart-contracts'; import { EthereumTransactionSubmitter } from './ethereum-tx-submitter'; +import { getCurrentTimestampInSecond, SimpleLogger } from '@requestnetwork/utils'; export type GasDefinerProps = { gasPriceMin?: BigNumber; @@ -33,7 +33,7 @@ export class EthereumStorageEthers implements StorageTypes.IStorageWrite { private readonly txSubmitter: EthereumTransactionSubmitter; constructor({ network, signer, ipfsStorage, logger, gasPriceMin }: StorageProps) { - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.ipfsStorage = ipfsStorage; this.network = network; this.txSubmitter = new EthereumTransactionSubmitter({ network, signer, logger, gasPriceMin }); @@ -68,7 +68,7 @@ export class EthereumStorageEthers implements StorageTypes.IStorageWrite { }, state: StorageTypes.ContentState.PENDING, storageType: StorageTypes.StorageSystemType.LOCAL, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }, }; diff --git a/packages/ethereum-storage/src/ethereum-storage.ts b/packages/ethereum-storage/src/ethereum-storage.ts index e38eed5dd..52180f5bf 100644 --- a/packages/ethereum-storage/src/ethereum-storage.ts +++ b/packages/ethereum-storage/src/ethereum-storage.ts @@ -1,5 +1,4 @@ import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Bluebird from 'bluebird'; import { EventEmitter } from 'events'; import { getMaxConcurrency } from './config'; @@ -11,6 +10,7 @@ import SmartContractManager from './smart-contract-manager'; import * as Keyv from 'keyv'; import { BigNumber } from 'ethers'; +import { getCurrentTimestampInSecond, SimpleLogger } from '@requestnetwork/utils'; // time to wait before considering the web3 provider is not reachable const WEB3_PROVIDER_TIMEOUT = 10000; @@ -90,7 +90,7 @@ export class EthereumStorage implements StorageTypes.IStorage { metadataStore?: Keyv.Store, ) { this.maxConcurrency = maxConcurrency || getMaxConcurrency(); - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.ipfsStorage = ipfsStorage; this.smartContractManager = new SmartContractManager(web3Connection, { getLastBlockNumberDelay, @@ -167,7 +167,7 @@ export class EthereumStorage implements StorageTypes.IStorage { const { ipfsHash, ipfsSize } = await this.ipfsStorage.ipfsAdd(content); - const timestamp = Utils.getCurrentTimestampInSecond(); + const timestamp = getCurrentTimestampInSecond(); const result: StorageTypes.IAppendResult = Object.assign(new EventEmitter(), { content, id: ipfsHash, diff --git a/packages/ethereum-storage/src/ethereum-tx-submitter.ts b/packages/ethereum-storage/src/ethereum-tx-submitter.ts index 1e8233b56..672d4503f 100644 --- a/packages/ethereum-storage/src/ethereum-tx-submitter.ts +++ b/packages/ethereum-storage/src/ethereum-tx-submitter.ts @@ -1,10 +1,10 @@ import { ContractTransaction, providers, utils } from 'ethers'; -import Utils from '@requestnetwork/utils'; import { LogTypes } from '@requestnetwork/types'; import { requestHashSubmitterArtifact } from '@requestnetwork/smart-contracts'; import { RequestOpenHashSubmitter } from '@requestnetwork/smart-contracts/types'; import { SubmitterProps } from './ethereum-storage-ethers'; import { GasFeeDefiner } from './gas-fee-definer'; +import { SimpleLogger } from '@requestnetwork/utils'; /** * Handles the submission of a hash on the request HashSubmitter contract @@ -17,7 +17,7 @@ export class EthereumTransactionSubmitter { private readonly gasFeeDefiner: GasFeeDefiner; constructor({ network, signer, logger, gasPriceMin }: SubmitterProps) { - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); const provider = signer.provider as providers.JsonRpcProvider; this.provider = provider; this.hashSubmitter = requestHashSubmitterArtifact.connect( diff --git a/packages/ethereum-storage/src/gas-fee-definer.ts b/packages/ethereum-storage/src/gas-fee-definer.ts index fff8224c2..09afa7c8d 100644 --- a/packages/ethereum-storage/src/gas-fee-definer.ts +++ b/packages/ethereum-storage/src/gas-fee-definer.ts @@ -1,6 +1,6 @@ import { BigNumber, providers, constants } from 'ethers'; -import Utils from '@requestnetwork/utils'; import { GasDefinerProps } from './ethereum-storage-ethers'; +import { estimateGasFees } from '@requestnetwork/utils'; export class GasFeeDefiner { private readonly provider: providers.JsonRpcProvider; @@ -18,6 +18,6 @@ export class GasFeeDefiner { maxFeePerGas?: BigNumber; maxPriorityFeePerGas?: BigNumber; }> { - return Utils.estimateGasFees({ provider: this.provider, gasPriceMin: this.gasPriceMin }); + return estimateGasFees({ provider: this.provider, gasPriceMin: this.gasPriceMin }); } } diff --git a/packages/ethereum-storage/src/gas-price-definer.ts b/packages/ethereum-storage/src/gas-price-definer.ts index 6cc60927a..7bd232392 100644 --- a/packages/ethereum-storage/src/gas-price-definer.ts +++ b/packages/ethereum-storage/src/gas-price-definer.ts @@ -5,11 +5,11 @@ import EtherscanProvider from './gas-price-providers/etherscan-provider'; import EthGasStationProvider from './gas-price-providers/ethgasstation-provider'; import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { BigNumber } from 'ethers'; import XDaiFixedProvider from './gas-price-providers/xdai-fixed-provider'; import { GasDefinerProps } from './ethereum-storage-ethers'; +import { SimpleLogger } from '@requestnetwork/utils'; /** * Determines the gas price to use depending on the used network @@ -48,7 +48,7 @@ export class GasPriceDefiner { logger, gasPriceMin, }: GasDefinerProps & { logger?: LogTypes.ILogger } = {}) { - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.gasPriceMin = gasPriceMin; } diff --git a/packages/ethereum-storage/src/gas-price-providers/etherchain-provider.ts b/packages/ethereum-storage/src/gas-price-providers/etherchain-provider.ts index 8c711653f..3f7b9e5a7 100644 --- a/packages/ethereum-storage/src/gas-price-providers/etherchain-provider.ts +++ b/packages/ethereum-storage/src/gas-price-providers/etherchain-provider.ts @@ -1,11 +1,11 @@ import EthereumUtils from '../ethereum-utils'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const ETHERCHAIN_REQUEST_MAX_RETRY = 3; @@ -32,7 +32,7 @@ export default class EtherchainProvider implements StorageTypes.IGasPriceProvide * @returns Requested gas price */ public async getGasPrice(type: StorageTypes.GasPriceType): Promise { - const res = await Utils.retry(async () => Axios.get(this.providerUrl), { + const res = await retry(async () => Axios.get(this.providerUrl), { maxRetries: ETHERCHAIN_REQUEST_MAX_RETRY, retryDelay: ETHERCHAIN_REQUEST_RETRY_DELAY, })(); diff --git a/packages/ethereum-storage/src/gas-price-providers/etherscan-provider.ts b/packages/ethereum-storage/src/gas-price-providers/etherscan-provider.ts index e2eb0fdb5..f84928d4a 100644 --- a/packages/ethereum-storage/src/gas-price-providers/etherscan-provider.ts +++ b/packages/ethereum-storage/src/gas-price-providers/etherscan-provider.ts @@ -1,11 +1,11 @@ import EthereumUtils from '../ethereum-utils'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const ETHERSCAN_REQUEST_MAX_RETRY = 3; @@ -32,7 +32,7 @@ export default class EtherscanProvider implements StorageTypes.IGasPriceProvider * @returns Requested gas price */ public async getGasPrice(type: StorageTypes.GasPriceType): Promise { - const res = await Utils.retry(async () => Axios.get(this.providerUrl), { + const res = await retry(async () => Axios.get(this.providerUrl), { maxRetries: ETHERSCAN_REQUEST_MAX_RETRY, retryDelay: ETHERSCAN_REQUEST_RETRY_DELAY, })(); diff --git a/packages/ethereum-storage/src/gas-price-providers/ethgasstation-provider.ts b/packages/ethereum-storage/src/gas-price-providers/ethgasstation-provider.ts index f405cab96..411a75e0b 100644 --- a/packages/ethereum-storage/src/gas-price-providers/ethgasstation-provider.ts +++ b/packages/ethereum-storage/src/gas-price-providers/ethgasstation-provider.ts @@ -1,10 +1,10 @@ import EthereumUtils from '../ethereum-utils'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const ETHGASSTATION_REQUEST_MAX_RETRY = 3; @@ -31,7 +31,7 @@ export default class EthGasStationProvider implements StorageTypes.IGasPriceProv * @returns Requested gas price */ public async getGasPrice(type: StorageTypes.GasPriceType): Promise { - const res = await Utils.retry(async () => Axios.get(this.providerUrl), { + const res = await retry(async () => Axios.get(this.providerUrl), { maxRetries: ETHGASSTATION_REQUEST_MAX_RETRY, retryDelay: ETHGASSTATION_RETRY_DELAY, })(); diff --git a/packages/ethereum-storage/src/ipfs-manager.ts b/packages/ethereum-storage/src/ipfs-manager.ts index 65fc0938a..a4d2cd848 100644 --- a/packages/ethereum-storage/src/ipfs-manager.ts +++ b/packages/ethereum-storage/src/ipfs-manager.ts @@ -1,11 +1,11 @@ import { UnixFS } from 'ipfs-unixfs'; import * as qs from 'qs'; import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios'; -import Utils from '@requestnetwork/utils'; import { LogTypes, StorageTypes } from '@requestnetwork/types'; import { getDefaultIpfs, getIpfsErrorHandlingConfig } from './config'; import * as FormData from 'form-data'; +import { retry, SimpleLogger } from '@requestnetwork/utils'; /** A mapping between IPFS Paths and the response type */ type IpfsPaths = { @@ -43,7 +43,7 @@ export default class IpfsManager { }) { this.ipfsGatewayConnection = options?.ipfsGatewayConnection || getDefaultIpfs(); this.ipfsErrorHandling = options?.ipfsErrorHandling || getIpfsErrorHandlingConfig(); - this.logger = options?.logger || new Utils.SimpleLogger(); + this.logger = options?.logger || new SimpleLogger(); this.axiosInstance = axios.create({ baseURL: `${this.ipfsGatewayConnection.protocol}://${this.ipfsGatewayConnection.host}:${this.ipfsGatewayConnection.port}/${this.BASE_PATH}/`, @@ -55,7 +55,7 @@ export default class IpfsManager { } private async ipfs(path: T, config?: AxiosRequestConfig) { - const _post = Utils.retry(this.axiosInstance.post, { + const _post = retry(this.axiosInstance.post, { context: this.axiosInstance, maxRetries: this.ipfsErrorHandling.maxRetries, retryDelay: this.ipfsErrorHandling.delayBetweenRetries, diff --git a/packages/ethereum-storage/src/ipfs-storage.ts b/packages/ethereum-storage/src/ipfs-storage.ts index 603dd4ff6..6df4a11b1 100644 --- a/packages/ethereum-storage/src/ipfs-storage.ts +++ b/packages/ethereum-storage/src/ipfs-storage.ts @@ -1,8 +1,8 @@ import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { getIpfsExpectedBootstrapNodes, getPinRequestConfig } from './config'; import IpfsManager from './ipfs-manager'; +import { SimpleLogger } from '@requestnetwork/utils'; export type IpfsStorageProps = { logger?: LogTypes.ILogger; @@ -15,7 +15,7 @@ export class IpfsStorage implements StorageTypes.IIpfsStorage { constructor({ ipfsGatewayConnection, logger }: IpfsStorageProps) { this.ipfsManager = new IpfsManager({ ipfsGatewayConnection, logger }); - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); } public async initialize(): Promise { diff --git a/packages/ethereum-storage/src/smart-contract-manager.ts b/packages/ethereum-storage/src/smart-contract-manager.ts index fa15336e8..2c184c37a 100644 --- a/packages/ethereum-storage/src/smart-contract-manager.ts +++ b/packages/ethereum-storage/src/smart-contract-manager.ts @@ -1,6 +1,5 @@ import * as SmartContracts from '@requestnetwork/smart-contracts'; import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Bluebird from 'bluebird'; import * as config from './config'; import EthereumBlocks from './ethereum-blocks'; @@ -13,6 +12,12 @@ const web3Eth = require('web3-eth'); const web3Utils = require('web3-utils'); import { BigNumber } from 'ethers'; +import { + flatten2DimensionsArray, + retry, + SimpleLogger, + timeoutPromise, +} from '@requestnetwork/utils'; // Maximum number of attempt to create ethereum metadata when transaction to add hash and size to Ethereum is confirmed // 23 is the number of call of the transaction's confirmation event function @@ -105,7 +110,7 @@ export default class SmartContractManager { }, ) { this.maxConcurrency = maxConcurrency; - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.maxRetries = maxRetries; this.retryDelay = retryDelay; @@ -235,7 +240,7 @@ export default class SmartContractManager { public async getMainAccount(): Promise { // Get the accounts on the provider // Throws an error if timeout is reached - const accounts = await Utils.timeoutPromise( + const accounts = await timeoutPromise( this.eth.getAccounts(), this.timeout, 'Web3 getAccounts connection timeout', @@ -265,7 +270,7 @@ export default class SmartContractManager { // Get the fee from the size of the content // Throws an error if timeout is reached - const fee = await Utils.timeoutPromise( + const fee = await timeoutPromise( this.requestHashSubmitter.methods.getFeesAmount(feesParameters.contentSize).call(), this.timeout, 'Web3 getFeesAmount connection timeout', @@ -532,9 +537,9 @@ export default class SmartContractManager { // If getPastEvents doesn't throw, we can return the returned events from the function let events: any; try { - events = await Utils.retry( + events = await retry( (args) => - Utils.timeoutPromise( + timeoutPromise( this.requestHashStorage.getPastEvents(args), this.timeout, 'Web3 getPastEvents connection timeout', @@ -564,7 +569,7 @@ export default class SmartContractManager { ); return Promise.all([eventsFirstHalfPromise, eventsSecondHalfPromise]) - .then((halves) => Utils.flatten2DimensionsArray(halves)) + .then((halves) => flatten2DimensionsArray(halves)) .catch((err) => { throw err; }); diff --git a/packages/ethereum-storage/test/ethereum-entries-to-ipfs-content.test.ts b/packages/ethereum-storage/test/ethereum-entries-to-ipfs-content.test.ts index d08723555..2ba90d6a0 100644 --- a/packages/ethereum-storage/test/ethereum-entries-to-ipfs-content.test.ts +++ b/packages/ethereum-storage/test/ethereum-entries-to-ipfs-content.test.ts @@ -1,5 +1,5 @@ import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { SimpleLogger } from '@requestnetwork/utils'; import ethereumEntriesToIpfsContent from '../src/ethereum-entries-to-ipfs-content'; import IgnoredDataIndex from '../src/ignored-dataIds'; @@ -60,7 +60,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); @@ -175,7 +175,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); @@ -246,7 +246,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); @@ -287,7 +287,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); expect(result.length).toBe(1); @@ -316,7 +316,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); expect(result.length).toBe(0); @@ -349,7 +349,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); expect(result.length).toBe(0); diff --git a/packages/ethereum-storage/test/ethereum-storage.test.ts b/packages/ethereum-storage/test/ethereum-storage.test.ts index ab02c30ba..bcc4ffa62 100644 --- a/packages/ethereum-storage/test/ethereum-storage.test.ts +++ b/packages/ethereum-storage/test/ethereum-storage.test.ts @@ -1,6 +1,6 @@ import * as SmartContracts from '@requestnetwork/smart-contracts'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { getCurrentTimestampInSecond } from '@requestnetwork/utils'; import { EventEmitter } from 'events'; import { EthereumStorage } from '../src/ethereum-storage'; @@ -222,7 +222,7 @@ describe('EthereumStorage', () => { it('allows to append a file', async () => { jest.useFakeTimers('modern'); jest.setSystemTime(0); - const timestamp = Utils.getCurrentTimestampInSecond(); + const timestamp = getCurrentTimestampInSecond(); const result = await ethereumStorage.append(content1); const resultExpected: StorageTypes.IAppendResult = Object.assign(new EventEmitter(), { diff --git a/packages/integration-test/test/layers.test.ts b/packages/integration-test/test/layers.test.ts index 2d9b09d3d..1e72d03a6 100644 --- a/packages/integration-test/test/layers.test.ts +++ b/packages/integration-test/test/layers.test.ts @@ -1,3 +1,5 @@ +import { getCurrentTimestampInSecond } from '@requestnetwork/utils'; + const web3Eth = require('web3-eth'); import { AdvancedLogic } from '@requestnetwork/advanced-logic'; @@ -17,7 +19,6 @@ import { SignatureTypes, StorageTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; let advancedLogic: AdvancedLogicTypes.IAdvancedLogic; let requestLogic: RequestLogicTypes.IRequestLogic; @@ -367,7 +368,7 @@ describe('Request system', () => { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0x740fc87Bd3f41d07d23A01DEc90623eBC5fed9D6', }, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }; // create a unique topic just to not have collisions in tests const topics1 = [request1CreationHash]; @@ -390,7 +391,7 @@ describe('Request system', () => { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0x740fc87Bd3f41d07d23A01DEc90623eBC5fed9D6', }, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }; const resultCreation2 = await requestLogic.createRequest( request2CreationHash, diff --git a/packages/integration-test/test/node-client.test.ts b/packages/integration-test/test/node-client.test.ts index f5e7a546a..41a1ae528 100644 --- a/packages/integration-test/test/node-client.test.ts +++ b/packages/integration-test/test/node-client.test.ts @@ -8,7 +8,6 @@ import { RequestLogicTypes, ExtensionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { payRequest, approveErc20ForProxyConversionIfNeeded, @@ -24,6 +23,7 @@ import { requestNetwork, signatureProvider, } from './scheduled/fixtures'; +import { getCurrentTimestampInSecond, normalizeKeccak256Hash } from '@requestnetwork/utils'; const mnemonic = 'candy maple cake sugar pudding cream honey rich smooth crumble sweet treat'; const provider = new providers.JsonRpcProvider('http://localhost:8545'); @@ -175,11 +175,11 @@ describe('Request client using a request node', () => { expectedAmount: '100000000', payee: payeeIdentity, payer: payerIdentity, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }; const topicsRequest1and2: string[] = [ - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(requestCreationHash1)), + MultiFormat.serialize(normalizeKeccak256Hash(requestCreationHash1)), ]; const request1: Request = await requestNetwork.createRequest({ @@ -188,7 +188,7 @@ describe('Request client using a request node', () => { topics: topicsRequest1and2, }); await request1.waitForConfirmation(); - const timestampBeforeReduce = Utils.getCurrentTimestampInSecond(); + const timestampBeforeReduce = getCurrentTimestampInSecond(); // make sure that request 2 timestamp is greater than request 1 timestamp const waitNextSecond = (timestampBeforeReduce + 1) * 1000 - Date.now(); @@ -200,7 +200,7 @@ describe('Request client using a request node', () => { expectedAmount: '1000', payee: payeeIdentity, payer: payerIdentity, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }; const request2: Request = await requestNetwork.createRequest({ @@ -251,11 +251,11 @@ describe('Request client using a request node', () => { value: '0xf17f52151ebef6c7334fad080c5704d77216b732', }; - const timestampCreation = Utils.getCurrentTimestampInSecond(); + const timestampCreation = getCurrentTimestampInSecond(); // create request 1 const topicsRequest1and2: string[] = [ - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(timestampCreation)), + MultiFormat.serialize(normalizeKeccak256Hash(timestampCreation)), ]; const request1: Request = await requestNetwork.createRequest({ requestInfo: { @@ -263,7 +263,7 @@ describe('Request client using a request node', () => { expectedAmount: '100000000', payee: payeeIdentity, payer: payerSmartContract, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }, signer: payeeIdentity, topics: topicsRequest1and2, @@ -276,7 +276,7 @@ describe('Request client using a request node', () => { expectedAmount: '1000', payee: payeeIdentity, payer: payerIdentity, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }, signer: payeeIdentity, topics: topicsRequest1and2, @@ -473,7 +473,7 @@ describe('Request client using a request node', () => { it('cannot decrypt a request with the wrong decryption provider', async () => { const timestamp = Date.now(); - const myRandomTopic = `topic ${Utils.getCurrentTimestampInSecond()}`; + const myRandomTopic = `topic ${getCurrentTimestampInSecond()}`; const requestNetwork = new RequestNetwork({ httpConfig, decryptionProvider, diff --git a/packages/payment-detection/src/any-to-any-detector.ts b/packages/payment-detection/src/any-to-any-detector.ts index e760cd1e6..1e135712f 100644 --- a/packages/payment-detection/src/any-to-any-detector.ts +++ b/packages/payment-detection/src/any-to-any-detector.ts @@ -1,8 +1,7 @@ import { ExtensionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { FeeReferenceBasedDetector } from './fee-reference-based-detector'; - import { ICurrencyManager } from '@requestnetwork/currency'; +import { generate8randomBytes } from '@requestnetwork/utils'; /** * Abstract class to extend to get the payment balance of conversion requests @@ -34,7 +33,7 @@ export abstract class AnyToAnyDetector< ): Promise { // If no salt is given, generate one paymentNetworkCreationParameters.salt = - paymentNetworkCreationParameters.salt || (await Utils.crypto.generate8randomBytes()); + paymentNetworkCreationParameters.salt || (await generate8randomBytes()); return this.extension.createCreationAction(paymentNetworkCreationParameters); } diff --git a/packages/payment-detection/src/any/any-to-erc20-proxy.ts b/packages/payment-detection/src/any/any-to-erc20-proxy.ts index 2ff462823..9e336cc8c 100644 --- a/packages/payment-detection/src/any/any-to-erc20-proxy.ts +++ b/packages/payment-detection/src/any/any-to-erc20-proxy.ts @@ -1,11 +1,11 @@ import { erc20ConversionProxy } from '@requestnetwork/smart-contracts'; import { ExtensionTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { ERC20FeeProxyPaymentDetectorBase } from '../erc20/fee-proxy-contract'; import { AnyToErc20InfoRetriever } from './retrievers/any-to-erc20-proxy'; import { TheGraphInfoRetriever } from '../thegraph'; import { makeGetDeploymentInformation } from '../utils'; import { PaymentNetworkOptions, ReferenceBasedDetectorOptions } from '../types'; +import { generate8randomBytes } from '@requestnetwork/utils'; const PROXY_CONTRACT_ADDRESS_MAP = { ['0.1.0']: '0.1.0', @@ -48,8 +48,7 @@ export class AnyToERC20PaymentDetector extends ERC20FeeProxyPaymentDetectorBase< paymentNetworkCreationParameters: PaymentTypes.IAnyToErc20CreationParameters, ): Promise { // If no salt is given, generate one - const salt = - paymentNetworkCreationParameters.salt || (await Utils.crypto.generate8randomBytes()); + const salt = paymentNetworkCreationParameters.salt || (await generate8randomBytes()); return this.extension.createCreationAction({ feeAddress: paymentNetworkCreationParameters.feeAddress, diff --git a/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts b/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts index b8e3f42ed..adba109f1 100644 --- a/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts +++ b/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts @@ -1,9 +1,9 @@ import { CurrencyDefinition } from '@requestnetwork/currency'; import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { BigNumber, ethers } from 'ethers'; import { parseLogArgs, unpadAmountFromChainlink } from '../../utils'; import type { JsonFragment } from '@ethersproject/abi'; +import { getDefaultProvider } from '../../index'; /** TransferWithConversionAndReference event */ type TransferWithConversionAndReferenceArgs = { @@ -53,7 +53,7 @@ export abstract class ConversionInfoRetriever { protected maxRateTimespan: number = 0, ) { // Creates a local or default provider - this.provider = Utils.getDefaultProvider(this.network); + this.provider = getDefaultProvider(this.network); // Setup the conversion proxy contract interface this.contractConversionProxy = new ethers.Contract( diff --git a/packages/payment-detection/src/btc/default-providers/blockchain-info.ts b/packages/payment-detection/src/btc/default-providers/blockchain-info.ts index 19a37a7c2..941963301 100644 --- a/packages/payment-detection/src/btc/default-providers/blockchain-info.ts +++ b/packages/payment-detection/src/btc/default-providers/blockchain-info.ts @@ -1,8 +1,8 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const BLOCKCHAININFO_REQUEST_MAX_RETRY = 3; @@ -34,7 +34,7 @@ export class BlockchainInfoProvider implements PaymentTypes.IBitcoinDetectionPro const queryUrl = `${blockchainInfoUrl}/rawaddr/${address}?cors=true`; try { - const res = await Utils.retry(async () => Axios.get(queryUrl), { + const res = await retry(async () => Axios.get(queryUrl), { maxRetries: BLOCKCHAININFO_REQUEST_MAX_RETRY, retryDelay: BLOCKCHAININFO_REQUEST_RETRY_DELAY, })(); @@ -50,7 +50,7 @@ export class BlockchainInfoProvider implements PaymentTypes.IBitcoinDetectionPro // get all the transactions from the whole pagination for (let i = 1; i <= numberOfExtraPages; i++) { - const resExtraPage = await Utils.retry( + const resExtraPage = await retry( async () => fetch(`${blockchainInfoUrl}/rawaddr/${address}?cors=true&offset=${i * TXS_PER_PAGE}`), { diff --git a/packages/payment-detection/src/btc/default-providers/blockcypher-com.ts b/packages/payment-detection/src/btc/default-providers/blockcypher-com.ts index a161e6150..e9914b2d0 100644 --- a/packages/payment-detection/src/btc/default-providers/blockcypher-com.ts +++ b/packages/payment-detection/src/btc/default-providers/blockcypher-com.ts @@ -1,7 +1,7 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const BLOCKCYPHER_REQUEST_MAX_RETRY = 3; @@ -29,7 +29,7 @@ export class BlockcypherComProvider implements PaymentTypes.IBitcoinDetectionPro const baseUrl = this.getBaseUrl(bitcoinNetworkId); const queryUrl = `${baseUrl}/addrs/${address}`; try { - const res = await Utils.retry(async () => Axios.get(queryUrl), { + const res = await retry(async () => Axios.get(queryUrl), { maxRetries: BLOCKCYPHER_REQUEST_MAX_RETRY, retryDelay: BLOCKCYPHER_REQUEST_RETRY_DELAY, })(); diff --git a/packages/payment-detection/src/btc/default-providers/blockstream-info.ts b/packages/payment-detection/src/btc/default-providers/blockstream-info.ts index 4d7d4290a..83ec48fa7 100644 --- a/packages/payment-detection/src/btc/default-providers/blockstream-info.ts +++ b/packages/payment-detection/src/btc/default-providers/blockstream-info.ts @@ -1,7 +1,7 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const BLOCKSTREAMINFO_REQUEST_MAX_RETRY = 3; @@ -32,7 +32,7 @@ export class BlockStreamInfoProvider implements PaymentTypes.IBitcoinDetectionPr const baseUrl = this.getBaseUrl(bitcoinNetworkId); const queryUrl = `${baseUrl}/address/${address}/txs`; try { - const res = await Utils.retry(async () => Axios.get(queryUrl), { + const res = await retry(async () => Axios.get(queryUrl), { maxRetries: BLOCKSTREAMINFO_REQUEST_MAX_RETRY, retryDelay: BLOCKSTREAMINFO_REQUEST_RETRY_DELAY, })(); @@ -48,7 +48,7 @@ export class BlockStreamInfoProvider implements PaymentTypes.IBitcoinDetectionPr while (checkForMoreTransactions) { const lastTxHash = txs[txs.length - 1].txid; - const resExtraPage = await Utils.retry( + const resExtraPage = await retry( async () => fetch(`${baseUrl}/address/${address}/txs/chain/${lastTxHash}`), { maxRetries: BLOCKSTREAMINFO_REQUEST_MAX_RETRY, diff --git a/packages/payment-detection/src/btc/default-providers/chain-so.ts b/packages/payment-detection/src/btc/default-providers/chain-so.ts index 6ac867f73..8258ce457 100644 --- a/packages/payment-detection/src/btc/default-providers/chain-so.ts +++ b/packages/payment-detection/src/btc/default-providers/chain-so.ts @@ -1,8 +1,8 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import * as converterBTC from 'satoshi-bitcoin'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const CHAINSO_REQUEST_MAX_RETRY = 3; @@ -31,7 +31,7 @@ export class ChainSoProvider implements PaymentTypes.IBitcoinDetectionProvider { const queryUrl = `${baseUrl}${address}`; try { - const res = await Utils.retry(async () => Axios.get(queryUrl), { + const res = await retry(async () => Axios.get(queryUrl), { maxRetries: CHAINSO_REQUEST_MAX_RETRY, retryDelay: CHAINSO_REQUEST_RETRY_DELAY, })(); diff --git a/packages/payment-detection/src/declarative.ts b/packages/payment-detection/src/declarative.ts index 9a799e64b..c138c985d 100644 --- a/packages/payment-detection/src/declarative.ts +++ b/packages/payment-detection/src/declarative.ts @@ -4,8 +4,8 @@ import { PaymentTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { PaymentDetectorBase } from './payment-detector-base'; +import { notNull } from '@requestnetwork/utils'; /** * Handles payment detection for a declarative request, or derived. @@ -184,7 +184,7 @@ export abstract class DeclarativePaymentDetectorBase< } return null; }) - .filter(Utils.notNull); + .filter(notNull); } } diff --git a/packages/payment-detection/src/erc20/address-based-info-retriever.ts b/packages/payment-detection/src/erc20/address-based-info-retriever.ts index 85cf51921..d8dec80d4 100644 --- a/packages/payment-detection/src/erc20/address-based-info-retriever.ts +++ b/packages/payment-detection/src/erc20/address-based-info-retriever.ts @@ -1,7 +1,7 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { IPaymentRetriever } from '../types'; import { ethers } from 'ethers'; +import { getDefaultProvider } from '@requestnetwork/utils'; // The ERC20 smart contract ABI fragment containing decimals property and Transfer event const erc20BalanceOfAbiFragment = [ @@ -69,7 +69,7 @@ export default class ERC20InfoRetriever */ public async getTransferEvents(): Promise { // Creates a local or default provider - const provider = Utils.getDefaultProvider(this.network); + const provider = getDefaultProvider(this.network); // Set up the ERC20 contract interface const contract = new ethers.Contract( diff --git a/packages/payment-detection/src/erc20/currency.ts b/packages/payment-detection/src/erc20/currency.ts index 13508da64..68b8888a1 100644 --- a/packages/payment-detection/src/erc20/currency.ts +++ b/packages/payment-detection/src/erc20/currency.ts @@ -1,4 +1,3 @@ -import { utils } from 'ethers'; import { CurrencyDefinition, CurrencyManager, @@ -7,20 +6,18 @@ import { } from '@requestnetwork/currency'; import { RequestLogicTypes } from '@requestnetwork/types'; import { ERC20__factory } from '@requestnetwork/smart-contracts/types'; -import Utils from '@requestnetwork/utils'; +import { isAddress } from 'ethers/lib/utils'; +import { getDefaultProvider } from '@requestnetwork/utils'; export const loadCurrencyFromContract = async ( currency: StorageCurrency, ): Promise => { - if (!currency.network || !utils.isAddress(currency.value)) { + if (!currency.network || !isAddress(currency.value)) { return null; } try { - const contract = ERC20__factory.connect( - currency.value, - Utils.getDefaultProvider(currency.network), - ); + const contract = ERC20__factory.connect(currency.value, getDefaultProvider(currency.network)); const decimals = await contract.decimals(); if (!decimals) { diff --git a/packages/payment-detection/src/erc20/escrow-info-retriever.ts b/packages/payment-detection/src/erc20/escrow-info-retriever.ts index 4fff9e8ad..2f128d97e 100644 --- a/packages/payment-detection/src/erc20/escrow-info-retriever.ts +++ b/packages/payment-detection/src/erc20/escrow-info-retriever.ts @@ -1,9 +1,9 @@ import { PaymentTypes } from '@requestnetwork/types'; import { erc20EscrowToPayArtifact } from '@requestnetwork/smart-contracts'; -import Utils from '@requestnetwork/utils'; import { BigNumber, ethers } from 'ethers'; import { IEventRetriever } from '../types'; import { makeGetDeploymentInformation, parseLogArgs } from '../utils'; +import { getDefaultProvider } from '@requestnetwork/utils'; const ESCROW_CONTRACT_ADDRESS_MAP = { ['0.1.0']: '0.1.0', @@ -55,7 +55,7 @@ export class EscrowERC20InfoRetriever private eventName?: PaymentTypes.ESCROW_EVENTS_NAMES, ) { // Creates a local or default provider. - this.provider = Utils.getDefaultProvider(this.network); + this.provider = getDefaultProvider(this.network); // Set up the ERC20 escrow contract interface. this.contractEscrow = new ethers.Contract( diff --git a/packages/payment-detection/src/erc20/proxy-info-retriever.ts b/packages/payment-detection/src/erc20/proxy-info-retriever.ts index 41a0cae66..2ce08aa64 100644 --- a/packages/payment-detection/src/erc20/proxy-info-retriever.ts +++ b/packages/payment-detection/src/erc20/proxy-info-retriever.ts @@ -1,8 +1,8 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { IPaymentRetriever } from '../types'; import { BigNumber, ethers } from 'ethers'; import { parseLogArgs } from '../utils'; +import { getDefaultProvider } from '@requestnetwork/utils'; // The ERC20 proxy smart contract ABI fragment containing TransferWithReference event const erc20proxyContractAbiFragment = [ @@ -52,7 +52,7 @@ export default class ProxyERC20InfoRetriever private network: string, ) { // Creates a local or default provider - this.provider = Utils.getDefaultProvider(this.network); + this.provider = getDefaultProvider(this.network); // Set up the ERC20 proxy contract interface this.contractProxy = new ethers.Contract( diff --git a/packages/payment-detection/src/erc777/superfluid-retriever.ts b/packages/payment-detection/src/erc777/superfluid-retriever.ts index 609005216..ff21683f4 100644 --- a/packages/payment-detection/src/erc777/superfluid-retriever.ts +++ b/packages/payment-detection/src/erc777/superfluid-retriever.ts @@ -1,11 +1,11 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { FlowUpdatedEvent, SentEvent } from '../thegraph/generated/graphql-superfluid'; import { getTheGraphSuperfluidClient, TheGraphSuperfluidClient, TheGraphClientOptions, } from '../thegraph/superfluid'; +import { getCurrentTimestampInSecond } from '@requestnetwork/utils'; /** Parameters for getting payment events from theGraph */ type GraphPaymentQueryParams = { @@ -96,7 +96,7 @@ export class SuperFluidInfoRetriever { streamEvents.push({ oldFlowRate: streamEvents[streamEvents.length - 1].flowRate, flowRate: 0, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), blockNumber: parseInt(streamEvents[streamEvents.length - 1].blockNumber.toString()), transactionHash: streamEvents[streamEvents.length - 1].transactionHash, } as FlowUpdatedEvent); diff --git a/packages/payment-detection/src/eth/proxy-info-retriever.ts b/packages/payment-detection/src/eth/proxy-info-retriever.ts index cca9da8ee..789cefdd2 100644 --- a/packages/payment-detection/src/eth/proxy-info-retriever.ts +++ b/packages/payment-detection/src/eth/proxy-info-retriever.ts @@ -1,8 +1,8 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { IPaymentRetriever } from '../types'; import { BigNumber, ethers } from 'ethers'; import { parseLogArgs } from '../utils'; +import { getDefaultProvider } from '@requestnetwork/utils'; // The Ethereum proxy smart contract ABI fragment containing TransferWithReference event const ethProxyContractAbiFragment = [ @@ -49,7 +49,7 @@ export class EthProxyInfoRetriever private network: string, ) { // Creates a local or default provider - this.provider = Utils.getDefaultProvider(this.network); + this.provider = getDefaultProvider(this.network); // Set up the Ethereum proxy contract interface this.contractProxy = new ethers.Contract( diff --git a/packages/payment-detection/src/fee-reference-based-detector.ts b/packages/payment-detection/src/fee-reference-based-detector.ts index 7df572426..1922c6563 100644 --- a/packages/payment-detection/src/fee-reference-based-detector.ts +++ b/packages/payment-detection/src/fee-reference-based-detector.ts @@ -1,8 +1,8 @@ import { BigNumber } from 'ethers'; import { ExtensionTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types'; import { ICurrencyManager } from '@requestnetwork/currency'; -import Utils from '@requestnetwork/utils'; import { ReferenceBasedDetector } from './reference-based-detector'; +import { generate8randomBytes } from '@requestnetwork/utils'; /** * Abstract class to extend to get the payment balance of reference based requests @@ -38,7 +38,7 @@ export abstract class FeeReferenceBasedDetector< ): Promise { // If no salt is given, generate one paymentNetworkCreationParameters.salt = - paymentNetworkCreationParameters.salt || (await Utils.crypto.generate8randomBytes()); + paymentNetworkCreationParameters.salt || (await generate8randomBytes()); return this.extension.createCreationAction({ feeAddress: paymentNetworkCreationParameters.feeAddress, diff --git a/packages/payment-detection/src/index.ts b/packages/payment-detection/src/index.ts index 6dd873651..3ba743999 100644 --- a/packages/payment-detection/src/index.ts +++ b/packages/payment-detection/src/index.ts @@ -1,4 +1,8 @@ -import Utils from '@requestnetwork/utils'; +import { + getDefaultProvider, + initPaymentDetectionApiKeys, + setProviderFactory, +} from '@requestnetwork/utils'; import { PaymentNetworkFactory } from './payment-network-factory'; import PaymentReferenceCalculator from './payment-reference-calculator'; import * as BtcPaymentNetwork from './btc'; @@ -25,10 +29,6 @@ import { PaymentNetworkOptions } from './types'; export type { TheGraphClient } from './thegraph'; -const setProviderFactory = Utils.setProviderFactory; -const initPaymentDetectionApiKeys = Utils.initPaymentDetectionApiKeys; -const getDefaultProvider = Utils.getDefaultProvider; - export { PaymentNetworkFactory, PaymentNetworkOptions, diff --git a/packages/payment-detection/src/payment-network-factory.ts b/packages/payment-detection/src/payment-network-factory.ts index 904485b1c..8204115fb 100644 --- a/packages/payment-detection/src/payment-network-factory.ts +++ b/packages/payment-detection/src/payment-network-factory.ts @@ -4,7 +4,6 @@ import { PaymentTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { ICurrencyManager } from '@requestnetwork/currency'; import { ContractBasedDetector, @@ -25,6 +24,7 @@ import { AnyToERC20PaymentDetector, AnyToEthFeeProxyPaymentDetector } from './an import { NearConversionNativeTokenPaymentDetector, NearNativeTokenPaymentDetector } from './near'; import { getPaymentNetworkExtension } from './utils'; import { getTheGraphClient } from './thegraph'; +import { getDefaultProvider } from 'ethers'; const PN_ID = ExtensionTypes.PAYMENT_NETWORK_ID; @@ -99,7 +99,7 @@ export class PaymentNetworkFactory { ); }, explorerApiKeys: {}, - getRpcProvider: Utils.getDefaultProvider, + getRpcProvider: getDefaultProvider, }; return { ...defaultOptions, ...options }; } diff --git a/packages/payment-detection/src/payment-reference-calculator.ts b/packages/payment-detection/src/payment-reference-calculator.ts index 842b98518..59be64543 100644 --- a/packages/payment-detection/src/payment-reference-calculator.ts +++ b/packages/payment-detection/src/payment-reference-calculator.ts @@ -1,4 +1,4 @@ -import Utils from '@requestnetwork/utils'; +import { keccak256Hash } from '@requestnetwork/utils'; /** * Compute the payment reference @@ -7,13 +7,14 @@ import Utils from '@requestnetwork/utils'; * @param salt The salt for the request * @param address Payment or refund address */ + function calculate(requestId: string, salt: string, address: string): string { if (!requestId || !salt || !address) { throw new Error('RequestId, salt and address are mandatory to calculate the payment reference'); } // "The value is the last 8 bytes of a salted hash of the requestId: `last8Bytes(hash(requestId + salt + address))`" /* eslint-disable no-magic-numbers */ - return Utils.crypto.keccak256Hash((requestId + salt + address).toLowerCase()).slice(-16); + return keccak256Hash((requestId + salt + address).toLowerCase()).slice(-16); } export default { calculate }; diff --git a/packages/payment-detection/src/reference-based-detector.ts b/packages/payment-detection/src/reference-based-detector.ts index 111d95326..934e2c34e 100644 --- a/packages/payment-detection/src/reference-based-detector.ts +++ b/packages/payment-detection/src/reference-based-detector.ts @@ -1,9 +1,9 @@ import { ExtensionTypes, PaymentTypes, RequestLogicTypes, TypesUtils } from '@requestnetwork/types'; import { ICurrencyManager } from '@requestnetwork/currency'; -import Utils from '@requestnetwork/utils'; import PaymentReferenceCalculator from './payment-reference-calculator'; import { DeclarativePaymentDetectorBase } from './declarative'; +import { generate8randomBytes } from '@requestnetwork/utils'; /** * Abstract class to extend to get the payment balance of reference based requests @@ -45,7 +45,7 @@ export abstract class ReferenceBasedDetector< ): Promise { // If no salt is given, generate one paymentNetworkCreationParameters.salt = - paymentNetworkCreationParameters.salt || (await Utils.crypto.generate8randomBytes()); + paymentNetworkCreationParameters.salt || (await generate8randomBytes()); return this.extension.createCreationAction({ paymentAddress: paymentNetworkCreationParameters.paymentAddress, diff --git a/packages/payment-processor/test/payment/any-to-erc20-batch-proxy.test.ts b/packages/payment-processor/test/payment/any-to-erc20-batch-proxy.test.ts index 773bc66dd..14e521603 100644 --- a/packages/payment-processor/test/payment/any-to-erc20-batch-proxy.test.ts +++ b/packages/payment-processor/test/payment/any-to-erc20-batch-proxy.test.ts @@ -7,7 +7,7 @@ import { RequestLogicTypes, } from '@requestnetwork/types'; import { getErc20Balance } from '../../src/payment/erc20'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { revokeErc20Approval } from '@requestnetwork/payment-processor/src/payment/utils'; import { EnrichedRequest, IConversionPaymentSettings } from '../../src/index'; import { batchConversionPaymentsArtifact } from '@requestnetwork/smart-contracts'; @@ -59,7 +59,7 @@ const paymentSettings: IConversionPaymentSettings = { currencyManager: currencyManager, }; -const conversionPaymentSettings = Utils.deepCopy(paymentSettings); +const conversionPaymentSettings = deepCopy(paymentSettings); // conversionPaymentSettings.currencyManager = undefined; const options: IRequestPaymentOptions = { @@ -165,7 +165,7 @@ const DAIValidRequest: ClientTypes.IRequestData = { version: '1.0', }; -const FAUValidRequest = Utils.deepCopy(DAIValidRequest) as ClientTypes.IRequestData; +const FAUValidRequest = deepCopy(DAIValidRequest) as ClientTypes.IRequestData; FAUValidRequest.currencyInfo = { network: 'private', type: RequestLogicTypes.CURRENCY.ERC20 as any, @@ -220,7 +220,7 @@ describe('erc20-batch-conversion-proxy', () => { describe(`Conversion:`, () => { beforeEach(() => { jest.restoreAllMocks(); - EURRequest = Utils.deepCopy(EURValidRequest); + EURRequest = deepCopy(EURValidRequest); enrichedRequests = [ { paymentNetworkId: ExtensionTypes.PAYMENT_NETWORK_ID.ANY_TO_ERC20_PROXY, @@ -263,7 +263,7 @@ describe('erc20-batch-conversion-proxy', () => { ); }); it('should throw an error if request has no currency within paymentSettings', async () => { - const wrongPaymentSettings = Utils.deepCopy(conversionPaymentSettings); + const wrongPaymentSettings = deepCopy(conversionPaymentSettings); wrongPaymentSettings.currency = undefined; await expect( payBatchConversionProxyRequest( @@ -546,7 +546,7 @@ describe('erc20-batch-conversion-proxy', () => { describe('No conversion:', () => { beforeEach(() => { - FAURequest = Utils.deepCopy(FAUValidRequest); + FAURequest = deepCopy(FAUValidRequest); enrichedRequests = [ { paymentNetworkId: ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_FEE_PROXY_CONTRACT, diff --git a/packages/payment-processor/test/payment/any-to-erc20-proxy.test.ts b/packages/payment-processor/test/payment/any-to-erc20-proxy.test.ts index da95d9f1b..48822ca8d 100644 --- a/packages/payment-processor/test/payment/any-to-erc20-proxy.test.ts +++ b/packages/payment-processor/test/payment/any-to-erc20-proxy.test.ts @@ -1,14 +1,11 @@ import { Wallet, providers, BigNumber } from 'ethers'; - import { ClientTypes, ExtensionTypes, IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; - -import Utils from '@requestnetwork/utils'; - +import { deepCopy } from '@requestnetwork/utils'; import { approveErc20ForProxyConversionIfNeeded } from '../../src/payment/conversion-erc20'; import { payAnyToErc20ProxyRequest } from '../../src/payment/any-to-erc20-proxy'; import { ERC20__factory } from '@requestnetwork/smart-contracts/types'; @@ -116,7 +113,7 @@ describe('conversion-erc20-fee-proxy', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validEuroRequest); + const request = deepCopy(validEuroRequest); request.extensions = [] as any; await expect( diff --git a/packages/payment-processor/test/payment/any-to-eth-proxy.test.ts b/packages/payment-processor/test/payment/any-to-eth-proxy.test.ts index c48df462a..9ce12f0b2 100644 --- a/packages/payment-processor/test/payment/any-to-eth-proxy.test.ts +++ b/packages/payment-processor/test/payment/any-to-eth-proxy.test.ts @@ -1,17 +1,15 @@ import { Wallet, providers } from 'ethers'; - import { ClientTypes, ExtensionTypes, IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; - -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { payAnyToEthProxyRequest } from '../../src/payment/any-to-eth-proxy'; import { currencyManager } from './shared'; - import { IConversionPaymentSettings } from '../../src/index'; + const paymentSettings: IConversionPaymentSettings = { maxToSpend: '2500000000000000', currencyManager, @@ -70,7 +68,7 @@ const validEuroRequest: ClientTypes.IRequestData = { describe('any-to-eth-proxy', () => { describe('error checking', () => { it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validEuroRequest); + const request = deepCopy(validEuroRequest); request.extensions = [] as any; await expect(payAnyToEthProxyRequest(request, wallet, paymentSettings)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/erc20-batch-proxy.test.ts b/packages/payment-processor/test/payment/erc20-batch-proxy.test.ts index 6a7e977ea..800685317 100644 --- a/packages/payment-processor/test/payment/erc20-batch-proxy.test.ts +++ b/packages/payment-processor/test/payment/erc20-batch-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { batchPaymentsArtifact } from '@requestnetwork/smart-contracts'; import { getErc20Balance } from '../../src/payment/erc20'; @@ -74,7 +74,7 @@ const validRequest: ClientTypes.IRequestData = { version: '1.0', }; -const fauValidRequest = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; +const fauValidRequest = deepCopy(validRequest) as ClientTypes.IRequestData; fauValidRequest.currencyInfo = { network: 'private', type: RequestLogicTypes.CURRENCY.ERC20 as any, @@ -115,8 +115,8 @@ const testSuite = ( beforeEach(() => { jest.restoreAllMocks(); - request1 = Utils.deepCopy(requestTemplate1) as ClientTypes.IRequestData; - request2 = Utils.deepCopy(requestTemplate2) as ClientTypes.IRequestData; + request1 = deepCopy(requestTemplate1) as ClientTypes.IRequestData; + request2 = deepCopy(requestTemplate2) as ClientTypes.IRequestData; }); it('should throw an error if the request is not erc20', async () => { @@ -206,7 +206,7 @@ const testSuite = ( it('should pay an ERC20 request with fees', async () => { // first approve the contract - const tmpRequest = Utils.deepCopy(request1); + const tmpRequest = deepCopy(request1); let amount = 1000; const isMultiToken = !sameCurrencyValue(request1, request2); diff --git a/packages/payment-processor/test/payment/erc20-escrow-payment.test.ts b/packages/payment-processor/test/payment/erc20-escrow-payment.test.ts index 3b9bef071..1391f5008 100644 --- a/packages/payment-processor/test/payment/erc20-escrow-payment.test.ts +++ b/packages/payment-processor/test/payment/erc20-escrow-payment.test.ts @@ -5,7 +5,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { Escrow } from '../../src/'; import { getRequestPaymentValues, getSigner } from '../../src/payment/utils'; @@ -86,7 +86,7 @@ describe('erc20-escrow-payment tests:', () => { expect(values.paymentReference).toBe(paymentReference); }); it('Should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect(Escrow.payEscrow(request, wallet)).rejects.toThrowError( @@ -94,21 +94,21 @@ describe('erc20-escrow-payment tests:', () => { ); }); it('Should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect(Escrow.payEscrow(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-fee-proxy-contract request', ); }); it('Should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(Escrow.payEscrow(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-fee-proxy-contract request', ); }); it('Should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(Escrow.payEscrow(request, wallet)).rejects.toThrowError( @@ -203,7 +203,7 @@ describe('erc20-escrow-payment tests:', () => { describe('Normal Flow:', () => { it('Should pay the amount and fee from payers account', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; const payerBeforeBalance = await getErc20Balance(request, payerAddress); const escrowBeforeBalance = await getErc20Balance(request, escrowAddress); @@ -228,7 +228,7 @@ describe('erc20-escrow-payment tests:', () => { }); it('Should withdraw funds and pay funds from escrow to payee', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aabb'; // Execute payEscrow @@ -258,7 +258,7 @@ describe('erc20-escrow-payment tests:', () => { describe('Emergency Flow:', () => { it('Should initiate emergency claim', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aacc'; // Assign the paymentAddress as the payee. @@ -277,7 +277,7 @@ describe('erc20-escrow-payment tests:', () => { }); it('Should revert emergency claim', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aadd'; // Assign the paymentAddress as the payee. @@ -304,7 +304,7 @@ describe('erc20-escrow-payment tests:', () => { describe('Freeze Request Flow:', () => { it('Should freeze funds:', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aaee'; // Execute payEscrow function on smart contract. @@ -320,7 +320,7 @@ describe('erc20-escrow-payment tests:', () => { }); it('Should revert if tried to withdraw to early:', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aaff'; // Execute payEscrow. diff --git a/packages/payment-processor/test/payment/erc20-fee-proxy.test.ts b/packages/payment-processor/test/payment/erc20-fee-proxy.test.ts index 2c2003feb..592b5a527 100644 --- a/packages/payment-processor/test/payment/erc20-fee-proxy.test.ts +++ b/packages/payment-processor/test/payment/erc20-fee-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { erc20FeeProxyArtifact } from '@requestnetwork/smart-contracts'; import { approveErc20, getErc20Balance } from '../../src/payment/erc20'; @@ -88,7 +88,7 @@ describe('erc20-fee-proxy', () => { describe('encodePayErc20FeeRequest (used to pay and swap to pay)', () => { it('should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect(payErc20FeeProxyRequest(request, wallet)).rejects.toThrowError( @@ -97,7 +97,7 @@ describe('erc20-fee-proxy', () => { }); it('should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect(payErc20FeeProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-fee-proxy-contract request', @@ -105,7 +105,7 @@ describe('erc20-fee-proxy', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payErc20FeeProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-fee-proxy-contract request', @@ -113,7 +113,7 @@ describe('erc20-fee-proxy', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payErc20FeeProxyRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/erc20-proxy.test.ts b/packages/payment-processor/test/payment/erc20-proxy.test.ts index 9356a02d0..5139c18ef 100644 --- a/packages/payment-processor/test/payment/erc20-proxy.test.ts +++ b/packages/payment-processor/test/payment/erc20-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { approveErc20, getErc20Balance } from '../../src/payment/erc20'; import { _getErc20ProxyPaymentUrl, payErc20ProxyRequest } from '../../src/payment/erc20-proxy'; import { getRequestPaymentValues } from '../../src/payment/utils'; @@ -73,7 +73,7 @@ describe('getRequestPaymentValues', () => { describe('payErc20ProxyRequest', () => { it('should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect(payErc20ProxyRequest(request, wallet)).rejects.toThrowError( @@ -82,7 +82,7 @@ describe('payErc20ProxyRequest', () => { }); it('should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect(payErc20ProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-proxy-contract request', @@ -90,7 +90,7 @@ describe('payErc20ProxyRequest', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payErc20ProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-proxy-contract request', @@ -98,7 +98,7 @@ describe('payErc20ProxyRequest', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payErc20ProxyRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/erc777-stream.test.ts b/packages/payment-processor/test/payment/erc777-stream.test.ts index 468ed981f..2b01b425d 100644 --- a/packages/payment-processor/test/payment/erc777-stream.test.ts +++ b/packages/payment-processor/test/payment/erc777-stream.test.ts @@ -7,7 +7,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { closeErc777StreamRequest, @@ -91,7 +91,7 @@ describe('erc777-stream', () => { describe('encodePayErc20FeeRequest (used to pay and swap to pay)', () => { it('should throw an error if the request is not erc777', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect(payErc777StreamRequest(request, wallet)).rejects.toThrowError( @@ -100,7 +100,7 @@ describe('erc777-stream', () => { }); it('should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect(payErc777StreamRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc777-stream request', @@ -108,7 +108,7 @@ describe('erc777-stream', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payErc777StreamRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc777-stream request', @@ -116,7 +116,7 @@ describe('erc777-stream', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payErc777StreamRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/eth-batch-proxy.test.ts b/packages/payment-processor/test/payment/eth-batch-proxy.test.ts index 86327cbc8..f44ae6fbe 100644 --- a/packages/payment-processor/test/payment/eth-batch-proxy.test.ts +++ b/packages/payment-processor/test/payment/eth-batch-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { payBatchProxyRequest, encodePayBatchRequest } from '../../src/payment/batch-proxy'; import { getRequestPaymentValues } from '../../src/payment/utils'; @@ -67,7 +67,7 @@ const validRequest: ClientTypes.IRequestData = { version: '2.0.3', }; -const validRequest2 = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; +const validRequest2 = deepCopy(validRequest) as ClientTypes.IRequestData; validRequest2.extensions = { [ExtensionTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], @@ -93,7 +93,7 @@ describe('getRequestPaymentValues', () => { describe('payBatchProxyRequest', () => { it('should throw an error if one request is not eth', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ERC20; await expect( @@ -104,7 +104,7 @@ describe('payBatchProxyRequest', () => { }); it('should throw an error if in one request, currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect( payBatchProxyRequest([validRequest, request], batchVersion, wallet, batchFee), @@ -114,7 +114,7 @@ describe('payBatchProxyRequest', () => { }); it('should throw an error if one request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect( diff --git a/packages/payment-processor/test/payment/eth-fee-proxy.test.ts b/packages/payment-processor/test/payment/eth-fee-proxy.test.ts index b46174a3e..5f39d8d0c 100644 --- a/packages/payment-processor/test/payment/eth-fee-proxy.test.ts +++ b/packages/payment-processor/test/payment/eth-fee-proxy.test.ts @@ -1,13 +1,11 @@ import { Wallet, providers } from 'ethers'; - import { ClientTypes, ExtensionTypes, IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; - +import { deepCopy } from '@requestnetwork/utils'; import { encodePayEthFeeProxyRequest, payEthFeeProxyRequest, @@ -77,7 +75,7 @@ describe('getRequestPaymentValues', () => { describe('payEthFeeProxyRequest', () => { it('should throw an error if the request is not eth', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ERC20; await expect(payEthFeeProxyRequest(request, wallet)).rejects.toThrowError( @@ -86,7 +84,7 @@ describe('payEthFeeProxyRequest', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payEthFeeProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-eth-fee-proxy-contract request', @@ -94,7 +92,7 @@ describe('payEthFeeProxyRequest', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payEthFeeProxyRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/eth-input-data.test.ts b/packages/payment-processor/test/payment/eth-input-data.test.ts index 5a52eeaca..f4eaefd64 100644 --- a/packages/payment-processor/test/payment/eth-input-data.test.ts +++ b/packages/payment-processor/test/payment/eth-input-data.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { _getEthPaymentUrl, payEthInputDataRequest } from '../../src/payment/eth-input-data'; import { getRequestPaymentValues } from '../../src/payment/utils'; @@ -72,7 +72,7 @@ describe('getRequestPaymentValues', () => { describe('payEthInputDataRequest', () => { it('should throw an error if the request is not eth', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ERC20; await expect(payEthInputDataRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-eth-input-data request', @@ -80,7 +80,7 @@ describe('payEthInputDataRequest', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payEthInputDataRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-eth-input-data request', @@ -88,7 +88,7 @@ describe('payEthInputDataRequest', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payEthInputDataRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/eth-proxy.test.ts b/packages/payment-processor/test/payment/eth-proxy.test.ts index 534b59231..979090db5 100644 --- a/packages/payment-processor/test/payment/eth-proxy.test.ts +++ b/packages/payment-processor/test/payment/eth-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { encodePayEthProxyRequest, @@ -76,7 +76,7 @@ describe('getRequestPaymentValues', () => { describe('payEthProxyRequest', () => { it('should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ERC20; await expect(payEthProxyRequest(request, wallet)).rejects.toThrowError( @@ -85,7 +85,7 @@ describe('payEthProxyRequest', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payEthProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-eth-input-data request', @@ -93,7 +93,7 @@ describe('payEthProxyRequest', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payEthProxyRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/swap-any-to-erc20.test.ts b/packages/payment-processor/test/payment/swap-any-to-erc20.test.ts index 886341368..a95aec8c2 100644 --- a/packages/payment-processor/test/payment/swap-any-to-erc20.test.ts +++ b/packages/payment-processor/test/payment/swap-any-to-erc20.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { approveErc20ForSwapWithConversionIfNeeded } from '../../src/payment/swap-conversion-erc20'; import { ERC20, ERC20__factory } from '@requestnetwork/smart-contracts/types'; @@ -111,7 +111,7 @@ describe('swap-any-to-erc20', () => { }); it('should throw an error if the payment network is wrong', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); delete request.extensions[ExtensionTypes.PAYMENT_NETWORK_ID.ANY_TO_ERC20_PROXY]; await expect( @@ -123,7 +123,7 @@ describe('swap-any-to-erc20', () => { }); it('should throw an error if the conversion path is impossible', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); (request.currencyInfo = { type: RequestLogicTypes.CURRENCY.ISO4217, value: 'XXX', diff --git a/packages/payment-processor/test/payment/swap-erc20-fee-proxy.test.ts b/packages/payment-processor/test/payment/swap-erc20-fee-proxy.test.ts index d39591704..dd5e5a74a 100644 --- a/packages/payment-processor/test/payment/swap-erc20-fee-proxy.test.ts +++ b/packages/payment-processor/test/payment/swap-erc20-fee-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { getErc20Balance } from '../../src/payment/erc20'; import { approveErc20ForSwapToPayIfNeeded } from '../../src/payment/swap-erc20'; @@ -96,7 +96,7 @@ describe('swap-erc20-fee-proxy', () => { ); }); it('should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect( @@ -107,7 +107,7 @@ describe('swap-erc20-fee-proxy', () => { }); it('should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect( swapErc20FeeProxyRequest(request, wallet, validSwapSettings), @@ -117,7 +117,7 @@ describe('swap-erc20-fee-proxy', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect( swapErc20FeeProxyRequest(request, wallet, validSwapSettings), @@ -127,7 +127,7 @@ describe('swap-erc20-fee-proxy', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect( diff --git a/packages/prototype-estimator/src/mock-storage.ts b/packages/prototype-estimator/src/mock-storage.ts index 54dfd9103..db4166116 100644 --- a/packages/prototype-estimator/src/mock-storage.ts +++ b/packages/prototype-estimator/src/mock-storage.ts @@ -1,7 +1,7 @@ import MultiFormat from '@requestnetwork/multi-format'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { EventEmitter } from 'events'; +import { getCurrentTimestampInSecond, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Storage layer implemented with in-memory hashmap, to be used for testing. @@ -23,9 +23,9 @@ export default class MockStorage implements StorageTypes.IStorage { if (!content) { throw Error('Error: no content provided'); } - const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(content)); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(content)); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); this.data[hash] = { content, @@ -84,7 +84,7 @@ export default class MockStorage implements StorageTypes.IStorage { }, })); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); return { entries, diff --git a/packages/request-client.js/src/api/request-network.ts b/packages/request-client.js/src/api/request-network.ts index 8e9a9fe78..a74c16faa 100644 --- a/packages/request-client.js/src/api/request-network.ts +++ b/packages/request-client.js/src/api/request-network.ts @@ -13,7 +13,7 @@ import { SignatureProviderTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy, supportedIdentities } from '@requestnetwork/utils'; import { CurrencyManager, ICurrencyManager, @@ -29,7 +29,7 @@ import localUtils from './utils'; */ export default class RequestNetwork { public paymentNetworkFactory: PaymentNetworkFactory; - public supportedIdentities: IdentityTypes.TYPE[] = Utils.identity.supportedIdentities; + public supportedIdentities: IdentityTypes.TYPE[] = supportedIdentities; private requestLogic: RequestLogicTypes.IRequestLogic; private transaction: TransactionTypes.ITransactionManager; @@ -388,7 +388,7 @@ export default class RequestNetwork { } // avoid mutation of the parameters - const copiedRequestParameters = Utils.deepCopy(requestParameters); + const copiedRequestParameters = deepCopy(requestParameters); copiedRequestParameters.extensionsData = []; const detectionChain = diff --git a/packages/request-client.js/src/api/request.ts b/packages/request-client.js/src/api/request.ts index e403fa0f4..9d236811b 100644 --- a/packages/request-client.js/src/api/request.ts +++ b/packages/request-client.js/src/api/request.ts @@ -1,16 +1,15 @@ import { EventEmitter } from 'events'; - import { DeclarativePaymentDetector, EscrowERC20InfoRetriever, } from '@requestnetwork/payment-detection'; import { IdentityTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types'; import { ICurrencyManager } from '@requestnetwork/currency'; -import Utils from '@requestnetwork/utils'; import * as Types from '../types'; import ContentDataExtension from './content-data-extension'; import localUtils from './utils'; import { erc20EscrowToPayArtifact } from '@requestnetwork/smart-contracts'; +import { deepCopy } from '@requestnetwork/utils'; /** * Class representing a request. @@ -631,9 +630,9 @@ export default class Request { throw Error('request confirmation failed'); } - let requestData = Utils.deepCopy(this.requestData); + let requestData = deepCopy(this.requestData); - let pending = Utils.deepCopy(this.pendingData); + let pending = deepCopy(this.pendingData); if (!requestData) { requestData = pending as RequestLogicTypes.IRequest; requestData.state = RequestLogicTypes.STATE.PENDING; diff --git a/packages/request-client.js/src/api/utils.ts b/packages/request-client.js/src/api/utils.ts index 7712094bf..4eee0e979 100644 --- a/packages/request-client.js/src/api/utils.ts +++ b/packages/request-client.js/src/api/utils.ts @@ -1,5 +1,5 @@ import { RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { getCurrentTimestampInSecond } from '@requestnetwork/utils'; /** * Collection of utils functions related to the library, meant to simplify its use. */ @@ -11,7 +11,7 @@ export default { * * @returns current timestamp in second */ - getCurrentTimestampInSecond: Utils.getCurrentTimestampInSecond, + getCurrentTimestampInSecond, }; /** diff --git a/packages/request-client.js/src/http-data-access.ts b/packages/request-client.js/src/http-data-access.ts index bb4f64613..cf4397669 100644 --- a/packages/request-client.js/src/http-data-access.ts +++ b/packages/request-client.js/src/http-data-access.ts @@ -1,9 +1,9 @@ import { ClientTypes, DataAccessTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import axios, { AxiosRequestConfig } from 'axios'; import { EventEmitter } from 'events'; import httpConfigDefaults from './http-config-defaults'; +import { normalizeKeccak256Hash, retry } from '@requestnetwork/utils'; // eslint-disable-next-line @typescript-eslint/no-var-requires const packageJson = require('../package.json'); @@ -100,7 +100,7 @@ export default class HttpDataAccess implements DataAccessTypes.IDataAccess { this.axiosConfig, ); - const transactionHash: string = Utils.crypto.normalizeKeccak256Hash(transactionData).value; + const transactionHash: string = normalizeKeccak256Hash(transactionData).value; // Create the return result with EventEmitter const result: DataAccessTypes.IReturnPersistTransaction = Object.assign( @@ -203,7 +203,7 @@ export default class HttpDataAccess implements DataAccessTypes.IDataAccess { ): Promise { retryConfig.maxRetries = retryConfig.maxRetries ?? this.httpConfig.httpRequestMaxRetry; retryConfig.retryDelay = retryConfig.retryDelay ?? this.httpConfig.httpRequestRetryDelay; - const { data } = await Utils.retry( + const { data } = await retry( async () => axios.get(url, { ...this.axiosConfig, params }), retryConfig, )(); diff --git a/packages/request-client.js/src/http-metamask-data-access.ts b/packages/request-client.js/src/http-metamask-data-access.ts index dd13b9fc0..ca27f67cf 100644 --- a/packages/request-client.js/src/http-metamask-data-access.ts +++ b/packages/request-client.js/src/http-metamask-data-access.ts @@ -1,11 +1,11 @@ import { Block } from '@requestnetwork/data-access'; import { requestHashSubmitterArtifact } from '@requestnetwork/smart-contracts'; import { ClientTypes, DataAccessTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import axios, { AxiosRequestConfig } from 'axios'; import { ethers } from 'ethers'; import { EventEmitter } from 'events'; import HttpDataAccess from './http-data-access'; +import { retry } from '@requestnetwork/utils'; /** * Exposes a Data-Access module over HTTP @@ -187,7 +187,7 @@ export default class HttpMetaMaskDataAccess extends HttpDataAccess { channelId: string, timestampBoundaries?: DataAccessTypes.ITimestampBoundaries, ): Promise { - const { data } = await Utils.retry( + const { data } = await retry( async () => axios.get( '/getTransactionsByChannelId', diff --git a/packages/request-client.js/src/mock-storage.ts b/packages/request-client.js/src/mock-storage.ts index 3599ce963..6cfb0394d 100644 --- a/packages/request-client.js/src/mock-storage.ts +++ b/packages/request-client.js/src/mock-storage.ts @@ -1,7 +1,7 @@ import MultiFormat from '@requestnetwork/multi-format'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { EventEmitter } from 'events'; +import { getCurrentTimestampInSecond, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Storage layer implemented with in-memory hashmap, to be used for testing. @@ -23,9 +23,9 @@ export default class MockStorage implements StorageTypes.IStorage { if (!content) { throw Error('Error: no content provided'); } - const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(content)); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(content)); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); this.data.set(hash, { content, @@ -43,9 +43,9 @@ export default class MockStorage implements StorageTypes.IStorage { if (!content) { throw Error('Error: no content provided'); } - const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(content)); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(content)); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); const dataToStore = { content, @@ -117,7 +117,7 @@ export default class MockStorage implements StorageTypes.IStorage { }, })); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); return { entries, diff --git a/packages/request-client.js/test/api/request-network.test.ts b/packages/request-client.js/test/api/request-network.test.ts index d0b2aa281..fed1c9dd8 100644 --- a/packages/request-client.js/test/api/request-network.test.ts +++ b/packages/request-client.js/test/api/request-network.test.ts @@ -1,12 +1,12 @@ import MultiFormat from '@requestnetwork/multi-format'; import { DataAccessTypes, SignatureTypes, TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import RequestNetwork from '../../src/api/request-network'; import Request from '../../src/api/request'; import * as TestData from '../data-test'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; const mockDataAccess: DataAccessTypes.IDataAccess = { _getStatus: jest.fn(), @@ -59,7 +59,7 @@ describe('api/request-network', () => { timestamp: 1549953337, transaction: { data: 'broken transaction' }, }; - const actionWrongSigner = Utils.signature.sign(TestData.data, { + const actionWrongSigner = sign(TestData.data, { method: SignatureTypes.METHOD.ECDSA, privateKey: '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', }); @@ -71,9 +71,7 @@ describe('api/request-network', () => { data: JSON.stringify(actionWrongSigner), }, }; - const requestId = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(actionWrongSigner), - ); + const requestId = MultiFormat.serialize(normalizeKeccak256Hash(actionWrongSigner)); const mockDataAccessWithTxs: DataAccessTypes.IDataAccess = { ...mockDataAccess, diff --git a/packages/request-client.js/test/data-test-real-btc.ts b/packages/request-client.js/test/data-test-real-btc.ts index 8f22d3306..6ed341a2c 100644 --- a/packages/request-client.js/test/data-test-real-btc.ts +++ b/packages/request-client.js/test/data-test-real-btc.ts @@ -4,7 +4,7 @@ import { SignatureTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; const payee = { identity: { @@ -50,7 +50,7 @@ export const data = { version: '2.0.3', }; -export const action: RequestLogicTypes.IAction = Utils.signature.sign(data, payee.signatureParams); +export const action: RequestLogicTypes.IAction = sign(data, payee.signatureParams); export const timestampedTransaction: TransactionTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, diff --git a/packages/request-client.js/test/data-test.ts b/packages/request-client.js/test/data-test.ts index 42c8a3339..74b625611 100644 --- a/packages/request-client.js/test/data-test.ts +++ b/packages/request-client.js/test/data-test.ts @@ -8,7 +8,7 @@ import { SignatureTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; import AxiosMockAdapter from 'axios-mock-adapter'; import axios from 'axios'; import { Types } from '../src'; @@ -155,15 +155,12 @@ const dataWithDeclarativeNoPaymentInfo = { version: '2.0.3', }; -export const action: RequestLogicTypes.IAction = Utils.signature.sign( - dataWithDeclarative, - payee.signatureParams, -); -const actionWithoutExtensionsData: RequestLogicTypes.IAction = Utils.signature.sign( +export const action: RequestLogicTypes.IAction = sign(dataWithDeclarative, payee.signatureParams); +const actionWithoutExtensionsData: RequestLogicTypes.IAction = sign( dataWithoutExtensionsData, payee.signatureParams, ); -const actionWithoutPaymentInfo: RequestLogicTypes.IAction = Utils.signature.sign( +const actionWithoutPaymentInfo: RequestLogicTypes.IAction = sign( dataWithDeclarativeNoPaymentInfo, payee.signatureParams, ); @@ -191,12 +188,9 @@ export const timestampedTransactionWithoutPaymentInfo: TransactionTypes.ITimesta transaction: { data: JSON.stringify(actionWithoutPaymentInfo) }, }; -export const actionRequestId = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action)); +export const actionRequestId = MultiFormat.serialize(normalizeKeccak256Hash(action)); -export const anotherCreationAction: RequestLogicTypes.IAction = Utils.signature.sign( - data, - payer.signatureParams, -); +export const anotherCreationAction: RequestLogicTypes.IAction = sign(data, payer.signatureParams); export const anotherCreationTransactionConfirmed: TransactionTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, @@ -220,7 +214,7 @@ const dataSecondRequest = { version: '2.0.3', }; -export const actionCreationSecondRequest: RequestLogicTypes.IAction = Utils.signature.sign( +export const actionCreationSecondRequest: RequestLogicTypes.IAction = sign( dataSecondRequest, payee.signatureParams, ); @@ -232,7 +226,7 @@ export const timestampedTransactionSecondRequest: TransactionTypes.ITimestampedT }; export const actionRequestIdSecondRequest = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(actionCreationSecondRequest), + normalizeKeccak256Hash(actionCreationSecondRequest), ); export const declarativePaymentNetwork: PaymentTypes.PaymentNetworkCreateParameters = { @@ -265,11 +259,11 @@ export const signatureParametersDelegate: SignatureTypes.ISignatureParameters = export const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, signer: IdentityTypes.IIdentity): any => { if (signer.value === payee.identity.value) { - return Utils.signature.sign(data, signatureParametersPayee); + return sign(data, signatureParametersPayee); } else if (signer.value === payer.identity.value) { - return Utils.signature.sign(data, signatureParametersPayer); + return sign(data, signatureParametersPayer); } else { - return Utils.signature.sign(data, signatureParametersDelegate); + return sign(data, signatureParametersDelegate); } }, supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], diff --git a/packages/request-client.js/test/declarative-payments.test.ts b/packages/request-client.js/test/declarative-payments.test.ts index 6e105fc24..54a1fd9de 100644 --- a/packages/request-client.js/test/declarative-payments.test.ts +++ b/packages/request-client.js/test/declarative-payments.test.ts @@ -20,7 +20,7 @@ import { } from '@requestnetwork/payment-detection'; import { IRequestDataWithEvents } from '../src/types'; import { CurrencyManager } from '@requestnetwork/currency'; -import Utils from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; const httpConfig: Partial = { getConfirmationDeferDelay: 0, @@ -417,7 +417,7 @@ describe('request-client.js: declarative payments', () => { timestamp: TestData.arbitraryTimestamp, transaction: { data: JSON.stringify( - Utils.signature.sign( + sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { diff --git a/packages/request-client.js/test/index.test.ts b/packages/request-client.js/test/index.test.ts index c4ee9e2a7..6433e9731 100644 --- a/packages/request-client.js/test/index.test.ts +++ b/packages/request-client.js/test/index.test.ts @@ -9,7 +9,7 @@ import { PaymentTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { CryptoWrapper, decrypt } from '@requestnetwork/utils'; import { ethers } from 'ethers'; import AxiosMockAdapter from 'axios-mock-adapter'; @@ -54,7 +54,7 @@ const fakeDecryptionProvider: DecryptionProviderTypes.IDecryptionProvider = { ): Promise => { switch (identity.value.toLowerCase()) { case encryptionData.identity.value: - return Utils.encryption.decrypt(data, encryptionData.decryptionParams); + return decrypt(data, encryptionData.decryptionParams); default: throw new Error('Identity not registered'); @@ -1439,10 +1439,8 @@ describe('request-client.js', () => { useMockStorage: true, }); // generate address randomly to avoid collisions - const paymentAddress = - '0x' + (await Utils.crypto.CryptoWrapper.random32Bytes()).slice(12).toString('hex'); - const refundAddress = - '0x' + (await Utils.crypto.CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const paymentAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const refundAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); const paymentNetwork: PaymentTypes.PaymentNetworkCreateParameters = { id: ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_ADDRESS_BASED, @@ -1585,10 +1583,8 @@ describe('request-client.js', () => { }); // generate address randomly to avoid collisions - const paymentAddress = - '0x' + (await Utils.crypto.CryptoWrapper.random32Bytes()).slice(12).toString('hex'); - const refundAddress = - '0x' + (await Utils.crypto.CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const paymentAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const refundAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); const paymentNetwork: PaymentTypes.PaymentNetworkCreateParameters = { id: ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_ADDRESS_BASED, diff --git a/packages/request-logic/specs/example/example.ts b/packages/request-logic/specs/example/example.ts index a3d9af920..69f4915b2 100644 --- a/packages/request-logic/specs/example/example.ts +++ b/packages/request-logic/specs/example/example.ts @@ -6,9 +6,9 @@ import { SignatureProviderTypes, SignatureTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import RequestLogic from '../../src/requestLogicCore'; +import { sign } from '@requestnetwork/utils'; async function foo(): Promise { // Bob (the payee) @@ -38,8 +38,8 @@ async function foo(): Promise { const signatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, identity: IdentityTypes.IIdentity): any => ({ - [aliceRaw.identity.value as string]: Utils.signature.sign(data, aliceRaw.signatureParams), - [bobRaw.identity.value as string]: Utils.signature.sign(data, bobRaw.signatureParams), + [aliceRaw.identity.value as string]: sign(data, aliceRaw.signatureParams), + [bobRaw.identity.value as string]: sign(data, bobRaw.signatureParams), }[identity.value]), supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], supportedMethods: [SignatureTypes.METHOD.ECDSA], diff --git a/packages/request-logic/src/action.ts b/packages/request-logic/src/action.ts index 1a15ca1dd..5118c9587 100644 --- a/packages/request-logic/src/action.ts +++ b/packages/request-logic/src/action.ts @@ -1,9 +1,9 @@ import MultiFormat from '@requestnetwork/multi-format'; import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Semver from 'semver'; import Role from './role'; import Version from './version'; +import { normalizeKeccak256Hash, recover } from '@requestnetwork/utils'; /** * Function to manage Request logic action (object that will be interpreted to create or modify a request) @@ -45,7 +45,7 @@ function createAction( * @returns RequestEnum.ROLE the role of the signer (payee, payer or third party) */ function getSignerIdentityFromAction(action: RequestLogicTypes.IAction): IdentityTypes.IIdentity { - return Utils.signature.recover(action); + return recover(action); } /** @@ -125,7 +125,7 @@ function getVersionFromAction(action: RequestLogicTypes.IAction): string { function getActionHash(action: RequestLogicTypes.IAction): string { // Before the version 2.0.0, the hash was computed without the signature if (Semver.lte(action.data.version, '2.0.0')) { - return MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action.data)); + return MultiFormat.serialize(normalizeKeccak256Hash(action.data)); } - return MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action)); + return MultiFormat.serialize(normalizeKeccak256Hash(action)); } diff --git a/packages/request-logic/src/actions/accept.ts b/packages/request-logic/src/actions/accept.ts index a8538323c..712ad7320 100644 --- a/packages/request-logic/src/actions/accept.ts +++ b/packages/request-logic/src/actions/accept.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { deepCopy } from '@requestnetwork/utils'; /** * Implementation of the action accept from request logic specification @@ -69,7 +69,7 @@ function applyActionToRequest( throw new Error('Signer must be the payer'); } // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); diff --git a/packages/request-logic/src/actions/addExtensionsData.ts b/packages/request-logic/src/actions/addExtensionsData.ts index 66c711dac..9fd3034ad 100644 --- a/packages/request-logic/src/actions/addExtensionsData.ts +++ b/packages/request-logic/src/actions/addExtensionsData.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { deepCopy } from '@requestnetwork/utils'; /** * Implementation of the action add extensions data from request logic specification @@ -68,7 +68,7 @@ function applyActionToRequest( const signer: IdentityTypes.IIdentity = Action.getSignerIdentityFromAction(action); // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); diff --git a/packages/request-logic/src/actions/cancel.ts b/packages/request-logic/src/actions/cancel.ts index 48d432b21..b09816a3b 100644 --- a/packages/request-logic/src/actions/cancel.ts +++ b/packages/request-logic/src/actions/cancel.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { deepCopy } from '@requestnetwork/utils'; /** * Implementation of the action cancel from request logic specification @@ -56,7 +56,7 @@ function applyActionToRequest( const signerRole = Request.getRoleInRequest(signer, request); // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); diff --git a/packages/request-logic/src/actions/create.ts b/packages/request-logic/src/actions/create.ts index bd0b60c80..8afda7b6c 100644 --- a/packages/request-logic/src/actions/create.ts +++ b/packages/request-logic/src/actions/create.ts @@ -1,8 +1,14 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Semver from 'semver'; import Action from '../action'; import Version from '../version'; +import { + deepCopy, + getCurrentTimestampInSecond, + hasError, + isString, + isValid, +} from '@requestnetwork/utils'; /** * Implementation of the request logic specification @@ -32,20 +38,20 @@ function format( throw new Error('payee or PayerId must be given'); } - if (!Utils.amount.isValid(requestParameters.expectedAmount)) { + if (!isValid(requestParameters.expectedAmount)) { throw new Error('expectedAmount must be a positive integer'); } - if (requestParameters.payee && Utils.identity.hasError(requestParameters.payee)) { - throw new Error(`payee: ${Utils.identity.hasError(requestParameters.payee)}̀`); + if (requestParameters.payee && hasError(requestParameters.payee)) { + throw new Error(`payee: ${hasError(requestParameters.payee)}̀`); } - if (requestParameters.payer && Utils.identity.hasError(requestParameters.payer)) { - throw new Error(`payer: ${Utils.identity.hasError(requestParameters.payer)}̀`); + if (requestParameters.payer && hasError(requestParameters.payer)) { + throw new Error(`payer: ${hasError(requestParameters.payer)}̀`); } if (!requestParameters.timestamp) { - requestParameters.timestamp = Utils.getCurrentTimestampInSecond(); + requestParameters.timestamp = getCurrentTimestampInSecond(); } // convert expectedAmount to string to have a consistent numbering @@ -85,17 +91,17 @@ function createRequest( throw new Error('action.parameters.payee or action.parameters.payer must be given'); } - if (action.data.parameters.payee && Utils.identity.hasError(action.data.parameters.payee)) { - throw new Error(`payee: ${Utils.identity.hasError(action.data.parameters.payee)}̀`); + if (action.data.parameters.payee && hasError(action.data.parameters.payee)) { + throw new Error(`payee: ${hasError(action.data.parameters.payee)}̀`); } - if (action.data.parameters.payer && Utils.identity.hasError(action.data.parameters.payer)) { - throw new Error(`payer: ${Utils.identity.hasError(action.data.parameters.payer)}̀`); + if (action.data.parameters.payer && hasError(action.data.parameters.payer)) { + throw new Error(`payer: ${hasError(action.data.parameters.payer)}̀`); } if ( - !Utils.isString(action.data.parameters.expectedAmount) || - !Utils.amount.isValid(action.data.parameters.expectedAmount) + !isString(action.data.parameters.expectedAmount) || + !isValid(action.data.parameters.expectedAmount) ) { throw new Error( 'action.parameters.expectedAmount must be a string representing a positive integer', @@ -105,7 +111,7 @@ function createRequest( const signer: IdentityTypes.IIdentity = Action.getSignerIdentityFromAction(action); // Copy to not modify the action itself - const request: RequestLogicTypes.IRequest = Utils.deepCopy(action.data.parameters); + const request: RequestLogicTypes.IRequest = deepCopy(action.data.parameters); request.extensions = {}; request.requestId = Action.getRequestId(action); request.version = Action.getVersionFromAction(action); diff --git a/packages/request-logic/src/actions/increaseExpectedAmount.ts b/packages/request-logic/src/actions/increaseExpectedAmount.ts index 0a47e6858..efe65cc25 100644 --- a/packages/request-logic/src/actions/increaseExpectedAmount.ts +++ b/packages/request-logic/src/actions/increaseExpectedAmount.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { add, deepCopy, isValid } from '@requestnetwork/utils'; /** * Implementation of the action increaseExpectedAmount from request logic specification @@ -27,7 +27,7 @@ function format( signerIdentity: IdentityTypes.IIdentity, signatureProvider: SignatureProviderTypes.ISignatureProvider, ): Promise { - if (!Utils.amount.isValid(increaseAmountParameters.deltaAmount)) { + if (!isValid(increaseAmountParameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -61,7 +61,7 @@ function applyActionToRequest( if (!action.data.parameters.deltaAmount) { throw new Error('deltaAmount must be given'); } - if (!Utils.amount.isValid(action.data.parameters.deltaAmount)) { + if (!isValid(action.data.parameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -69,7 +69,7 @@ function applyActionToRequest( const signerRole = Request.getRoleInRequest(signer, request); // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); @@ -78,10 +78,7 @@ function applyActionToRequest( throw new Error('the request must not be canceled'); } // increase the expected amount and store it as string - requestCopied.expectedAmount = Utils.amount.add( - request.expectedAmount, - action.data.parameters.deltaAmount, - ); + requestCopied.expectedAmount = add(request.expectedAmount, action.data.parameters.deltaAmount); return requestCopied; } diff --git a/packages/request-logic/src/actions/reduceExpectedAmount.ts b/packages/request-logic/src/actions/reduceExpectedAmount.ts index dda8868df..b418d5f70 100644 --- a/packages/request-logic/src/actions/reduceExpectedAmount.ts +++ b/packages/request-logic/src/actions/reduceExpectedAmount.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { deepCopy, isValid, reduce } from '@requestnetwork/utils'; /** * Implementation of the action reduceExpectedAmount from request logic specification @@ -27,7 +27,7 @@ function format( signerIdentity: IdentityTypes.IIdentity, signatureProvider: SignatureProviderTypes.ISignatureProvider, ): Promise { - if (!Utils.amount.isValid(reduceAmountParameters.deltaAmount)) { + if (!isValid(reduceAmountParameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -61,7 +61,7 @@ function applyActionToRequest( if (!action.data.parameters.deltaAmount) { throw new Error('deltaAmount must be given'); } - if (!Utils.amount.isValid(action.data.parameters.deltaAmount)) { + if (!isValid(action.data.parameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -69,7 +69,7 @@ function applyActionToRequest( const signerRole = Request.getRoleInRequest(signer, request); // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); @@ -78,7 +78,7 @@ function applyActionToRequest( throw new Error('the request must not be canceled'); } // reduce the expected amount and store it as string or throw if the result is not valid - requestCopied.expectedAmount = Utils.amount.reduce( + requestCopied.expectedAmount = reduce( request.expectedAmount, action.data.parameters.deltaAmount, ); diff --git a/packages/request-logic/src/request-logic.ts b/packages/request-logic/src/request-logic.ts index 6ad87a831..63b5c323c 100644 --- a/packages/request-logic/src/request-logic.ts +++ b/packages/request-logic/src/request-logic.ts @@ -9,8 +9,8 @@ import { SignatureProviderTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import RequestLogicCore from './requestLogicCore'; +import { normalizeKeccak256Hash, notNull, uniqueByProperty } from '@requestnetwork/utils'; /** * Implementation of Request Logic @@ -457,7 +457,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { updatedBetween?: RequestLogicTypes.ITimestampBoundaries, ): Promise { // hash all the topics - const hashedTopic = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic)); + const hashedTopic = MultiFormat.serialize(normalizeKeccak256Hash(topic)); const getChannelsResult = await this.transactionManager.getChannelsByTopic( hashedTopic, @@ -477,7 +477,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { ): Promise { // hash all the topics const hashedTopics = topics.map((topic) => - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic)), + MultiFormat.serialize(normalizeKeccak256Hash(topic)), ); const getChannelsResult = await this.transactionManager.getChannelsByMultipleTopics( @@ -517,7 +517,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { // hash all the topics const hashedTopics = topics.map((topic) => - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic)), + MultiFormat.serialize(normalizeKeccak256Hash(topic)), ); return { @@ -542,16 +542,16 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { const resultGetTx = await this.transactionManager.getTransactionsByChannelId(requestId); const actions = resultGetTx.result.transactions // filter the actions ignored by the previous layers - .filter(Utils.notNull) + .filter(notNull) .sort((a, b) => a.timestamp - b.timestamp); // eslint-disable-next-line prefer-const let { ignoredTransactions, keptTransactions } = this.removeOldPendingTransactions(actions); // array of transaction without duplicates to avoid replay attack - const timestampedActionsWithoutDuplicates = Utils.uniqueByProperty( + const timestampedActionsWithoutDuplicates = uniqueByProperty( keptTransactions - .filter(Utils.notNull) + .filter(notNull) .map((t) => { try { return { @@ -568,7 +568,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { return; } }) - .filter(Utils.notNull), + .filter(notNull), 'action', ); @@ -678,10 +678,10 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { transactionsByChannel[channelId], ); - const timestampedActionsWithoutDuplicates = Utils.uniqueByProperty( + const timestampedActionsWithoutDuplicates = uniqueByProperty( keptTransactions // filter the actions ignored by the previous layers - .filter(Utils.notNull) + .filter(notNull) .map((t) => { try { return { @@ -698,7 +698,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { return; } }) - .filter(Utils.notNull), + .filter(notNull), 'action', ); @@ -820,8 +820,8 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { if (key in pendingRequestState) { // TODO: Should find a better way to do that if ( - Utils.crypto.normalizeKeccak256Hash(pendingRequestState[key]).value !== - Utils.crypto.normalizeKeccak256Hash(confirmedRequestState[key]).value + normalizeKeccak256Hash(pendingRequestState[key]).value !== + normalizeKeccak256Hash(confirmedRequestState[key]).value ) { if (!pending) { pending = {}; diff --git a/packages/request-logic/src/request.ts b/packages/request-logic/src/request.ts index 25eb798a7..4e40289ae 100644 --- a/packages/request-logic/src/request.ts +++ b/packages/request-logic/src/request.ts @@ -1,7 +1,7 @@ import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Role from './role'; +import { isValid } from '@requestnetwork/utils'; /** * Module to manage a request @@ -63,7 +63,7 @@ function checkRequest(request: RequestLogicTypes.IRequest): boolean { if (request.payer && request.payer.type !== IdentityTypes.TYPE.ETHEREUM_ADDRESS) { throw Error('request.payer.type not supported'); } - if (!Utils.amount.isValid(request.expectedAmount)) { + if (!isValid(request.expectedAmount)) { throw Error('expectedAmount must be a positive integer'); } return true; diff --git a/packages/request-logic/src/requestLogicCore.ts b/packages/request-logic/src/requestLogicCore.ts index 2d3c497c9..f4da831dd 100644 --- a/packages/request-logic/src/requestLogicCore.ts +++ b/packages/request-logic/src/requestLogicCore.ts @@ -1,5 +1,4 @@ import { AdvancedLogicTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from './action'; import Request from './request'; @@ -9,6 +8,7 @@ import CancelAction from './actions/cancel'; import CreateAction from './actions/create'; import IncreaseExpectedAmountAction from './actions/increaseExpectedAmount'; import ReduceExpectedAmountAction from './actions/reduceExpectedAmount'; +import { deepCopy } from '@requestnetwork/utils'; /** * Implementation of Request Logic Core @@ -45,7 +45,7 @@ function applyActionToRequest( } // we don't want to modify the original request state - const requestCopied: RequestLogicTypes.IRequest | null = request ? Utils.deepCopy(request) : null; + const requestCopied: RequestLogicTypes.IRequest | null = request ? deepCopy(request) : null; let requestAfterApply: RequestLogicTypes.IRequest | null = null; diff --git a/packages/request-logic/src/role.ts b/packages/request-logic/src/role.ts index 098cb99f1..16933a660 100644 --- a/packages/request-logic/src/role.ts +++ b/packages/request-logic/src/role.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { areEqual } from '@requestnetwork/utils'; /** * Function to manage Request Logic Role @@ -17,10 +17,10 @@ export default { * @returns Types.ROLE the role of identity in parameters */ function getRole(identity: IdentityTypes.IIdentity, parameters: any): RequestLogicTypes.ROLE { - if (parameters.payee && Utils.identity.areEqual(parameters.payee, identity)) { + if (parameters.payee && areEqual(parameters.payee, identity)) { return RequestLogicTypes.ROLE.PAYEE; } - if (parameters.payer && Utils.identity.areEqual(parameters.payer, identity)) { + if (parameters.payer && areEqual(parameters.payer, identity)) { return RequestLogicTypes.ROLE.PAYER; } diff --git a/packages/request-logic/test/index.test.ts b/packages/request-logic/test/index.test.ts index e8650a8df..d0b3cbd0d 100644 --- a/packages/request-logic/test/index.test.ts +++ b/packages/request-logic/test/index.test.ts @@ -2,12 +2,12 @@ import { EventEmitter } from 'events'; import MultiFormat from '@requestnetwork/multi-format'; import { AdvancedLogicTypes, RequestLogicTypes, TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { RequestLogic } from '../src/index'; import * as TestData from './unit/utils/test-data-generator'; import Version from '../src/version'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; const CURRENT_VERSION = Version.currentVersion; @@ -26,8 +26,8 @@ const unsignedAction: RequestLogicTypes.IUnsignedAction = { parameters: createParams, version: CURRENT_VERSION, }; -const action = Utils.signature.sign(unsignedAction, TestData.payeeRaw.signatureParams); -const requestId = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action)); +const action = sign(unsignedAction, TestData.payeeRaw.signatureParams); +const requestId = MultiFormat.serialize(normalizeKeccak256Hash(action)); const fakeTxHash = '01aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; @@ -167,8 +167,8 @@ describe('index', () => { JSON.stringify(action), requestId, [ - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payeeRaw.identity)), - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payerRaw.identity)), + MultiFormat.serialize(normalizeKeccak256Hash(TestData.payeeRaw.identity)), + MultiFormat.serialize(normalizeKeccak256Hash(TestData.payerRaw.identity)), ], ); }); @@ -324,8 +324,8 @@ describe('index', () => { JSON.stringify(action), requestId, [ - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payeeRaw.identity)), - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payerRaw.identity)), + MultiFormat.serialize(normalizeKeccak256Hash(TestData.payeeRaw.identity)), + MultiFormat.serialize(normalizeKeccak256Hash(TestData.payerRaw.identity)), ], [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], ); @@ -496,7 +496,7 @@ describe('index', () => { }); it('cannot accept as payee', async () => { - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -592,7 +592,7 @@ describe('index', () => { }); it('cannot cancel if not payee or payer', async () => { - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -693,7 +693,7 @@ describe('index', () => { ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot increaseExpectedAmountRequest as payee', async () => { - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -799,7 +799,7 @@ describe('index', () => { ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot reduceExpectedAmountRequest as payer', async () => { - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -908,7 +908,7 @@ describe('index', () => { }, }; - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -962,7 +962,7 @@ describe('index', () => { describe('getRequestFromId', () => { it('can getRequestFromId', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -980,7 +980,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -991,7 +991,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1098,7 +1098,7 @@ describe('index', () => { }); it('can getRequestFromId ignore old pending transaction', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1116,7 +1116,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1127,7 +1127,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1237,7 +1237,7 @@ describe('index', () => { }); it('can getRequestFromId with pending transaction', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1255,7 +1255,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1266,7 +1266,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1376,7 +1376,7 @@ describe('index', () => { }); it('can getRequestFromId ignore the same transactions even with different case', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1394,7 +1394,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1405,7 +1405,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const actionReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const actionReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1417,7 +1417,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionReduce2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionReduce2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1538,7 +1538,7 @@ describe('index', () => { }); it('can getRequestFromId do not ignore the same transactions if different nonces', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1556,7 +1556,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1567,7 +1567,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const actionReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const actionReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1579,7 +1579,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionReduce2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionReduce2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1736,7 +1736,7 @@ describe('index', () => { }); it('should ignored the corrupted data (e.g: wrong properties)', async () => { - const actionCorrupted: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCorrupted: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1811,15 +1811,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); - const newRequestId = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), - ); + const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1830,7 +1828,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1856,15 +1854,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); - const newRequestId2 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), - ); + const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -1889,13 +1885,11 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); - const newRequestId3 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), - ); + const newRequestId3 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation3)); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, @@ -1980,15 +1974,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); - const newRequestId = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), - ); + const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1999,7 +1991,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -2025,15 +2017,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); - const newRequestId2 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), - ); + const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -2058,13 +2048,11 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); - const newRequestId3 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), - ); + const newRequestId3 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation3)); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, @@ -2155,7 +2143,7 @@ describe('index', () => { }); it('should ignore the transaction none parsable and the rejected action', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -2173,7 +2161,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const acceptNotValid: RequestLogicTypes.IAction = Utils.signature.sign( + const acceptNotValid: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -2250,15 +2238,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); - const newRequestId = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), - ); + const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -2269,7 +2255,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -2295,15 +2281,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); - const newRequestId2 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), - ); + const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -2328,13 +2312,11 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); - const newRequestId3 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), - ); + const newRequestId3 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation3)); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, diff --git a/packages/request-logic/test/unit/action.test.ts b/packages/request-logic/test/unit/action.test.ts index 4a53d3a0a..a308739db 100644 --- a/packages/request-logic/test/unit/action.test.ts +++ b/packages/request-logic/test/unit/action.test.ts @@ -5,7 +5,7 @@ import { SignatureProviderTypes, SignatureTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy, normalizeKeccak256Hash } from '@requestnetwork/utils'; import Action from '../../src/action'; import CreateAction from '../../src/actions/create'; @@ -46,7 +46,7 @@ const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { describe('Action', () => { it('can getRequestId() of current version', () => { const reqId = Action.getRequestId(signedAction); - expect(reqId).toBe(MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(signedAction))); + expect(reqId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(signedAction))); }); it('can getRequestId() of version before or equal 2.0.0', () => { const randomUnsignedAction200 = { @@ -72,9 +72,7 @@ describe('Action', () => { }; const reqId = Action.getRequestId(signedAction200); - expect(reqId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(randomUnsignedAction200)), - ); + expect(reqId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(randomUnsignedAction200))); }); it('can getRoleInAction()', () => { @@ -110,7 +108,7 @@ describe('Action', () => { it('can isActionVersionSupported()', () => { expect(Action.isActionVersionSupported(signedAction)).toBeTruthy(); - const wrongVersionAction = Utils.deepCopy(signedAction); + const wrongVersionAction = deepCopy(signedAction); wrongVersionAction.data.version = '10.0.0'; expect(Action.isActionVersionSupported(wrongVersionAction)).toBeFalsy(); diff --git a/packages/request-logic/test/unit/actions/accept.test.ts b/packages/request-logic/test/unit/actions/accept.test.ts index b006bdbdc..2f7b3d172 100644 --- a/packages/request-logic/test/unit/actions/accept.test.ts +++ b/packages/request-logic/test/unit/actions/accept.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import AcceptAction from '../../../src/actions/accept'; import Version from '../../../src/version'; @@ -57,7 +57,7 @@ describe('actions/accept', () => { const request = AcceptAction.applyActionToRequest( actionAccept, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -118,7 +118,7 @@ describe('actions/accept', () => { AcceptAction.applyActionToRequest( actionAccept, 1, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('Signer must be the payer'); }); @@ -133,7 +133,7 @@ describe('actions/accept', () => { AcceptAction.applyActionToRequest( actionAccept, 1, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('Signer must be the payer'); }); @@ -152,11 +152,7 @@ describe('actions/accept', () => { }, }; expect(() => - AcceptAction.applyActionToRequest( - action, - 1, - Utils.deepCopy(TestData.requestCreatedNoExtension), - ), + AcceptAction.applyActionToRequest(action, 1, deepCopy(TestData.requestCreatedNoExtension)), ).toThrowError('requestId must be given'); }); @@ -234,11 +230,7 @@ describe('actions/accept', () => { }; expect(() => - AcceptAction.applyActionToRequest( - action, - 1, - Utils.deepCopy(TestData.requestCanceledNoExtension), - ), + AcceptAction.applyActionToRequest(action, 1, deepCopy(TestData.requestCanceledNoExtension)), ).toThrowError('the request state must be created'); }); @@ -259,11 +251,7 @@ describe('actions/accept', () => { }; expect(() => - AcceptAction.applyActionToRequest( - action, - 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), - ), + AcceptAction.applyActionToRequest(action, 2, deepCopy(TestData.requestCanceledNoExtension)), ).toThrowError('the request state must be created'); }); @@ -281,7 +269,7 @@ describe('actions/accept', () => { const request = AcceptAction.applyActionToRequest( actionAccept, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -344,7 +332,7 @@ describe('actions/accept', () => { const request = AcceptAction.applyActionToRequest( actionAccept, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -411,7 +399,7 @@ describe('actions/accept', () => { const request = AcceptAction.applyActionToRequest( actionAccept, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' diff --git a/packages/request-logic/test/unit/actions/addExtensionsData.test.ts b/packages/request-logic/test/unit/actions/addExtensionsData.test.ts index 840fc793d..95b769f83 100644 --- a/packages/request-logic/test/unit/actions/addExtensionsData.test.ts +++ b/packages/request-logic/test/unit/actions/addExtensionsData.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import AddExtensionsDataAction from '../../../src/actions/addExtensionsData'; import Version from '../../../src/version'; @@ -75,7 +75,7 @@ describe('actions/addExtensionsData', () => { const request = AddExtensionsDataAction.applyActionToRequest( actionAddExtensionsData, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -141,7 +141,7 @@ describe('actions/addExtensionsData', () => { AddExtensionsDataAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('requestId must be given'); }); @@ -163,7 +163,7 @@ describe('actions/addExtensionsData', () => { AddExtensionsDataAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('extensionsData must be given'); }); @@ -185,7 +185,7 @@ describe('actions/addExtensionsData', () => { AddExtensionsDataAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('extensionsData must be given'); }); @@ -204,7 +204,7 @@ describe('actions/addExtensionsData', () => { const request = AddExtensionsDataAction.applyActionToRequest( actionAddExtensionsData, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -267,7 +267,7 @@ describe('actions/addExtensionsData', () => { const request = AddExtensionsDataAction.applyActionToRequest( actionAddExtensionsData, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' diff --git a/packages/request-logic/test/unit/actions/cancel.test.ts b/packages/request-logic/test/unit/actions/cancel.test.ts index 3608378fa..580be2f78 100644 --- a/packages/request-logic/test/unit/actions/cancel.test.ts +++ b/packages/request-logic/test/unit/actions/cancel.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import CancelAction from '../../../src/actions/cancel'; import Version from '../../../src/version'; @@ -60,7 +60,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -122,7 +122,7 @@ describe('actions/cancel', () => { CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestAcceptedNoExtension), + deepCopy(TestData.requestAcceptedNoExtension), ), ).toThrowError('A payer cancel need to be done on a request with the state created'); }); @@ -139,7 +139,7 @@ describe('actions/cancel', () => { CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), + deepCopy(TestData.requestCanceledNoExtension), ), ).toThrowError('A payer cancel need to be done on a request with the state created'); }); @@ -155,7 +155,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -215,7 +215,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestAcceptedNoExtension), + deepCopy(TestData.requestAcceptedNoExtension), ); // 'requestId is wrong' @@ -276,7 +276,7 @@ describe('actions/cancel', () => { CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), + deepCopy(TestData.requestCanceledNoExtension), ), ).toThrowError('Cannot cancel an already canceled request'); }); @@ -294,7 +294,7 @@ describe('actions/cancel', () => { CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('Signer must be the payer or the payee'); }); @@ -314,11 +314,7 @@ describe('actions/cancel', () => { }; expect(() => - CancelAction.applyActionToRequest( - action, - 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), - ), + CancelAction.applyActionToRequest(action, 2, deepCopy(TestData.requestCreatedNoExtension)), ).toThrowError('requestId must be given'); }); it('cannot cancel by payer if no payer in state', () => { @@ -447,7 +443,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -510,7 +506,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -570,7 +566,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' diff --git a/packages/request-logic/test/unit/actions/create.test.ts b/packages/request-logic/test/unit/actions/create.test.ts index 781a9b43a..bfcd3fcdf 100644 --- a/packages/request-logic/test/unit/actions/create.test.ts +++ b/packages/request-logic/test/unit/actions/create.test.ts @@ -1,7 +1,7 @@ import MultiFormat from '@requestnetwork/multi-format'; import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; import CreateAction from '../../../src/actions/create'; @@ -647,9 +647,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -719,9 +717,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -791,9 +787,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -862,9 +856,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -1027,9 +1019,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, diff --git a/packages/request-logic/test/unit/actions/increaseExpectedAmount.test.ts b/packages/request-logic/test/unit/actions/increaseExpectedAmount.test.ts index 6cee4bfd6..f9166d9ab 100644 --- a/packages/request-logic/test/unit/actions/increaseExpectedAmount.test.ts +++ b/packages/request-logic/test/unit/actions/increaseExpectedAmount.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import IncreaseExpectedAmountAction from '../../../src/actions/increaseExpectedAmount'; import Version from '../../../src/version'; @@ -118,7 +118,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -181,7 +181,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('signer must be the payer'); }); @@ -199,7 +199,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('signer must be the payer'); }); @@ -224,7 +224,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('requestId must be given'); }); @@ -249,7 +249,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('deltaAmount must be given'); }); @@ -325,7 +325,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), + deepCopy(TestData.requestCanceledNoExtension), ), ).toThrowError('the request must not be canceled'); }); @@ -343,7 +343,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestAcceptedNoExtension), + deepCopy(TestData.requestAcceptedNoExtension), ); // 'requestId is wrong' @@ -407,7 +407,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -471,7 +471,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -532,7 +532,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -602,7 +602,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -629,7 +629,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -655,7 +655,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('deltaAmount must be a string representing a positive integer'); }); diff --git a/packages/request-logic/test/unit/actions/reduceExpectedAmount.test.ts b/packages/request-logic/test/unit/actions/reduceExpectedAmount.test.ts index c03c4c345..190e3aeb5 100644 --- a/packages/request-logic/test/unit/actions/reduceExpectedAmount.test.ts +++ b/packages/request-logic/test/unit/actions/reduceExpectedAmount.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import ReduceExpectedAmountAction from '../../../src/actions/reduceExpectedAmount'; import Version from '../../../src/version'; @@ -119,7 +119,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -182,7 +182,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('signer must be the payee'); }); @@ -200,7 +200,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('signer must be the payee'); }); @@ -224,7 +224,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('requestId must be given'); }); @@ -248,7 +248,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('deltaAmount must be given'); }); @@ -324,7 +324,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), + deepCopy(TestData.requestCanceledNoExtension), ); }).toThrowError('the request must not be canceled'); }); @@ -342,7 +342,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestAcceptedNoExtension), + deepCopy(TestData.requestAcceptedNoExtension), ); // 'requestId is wrong' @@ -406,7 +406,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -470,7 +470,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -531,7 +531,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -601,7 +601,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -627,7 +627,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -652,7 +652,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -670,7 +670,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -732,7 +732,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('result of reduce is not valid'); }); diff --git a/packages/request-logic/test/unit/requestLogicCore.test.ts b/packages/request-logic/test/unit/requestLogicCore.test.ts index 4c7b61021..bb85cfcf6 100644 --- a/packages/request-logic/test/unit/requestLogicCore.test.ts +++ b/packages/request-logic/test/unit/requestLogicCore.test.ts @@ -6,7 +6,7 @@ import { RequestLogicTypes, SignatureTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy, normalizeKeccak256Hash } from '@requestnetwork/utils'; import Version from '../../src/version'; const CURRENT_VERSION = Version.currentVersion; @@ -51,7 +51,7 @@ describe('requestLogicCore', () => { expect(() => RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), action, 2, fakeAdvancedLogic, @@ -392,9 +392,7 @@ describe('requestLogicCore', () => { ); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -431,7 +429,7 @@ describe('requestLogicCore', () => { ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionAccept, 2, fakeAdvancedLogic, @@ -485,7 +483,7 @@ describe('requestLogicCore', () => { TestData.fakeSignatureProvider, ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionCancel, 2, fakeAdvancedLogic, @@ -543,7 +541,7 @@ describe('requestLogicCore', () => { ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionIncreaseAmount, 2, fakeAdvancedLogic, @@ -601,7 +599,7 @@ describe('requestLogicCore', () => { ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionReduceAmount, 2, fakeAdvancedLogic, @@ -654,7 +652,7 @@ describe('requestLogicCore', () => { ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionAddExtensionsData, 2, fakeAdvancedLogic, diff --git a/packages/request-logic/test/unit/utils/test-data-generator.ts b/packages/request-logic/test/unit/utils/test-data-generator.ts index 3e8f190e0..25a107eb2 100644 --- a/packages/request-logic/test/unit/utils/test-data-generator.ts +++ b/packages/request-logic/test/unit/utils/test-data-generator.ts @@ -6,7 +6,7 @@ import { SignatureTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; import Version from '../../../src/version'; const CURRENT_VERSION = Version.currentVersion; @@ -280,9 +280,9 @@ export const fakeIdentity = { export const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, identity: IdentityTypes.IIdentity): any => ({ - [payeeRaw.address as string]: Utils.signature.sign(data, payeeRaw.signatureParams), - [payerRaw.address as string]: Utils.signature.sign(data, payerRaw.signatureParams), - [otherIdRaw.address as string]: Utils.signature.sign(data, otherIdRaw.signatureParams), + [payeeRaw.address as string]: sign(data, payeeRaw.signatureParams), + [payerRaw.address as string]: sign(data, payerRaw.signatureParams), + [otherIdRaw.address as string]: sign(data, otherIdRaw.signatureParams), }[identity.value]), supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], supportedMethods: [SignatureTypes.METHOD.ECDSA], diff --git a/packages/request-node/src/logger.ts b/packages/request-node/src/logger.ts index f9e565074..fb2980810 100644 --- a/packages/request-node/src/logger.ts +++ b/packages/request-node/src/logger.ts @@ -1,5 +1,5 @@ import { LogTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { SimpleLogger } from '@requestnetwork/utils'; import chalk from 'chalk'; /** The different logging modes supported by this logger */ @@ -20,7 +20,7 @@ const levelColor = { /** * A logger for the Request Node that extends the `SimpleLogger` */ -export class Logger extends Utils.SimpleLogger { +export class Logger extends SimpleLogger { // The class modeType private mode: modeType; diff --git a/packages/request-node/src/request/persistTransaction.ts b/packages/request-node/src/request/persistTransaction.ts index 9b190c369..768e72244 100644 --- a/packages/request-node/src/request/persistTransaction.ts +++ b/packages/request-node/src/request/persistTransaction.ts @@ -1,10 +1,10 @@ import { LogTypes, MultiFormatTypes, DataAccessTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { Request, Response } from 'express'; import { StatusCodes } from 'http-status-codes'; import { getPersistTransactionTimeout } from '../config'; import ConfirmedTransactionStore from './confirmedTransactionStore'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Class to persist transactions though the data-access layer @@ -52,7 +52,7 @@ export default class PersistTransactionHandler { return; } try { - const transactionHash: MultiFormatTypes.HashTypes.IHash = Utils.crypto.normalizeKeccak256Hash( + const transactionHash: MultiFormatTypes.HashTypes.IHash = normalizeKeccak256Hash( clientRequest.body.transactionData, ); diff --git a/packages/request-node/src/requestNode.ts b/packages/request-node/src/requestNode.ts index 3ca028e00..5fcd45184 100644 --- a/packages/request-node/src/requestNode.ts +++ b/packages/request-node/src/requestNode.ts @@ -7,12 +7,12 @@ import { getInitializationStorageFilePath, getMnemonic } from './config'; import { getEthereumStorage, getIpfsStorage } from './storageUtils'; import { RequestNodeBase } from './requestNodeBase'; -import Utils from '@requestnetwork/utils'; +import { SimpleLogger } from '@requestnetwork/utils'; export class RequestNode extends RequestNodeBase { constructor(logger?: LogTypes.ILogger) { const initializationStoragePath = getInitializationStorageFilePath(); - logger = logger || new Utils.SimpleLogger(); + logger = logger || new SimpleLogger(); const store = initializationStoragePath ? new KeyvFile({ diff --git a/packages/request-node/src/requestNodeBase.ts b/packages/request-node/src/requestNodeBase.ts index 12666e35f..81c05c5be 100644 --- a/packages/request-node/src/requestNodeBase.ts +++ b/packages/request-node/src/requestNodeBase.ts @@ -1,5 +1,5 @@ import { DataAccessTypes, LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { SimpleLogger } from '@requestnetwork/utils'; import cors from 'cors'; import { Server } from 'http'; import express, { NextFunction, Request, Response } from 'express'; @@ -61,7 +61,7 @@ export class RequestNodeBase { ) { this.initialized = false; - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.dataAccess = dataAccess; this.confirmedTransactionStore = new ConfirmedTransactionStore(store); diff --git a/packages/request-node/src/thegraph-node.ts b/packages/request-node/src/thegraph-node.ts index 81bbddcf5..757a60332 100644 --- a/packages/request-node/src/thegraph-node.ts +++ b/packages/request-node/src/thegraph-node.ts @@ -6,9 +6,9 @@ import { LogTypes } from '@requestnetwork/types'; import { RequestNodeBase } from './requestNodeBase'; import * as config from './config'; import { getIpfsStorage } from './storageUtils'; -import Utils from '@requestnetwork/utils'; import { TheGraphDataAccess } from '@requestnetwork/thegraph-data-access'; import { EthereumStorageEthers } from '@requestnetwork/ethereum-storage'; +import { SimpleLogger } from '@requestnetwork/utils'; const getNetworkFromId = (networkId: number) => { const customNames: Record = { @@ -20,7 +20,7 @@ const getNetworkFromId = (networkId: number) => { export class TheGraphRequestNode extends RequestNodeBase { constructor(url: string, logger?: LogTypes.ILogger) { const initializationStoragePath = config.getInitializationStorageFilePath(); - logger = logger || new Utils.SimpleLogger(); + logger = logger || new SimpleLogger(); const store = initializationStoragePath ? new KeyvFile({ diff --git a/packages/request-node/test/getConfirmedTransaction.test.ts b/packages/request-node/test/getConfirmedTransaction.test.ts index d5a7db037..4cd49ecd5 100644 --- a/packages/request-node/test/getConfirmedTransaction.test.ts +++ b/packages/request-node/test/getConfirmedTransaction.test.ts @@ -1,4 +1,4 @@ -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; import { StatusCodes } from 'http-status-codes'; import request from 'supertest'; import { RequestNode } from '../src/requestNode'; @@ -7,7 +7,7 @@ import { RequestNodeBase } from '../src/requestNodeBase'; const channelId = '010aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; const transactionData = { data: 'this is sample data for a transaction' }; -const transactionHash = Utils.crypto.normalizeKeccak256Hash(transactionData).value; +const transactionHash = normalizeKeccak256Hash(transactionData).value; let requestNodeInstance: RequestNodeBase; let server: any; diff --git a/packages/smart-contracts/hardhat.config.ts b/packages/smart-contracts/hardhat.config.ts index e02716a45..6d304a713 100644 --- a/packages/smart-contracts/hardhat.config.ts +++ b/packages/smart-contracts/hardhat.config.ts @@ -13,8 +13,8 @@ import { HardhatRuntimeEnvironmentExtended } from './scripts-create2/types'; import { computeCreate2DeploymentAddressesFromList } from './scripts-create2/compute-one-address'; import { VerifyCreate2FromList } from './scripts-create2/verify'; import { deployWithCreate2FromList } from './scripts-create2/deploy'; -import utils from '@requestnetwork/utils'; import { NUMBER_ERRORS } from './scripts/utils'; +import { networkRpcs } from '@requestnetwork/utils'; config(); @@ -45,8 +45,7 @@ const requestDeployer = process.env.REQUEST_DEPLOYER_LIVE ? LIVE_DEPLOYER_ADDRESS : LOCAL_DEPLOYER_ADDRESS; -const url = (network: string): string => - process.env.WEB3_PROVIDER_URL || utils.networkRpcs[network]; +const url = (network: string): string => process.env.WEB3_PROVIDER_URL || networkRpcs[network]; export default { solidity: '0.8.9', diff --git a/packages/smart-contracts/scripts-create2/check-deployer.ts b/packages/smart-contracts/scripts-create2/check-deployer.ts index 637c4ce36..e1c3c689a 100644 --- a/packages/smart-contracts/scripts-create2/check-deployer.ts +++ b/packages/smart-contracts/scripts-create2/check-deployer.ts @@ -1,5 +1,5 @@ -import utils from '@requestnetwork/utils'; import { HardhatRuntimeEnvironmentExtended } from './types'; +import { getCeloProvider, getDefaultProvider } from '@requestnetwork/utils'; export const checkCreate2Deployer = async ( hre: HardhatRuntimeEnvironmentExtended, @@ -14,9 +14,9 @@ export const checkCreate2Deployer = async ( hre.config.xdeploy.networks.map(async (network: string) => { let provider; if (network === 'celo') { - provider = utils.getCeloProvider(); + provider = getCeloProvider(); } else { - provider = utils.getDefaultProvider(network); + provider = getDefaultProvider(network); } const code = await provider.getCode(hre.config.xdeploy.deployerAddress); diff --git a/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts b/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts index f6445261e..344126d20 100644 --- a/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts +++ b/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts @@ -2,9 +2,9 @@ import { chainlinkConversionPath } from '../../src/lib'; import { uniswapV2RouterAddresses } from '../../scripts/utils'; import * as artifacts from '../../src/lib'; import { BigNumber, Overrides, Wallet } from 'ethers'; -import utils from '@requestnetwork/utils'; import { HardhatRuntimeEnvironmentExtended } from '../types'; import { parseUnits } from 'ethers/lib/utils'; +import { estimateGasFees, getCeloProvider, getDefaultProvider } from '@requestnetwork/utils'; // Fees: 0.5% export const REQUEST_SWAP_FEES = 5; @@ -243,15 +243,15 @@ export const getSignerAndGasFees = async ( }> => { let provider; if (network === 'celo') { - provider = utils.getCeloProvider(); + provider = getCeloProvider(); } else { - provider = utils.getDefaultProvider(network); + provider = getDefaultProvider(network); } const signer = new hre.ethers.Wallet(hre.config.xdeploy.signer).connect(provider); let txOverrides; try { - txOverrides = await utils.estimateGasFees({ provider }); + txOverrides = await estimateGasFees({ provider }); } catch (err) { txOverrides = {}; } diff --git a/packages/smart-contracts/scripts-create2/xdeployer.ts b/packages/smart-contracts/scripts-create2/xdeployer.ts index c8e8e0088..c9026faf4 100644 --- a/packages/smart-contracts/scripts-create2/xdeployer.ts +++ b/packages/smart-contracts/scripts-create2/xdeployer.ts @@ -1,7 +1,7 @@ import { HardhatRuntimeEnvironmentExtended, IDeploymentParams, IDeploymentResult } from './types'; -import utils from '@requestnetwork/utils'; import { requestDeployer } from '../src/lib'; import { Overrides } from 'ethers'; +import { estimateGasFees, getCeloProvider, getDefaultProvider } from '@requestnetwork/utils'; const ZERO_ETH_INPUT = 0; @@ -44,9 +44,9 @@ export const xdeploy = async ( console.log(`... on ${network}`); let provider; if (network === 'celo') { - provider = utils.getCeloProvider(); + provider = getCeloProvider(); } else { - provider = utils.getDefaultProvider(network); + provider = getDefaultProvider(network); } const wallet = new hre.ethers.Wallet(hre.config.xdeploy.signer, provider); const signer = wallet.connect(provider); @@ -74,7 +74,7 @@ export const xdeploy = async ( let txOverrides: Overrides; try { - txOverrides = await utils.estimateGasFees({ provider }); + txOverrides = await estimateGasFees({ provider }); const gasLimit = hre.config.xdeploy.gasLimit; txOverrides.gasLimit = gasLimit; } catch (e) { diff --git a/packages/smart-contracts/test/contracts/BatchConversionPayments.test.ts b/packages/smart-contracts/test/contracts/BatchConversionPayments.test.ts index 5f12cc131..6506ae36a 100644 --- a/packages/smart-contracts/test/contracts/BatchConversionPayments.test.ts +++ b/packages/smart-contracts/test/contracts/BatchConversionPayments.test.ts @@ -17,7 +17,7 @@ import { CurrencyManager } from '@requestnetwork/currency'; import { chainlinkConversionPath } from '../../src/lib'; import { FAU_USD_RATE } from '../../scripts/test-deploy-batch-conversion-deployment'; import { localERC20AlphaArtifact, secondLocalERC20AlphaArtifact } from './localArtifacts'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { HttpNetworkConfig } from 'hardhat/types'; import { DAI_USD_RATE, @@ -754,28 +754,28 @@ describe('contract: BatchConversionPayments', async () => { describe('batchMultiERC20ConversionPayments errors', async () => { it('cannot transfer with invalid path', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); convRequest.path = [EUR_hash, ETH_hash, DAI_address]; await expect( batchConversionProxy.batchMultiERC20ConversionPayments([convRequest], [], feeAddress), ).to.be.revertedWith('revert No aggregator found'); }); it('cannot transfer if max to spend too low', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); convRequest.maxToSpend = '1000000'; // not enough await expect( batchConversionProxy.batchMultiERC20ConversionPayments([convRequest], [], feeAddress), ).to.be.revertedWith('Amount to pay is over the user limit'); }); it('cannot transfer if rate is too old', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); convRequest.maxRateTimespan = '10'; await expect( batchConversionProxy.batchMultiERC20ConversionPayments([convRequest], [], feeAddress), ).to.be.revertedWith('aggregator rate is outdated'); }); it('Not enough allowance', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); // reduce fromSigner± allowance await fauERC20.approve( batchConversionProxy.address, @@ -789,7 +789,7 @@ describe('contract: BatchConversionPayments', async () => { ).to.be.revertedWith('Insufficient allowance for batch to pay'); }); it('Not enough funds even if partially enough funds', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); // fromSigner transfer enough token to pay just 1 invoice to signer4 await fauERC20 .connect(fromSigner) @@ -846,7 +846,7 @@ describe('contract: BatchConversionPayments', async () => { const initialToETHBalance = await provider.getBalance(to); const initialFeeETHBalance = await provider.getBalance(feeAddress); const initialFromETHBalance = await provider.getBalance(await fromSigner.getAddress()); - const EurEthConvRequest = Utils.deepCopy(ethConvRequest); + const EurEthConvRequest = deepCopy(ethConvRequest); EurEthConvRequest.path = [EUR_hash, USD_hash, ETH_hash]; tx = await batchConversionProxy.batchNativeConversionPayments( @@ -875,7 +875,7 @@ describe('contract: BatchConversionPayments', async () => { describe('batchNativeConversionPayments errors', () => { it('cannot transfer with invalid path', async () => { - const wrongConvRequest = Utils.deepCopy(ethConvRequest); + const wrongConvRequest = deepCopy(ethConvRequest); wrongConvRequest.path = [USD_hash, EUR_hash, ETH_hash]; await expect( batchConversionProxy.batchNativeConversionPayments([wrongConvRequest], false, feeAddress, { @@ -896,7 +896,7 @@ describe('contract: BatchConversionPayments', async () => { ).to.be.revertedWith('paymentProxy transferExactEthWithReferenceAndFee failed'); }); it('cannot transfer if rate is too old', async () => { - const wrongConvRequest = Utils.deepCopy(ethConvRequest); + const wrongConvRequest = deepCopy(ethConvRequest); wrongConvRequest.maxRateTimespan = '1'; await expect( batchConversionProxy.batchNativeConversionPayments([wrongConvRequest], false, feeAddress, { diff --git a/packages/smart-contracts/test/contracts/BatchNoConversionEthPayments.test.ts b/packages/smart-contracts/test/contracts/BatchNoConversionEthPayments.test.ts index d08067258..93288dcaa 100644 --- a/packages/smart-contracts/test/contracts/BatchNoConversionEthPayments.test.ts +++ b/packages/smart-contracts/test/contracts/BatchNoConversionEthPayments.test.ts @@ -1,7 +1,7 @@ import { ethers, network } from 'hardhat'; import { BigNumber, Signer } from 'ethers'; import { expect } from 'chai'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { EthereumFeeProxy__factory, BatchNoConversionPayments__factory, @@ -89,11 +89,11 @@ describe('contract: batchNoConversionPayments: Ethereum', () => { beforeEthBalance1 = await provider.getBalance(payee1); beforeEthBalance2 = await provider.getBalance(payee2); - const copyEthRequestDetail1 = Utils.deepCopy(ethRequestDetail1); + const copyEthRequestDetail1 = deepCopy(ethRequestDetail1); copyEthRequestDetail1.requestAmount = '2000'; copyEthRequestDetail1.feeAmount = '100'; - const copyEthRequestDetail2 = Utils.deepCopy(ethRequestDetail2); + const copyEthRequestDetail2 = deepCopy(ethRequestDetail2); copyEthRequestDetail2.requestAmount = '3000'; copyEthRequestDetail2.feeAmount = '200'; await expect( @@ -149,7 +149,7 @@ describe('contract: batchNoConversionPayments: Ethereum', () => { const feeAmount = 1; const nbTxs = 10; // to compare gas optim, go to 100. - const copyEthRequestDetail = Utils.deepCopy(ethRequestDetail2); + const copyEthRequestDetail = deepCopy(ethRequestDetail2); copyEthRequestDetail.requestAmount = amount.toString(); copyEthRequestDetail.feeAmount = feeAmount.toString(); const totalAmount = BigNumber.from(((amount + feeAmount) * nbTxs).toString()); diff --git a/packages/smart-contracts/test/contracts/ChainlinkConversionPath.test.ts b/packages/smart-contracts/test/contracts/ChainlinkConversionPath.test.ts index f30fbb763..11d118173 100644 --- a/packages/smart-contracts/test/contracts/ChainlinkConversionPath.test.ts +++ b/packages/smart-contracts/test/contracts/ChainlinkConversionPath.test.ts @@ -32,7 +32,7 @@ describe('contract: ChainlinkConversionPath', () => { describe('admin tasks', async () => { it('can updateAggregator and updateAggregatorsList', async () => { let addressAggregator = await conversionPathInstance.allAggregators(address1, address2); - expect(addressAggregator).equal('0x0000000000000000000000000000000000000000'); + expect(addressAggregator).equal('0x3333333333333333333333333333333333333333'); await conversionPathInstance.updateAggregator(address1, address2, address3); @@ -41,7 +41,7 @@ describe('contract: ChainlinkConversionPath', () => { addressAggregator = await conversionPathInstance.allAggregators(address4, address5); expect(addressAggregator, 'addressAggregator must be 0x').equal( - '0x0000000000000000000000000000000000000000', + '0x6666666666666666666666666666666666666666', ); await conversionPathInstance.updateAggregatorsList( diff --git a/packages/thegraph-data-access/src/data-access.ts b/packages/thegraph-data-access/src/data-access.ts index 273b1ad9d..9078137d8 100644 --- a/packages/thegraph-data-access/src/data-access.ts +++ b/packages/thegraph-data-access/src/data-access.ts @@ -3,7 +3,7 @@ import TypedEmitter from 'typed-emitter'; import { BigNumber } from 'ethers'; -import Utils from '@requestnetwork/utils'; +import { getCurrentTimestampInSecond, retry, SimpleLogger } from '@requestnetwork/utils'; import { Block } from '@requestnetwork/data-access'; import { DataAccessTypes, LogTypes, StorageTypes } from '@requestnetwork/types'; @@ -179,7 +179,7 @@ export class TheGraphDataRead implements DataAccessTypes.IDataRead { transactions: [ { state: DataAccessTypes.TransactionState.PENDING, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), transaction, }, ], @@ -219,7 +219,7 @@ export class TheGraphDataWrite implements DataAccessTypes.IDataWrite { private readonly graphql: SubgraphClient, { network, logger, pendingStore }: TheGraphDataAccessBaseOptions, ) { - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.network = network; this.pendingStore = pendingStore; } @@ -269,7 +269,7 @@ export class TheGraphDataWrite implements DataAccessTypes.IDataWrite { }; storageResult.on('confirmed', () => { - Utils.retry( + retry( async () => { const response = await this.graphql.getTransactionsByHash(storageResult.id); if (response.transactions.length === 0) { diff --git a/packages/toolbox/src/chainlinkConversionPathTools.ts b/packages/toolbox/src/chainlinkConversionPathTools.ts index 585f9a0f6..b92a3ea41 100644 --- a/packages/toolbox/src/chainlinkConversionPathTools.ts +++ b/packages/toolbox/src/chainlinkConversionPathTools.ts @@ -8,7 +8,7 @@ import { import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import Bluebird from 'bluebird'; import chunk from 'lodash/chunk'; -import Utils from '@requestnetwork/utils'; +import { retry } from '@requestnetwork/utils'; export interface IOptions { network?: string; @@ -75,13 +75,10 @@ class ChainlinkConversionPathTools { chunks, (blocks) => { console.error(`Fetching logs from ${blocks[0]} to ${blocks[blocks.length - 1]}`); - return Utils.retry( - this.chainLinkConversionPath.queryFilter.bind(this.chainLinkConversionPath), - { - maxRetries: 3, - retryDelay: 2000, - }, - )( + return retry(this.chainLinkConversionPath.queryFilter.bind(this.chainLinkConversionPath), { + maxRetries: 3, + retryDelay: 2000, + })( this.chainLinkConversionPath.filters.AggregatorUpdated(), blocks[0], blocks[blocks.length - 1], diff --git a/packages/transaction-manager/src/clear-transaction.ts b/packages/transaction-manager/src/clear-transaction.ts index 52404a364..2a903bb07 100644 --- a/packages/transaction-manager/src/clear-transaction.ts +++ b/packages/transaction-manager/src/clear-transaction.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; import { TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Class representing a clear transaction @@ -27,7 +27,7 @@ export default class ClearTransaction implements TransactionTypes.ITransaction { * @returns a promise resolving the transaction data hash */ public async getHash(): Promise { - return MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(JSON.parse(this.data))); + return MultiFormat.serialize(normalizeKeccak256Hash(JSON.parse(this.data))); } /** diff --git a/packages/transaction-manager/src/encrypted-transaction.ts b/packages/transaction-manager/src/encrypted-transaction.ts index fcfc86eab..3733127ab 100644 --- a/packages/transaction-manager/src/encrypted-transaction.ts +++ b/packages/transaction-manager/src/encrypted-transaction.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; import { EncryptionTypes, TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { decrypt, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Class representing an encrypted transaction @@ -40,7 +40,7 @@ export default class EncryptedTransaction implements TransactionTypes.ITransacti if (this.data === '') { try { const encryptedData = MultiFormat.deserialize(this.persistedData); - this.data = await Utils.encryption.decrypt(encryptedData, this.channelKey); + this.data = await decrypt(encryptedData, this.channelKey); } catch { throw new Error('Impossible to decrypt the transaction'); } @@ -57,7 +57,7 @@ export default class EncryptedTransaction implements TransactionTypes.ITransacti if (this.dataHashSerialized === '') { const data = await this.getData(); try { - const dataHash = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data)); + const dataHash = normalizeKeccak256Hash(JSON.parse(data)); this.dataHashSerialized = MultiFormat.serialize(dataHash); } catch (e) { throw new Error('Impossible to JSON parse the decrypted transaction data'); diff --git a/packages/transaction-manager/src/transaction-manager.ts b/packages/transaction-manager/src/transaction-manager.ts index 427c818c8..d28511105 100644 --- a/packages/transaction-manager/src/transaction-manager.ts +++ b/packages/transaction-manager/src/transaction-manager.ts @@ -5,7 +5,7 @@ import { EncryptionTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; import { EventEmitter } from 'events'; @@ -47,9 +47,7 @@ export default class TransactionManager implements TransactionTypes.ITransaction let channelEncryptionMethod: string | undefined; // compute hash to add it to the topics - const hash = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(JSON.parse(transactionData)), - ); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(JSON.parse(transactionData))); // Need to create a new channel (only the first transaction can have the hash equals to the channel id) if (channelId === hash) { diff --git a/packages/transaction-manager/src/transactions-factory.ts b/packages/transaction-manager/src/transactions-factory.ts index 658ac3b35..9a639d078 100644 --- a/packages/transaction-manager/src/transactions-factory.ts +++ b/packages/transaction-manager/src/transactions-factory.ts @@ -1,6 +1,10 @@ import MultiFormat from '@requestnetwork/multi-format'; import { EncryptionTypes, TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { + encrypt, + generate32BufferKey, + getIdentityFromEncryptionParams, +} from '@requestnetwork/utils'; /** * Class to create transactions (clear and encrypted) @@ -39,10 +43,10 @@ export default class TransactionsFactory { const encryptionMethod = `${EncryptionTypes.METHOD.ECIES}-${EncryptionTypes.METHOD.AES256_GCM}`; // Generate a key for the AES encryption - const symmetricKey: string = await Utils.crypto.generate32BufferKey(); + const symmetricKey: string = await generate32BufferKey(); // Encrypt the data with the key and the AES256-GCM algorithm - const encryptedData: EncryptionTypes.IEncryptedData = await Utils.encryption.encrypt(data, { + const encryptedData: EncryptionTypes.IEncryptedData = await encrypt(data, { key: symmetricKey, method: EncryptionTypes.METHOD.AES256_GCM, }); @@ -71,12 +75,11 @@ export default class TransactionsFactory { encryptedKey: EncryptionTypes.IEncryptedData; multiFormattedIdentity: string; }> => { - const encryptedKey: EncryptionTypes.IEncryptedData = await Utils.encryption.encrypt( + const encryptedKey: EncryptionTypes.IEncryptedData = await encrypt( symmetricKey, encryptionParam, ); - const identityEncryption = - Utils.encryption.getIdentityFromEncryptionParams(encryptionParam); + const identityEncryption = getIdentityFromEncryptionParams(encryptionParam); const multiFormattedIdentity: string = MultiFormat.serialize(identityEncryption); return { encryptedKey, multiFormattedIdentity }; @@ -123,10 +126,7 @@ export default class TransactionsFactory { } // Encrypt the data with the key and the AES256-GCM algorithm - const encryptedData: EncryptionTypes.IEncryptedData = await Utils.encryption.encrypt( - data, - channelKey, - ); + const encryptedData: EncryptionTypes.IEncryptedData = await encrypt(data, channelKey); try { JSON.parse(data); diff --git a/packages/transaction-manager/test/index.test.ts b/packages/transaction-manager/test/index.test.ts index 0aae90e5d..979aa9ddb 100644 --- a/packages/transaction-manager/test/index.test.ts +++ b/packages/transaction-manager/test/index.test.ts @@ -1,5 +1,5 @@ import MultiFormat from '@requestnetwork/multi-format'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; import { EventEmitter } from 'events'; @@ -27,9 +27,9 @@ const tx2: DataAccessTypes.ITimestampedTransaction = { transaction: { data: data2 }, }; -const dataHash = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data)); +const dataHash = normalizeKeccak256Hash(JSON.parse(data)); const channelId = MultiFormat.serialize(dataHash); -const dataHash2 = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data2)); +const dataHash2 = normalizeKeccak256Hash(JSON.parse(data2)); const channelId2 = MultiFormat.serialize(dataHash2); const fakeMetaDataAccessPersistReturn: DataAccessTypes.IReturnPersistTransaction = Object.assign( diff --git a/packages/transaction-manager/test/unit/channel-parser.test.ts b/packages/transaction-manager/test/unit/channel-parser.test.ts index 4441cc7ce..6ad4b4cfa 100644 --- a/packages/transaction-manager/test/unit/channel-parser.test.ts +++ b/packages/transaction-manager/test/unit/channel-parser.test.ts @@ -1,9 +1,9 @@ import MultiFormat from '@requestnetwork/multi-format'; import { TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import ChannelParser from '../../src/channel-parser'; import TransactionsFactory from '../../src/transactions-factory'; import * as TestData from './utils/test-data'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; let channelParser: ChannelParser; @@ -21,9 +21,9 @@ const tx2: TransactionTypes.ITimestampedTransaction = { transaction: { data: data2 }, }; -const dataHash = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data)); +const dataHash = normalizeKeccak256Hash(JSON.parse(data)); const channelId = MultiFormat.serialize(dataHash); -const dataHash2 = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data2)); +const dataHash2 = normalizeKeccak256Hash(JSON.parse(data2)); const channelId2 = MultiFormat.serialize(dataHash2); /* eslint-disable @typescript-eslint/no-unused-expressions */ diff --git a/packages/transaction-manager/test/unit/clear-transaction.test.ts b/packages/transaction-manager/test/unit/clear-transaction.test.ts index e34c119d1..52b1aaf7e 100644 --- a/packages/transaction-manager/test/unit/clear-transaction.test.ts +++ b/packages/transaction-manager/test/unit/clear-transaction.test.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; -import Utils from '@requestnetwork/utils'; import ClearTransaction from '../../src/clear-transaction'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; const data = '{ "what": "ever", "it": "is,", "this": "must", "work": true }'; @@ -21,7 +21,7 @@ describe('clear-transaction', () => { // 'hash not right' expect(await tx.getHash()).toEqual( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(JSON.parse(data))), + MultiFormat.serialize(normalizeKeccak256Hash(JSON.parse(data))), ); }); }); diff --git a/packages/transaction-manager/test/unit/encryption-transaction.test.ts b/packages/transaction-manager/test/unit/encryption-transaction.test.ts index 156119639..c42d65ded 100644 --- a/packages/transaction-manager/test/unit/encryption-transaction.test.ts +++ b/packages/transaction-manager/test/unit/encryption-transaction.test.ts @@ -1,11 +1,11 @@ import MultiFormat from '@requestnetwork/multi-format'; import { EncryptionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import EncryptedTransaction from '../../src/encrypted-transaction'; +import { encrypt, normalizeKeccak256Hash } from '@requestnetwork/utils'; const data = '{ "what": "ever", "it": "is,", "this": "must", "work": true }'; -const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(JSON.parse(data))); +const hash = MultiFormat.serialize(normalizeKeccak256Hash(JSON.parse(data))); const channelKey = { key: 'XYVH7kMWMAy/if+IZ0e7EXMbPVptHd22Xmpr9ktmjRo=', method: EncryptionTypes.METHOD.AES256_CBC, @@ -35,7 +35,7 @@ describe('encryption-transaction', () => { describe('getError', () => { it('can get error of a transaction not parsable', async () => { const encryptedDataNotParsable = MultiFormat.serialize( - await Utils.encryption.encrypt('Not parsable', channelKey), + await encrypt('Not parsable', channelKey), ); const tx = new EncryptedTransaction(encryptedDataNotParsable, channelKey); diff --git a/packages/transaction-manager/test/unit/utils/test-data.ts b/packages/transaction-manager/test/unit/utils/test-data.ts index 821e7de43..8f80914b4 100644 --- a/packages/transaction-manager/test/unit/utils/test-data.ts +++ b/packages/transaction-manager/test/unit/utils/test-data.ts @@ -1,5 +1,5 @@ import { DecryptionProviderTypes, EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { decrypt } from '@requestnetwork/utils'; export const idRaw1 = { address: '0xaf083f77f1ffd54218d91491afd06c9296eac3ce', @@ -65,11 +65,11 @@ export const fakeDecryptionProvider: DecryptionProviderTypes.IDecryptionProvider ): Promise => { switch (identity.value.toLowerCase()) { case idRaw1.address: - return Utils.encryption.decrypt(data, idRaw1.decryptionParams); + return decrypt(data, idRaw1.decryptionParams); case idRaw2.address: - return Utils.encryption.decrypt(data, idRaw2.decryptionParams); + return decrypt(data, idRaw2.decryptionParams); case idRaw3.address: - return Utils.encryption.decrypt(data, idRaw3.decryptionParams); + return decrypt(data, idRaw3.decryptionParams); default: throw new Error('Identity not registered'); } diff --git a/packages/usage-examples/src/mock/mock-storage.ts b/packages/usage-examples/src/mock/mock-storage.ts index 54dfd9103..db4166116 100644 --- a/packages/usage-examples/src/mock/mock-storage.ts +++ b/packages/usage-examples/src/mock/mock-storage.ts @@ -1,7 +1,7 @@ import MultiFormat from '@requestnetwork/multi-format'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { EventEmitter } from 'events'; +import { getCurrentTimestampInSecond, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Storage layer implemented with in-memory hashmap, to be used for testing. @@ -23,9 +23,9 @@ export default class MockStorage implements StorageTypes.IStorage { if (!content) { throw Error('Error: no content provided'); } - const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(content)); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(content)); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); this.data[hash] = { content, @@ -84,7 +84,7 @@ export default class MockStorage implements StorageTypes.IStorage { }, })); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); return { entries, diff --git a/packages/utils/README.md b/packages/utils/README.md index 0198b2855..c5e07b8bd 100644 --- a/packages/utils/README.md +++ b/packages/utils/README.md @@ -4,16 +4,16 @@ It is a collection of tools shared between the @requestnetwork packages. - Elliptic curve crypto and signature - - crypto.normalizeKeccak256Hash() - - crypto.ecUtils.getAddressFromPrivateKey() - - crypto.ecUtils.recover() - - crypto.ecUtils.sign() - - signature.getIdentityFromSignatureParams() - - signature.recover() - - signature.sign() + - normalizeKeccak256Hash() + - EcUtils.getAddressFromPrivateKey() + - EcUtils.recover() + - EcUtils.sign() + - getIdentityFromSignatureParams() + - recover() + - sign() - Identity - - identity.areEqual() - - identity.normalizeIdentityValue() + - areEqual() + - normalizeIdentityValue() - isString - Miscellaneous - deepCopy() @@ -30,9 +30,9 @@ npm install @requestnetwork/utils ## Usage ```javascript -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; -const hash = Utils.crypto.normalizeKeccak256Hash({ exampleData: true }); +const hash = normalizeKeccak256Hash({ exampleData: true }); ``` ## Contributing diff --git a/packages/utils/test/crypto.test.ts b/packages/utils/test/crypto.test.ts index add011527..4647b33e2 100644 --- a/packages/utils/test/crypto.test.ts +++ b/packages/utils/test/crypto.test.ts @@ -8,7 +8,7 @@ import { } from '../src'; /* eslint-disable @typescript-eslint/no-unused-expressions */ -describe('Utils.crypto', () => { +describe('Utils/crypto', () => { it('can normalizeKeccak256Hash', () => { const arbitraryObject = { param1: 'valC', diff --git a/packages/utils/test/crypto/crypto-wrapper.test.ts b/packages/utils/test/crypto/crypto-wrapper.test.ts index 4b1cb647a..05ea73cfa 100644 --- a/packages/utils/test/crypto/crypto-wrapper.test.ts +++ b/packages/utils/test/crypto/crypto-wrapper.test.ts @@ -4,7 +4,7 @@ const anyData = 'this is any data!'; const arbitraryKey = '12345678901234567890123456789012'; /* eslint-disable @typescript-eslint/no-unused-expressions */ -describe('Utils.cryptoWrapper', () => { +describe('Utils/cryptoWrapper', () => { describe('random32Bytes', () => { it('can create a 32 bytes buffer', async () => { const randomBytes = await CryptoWrapper.random32Bytes(); diff --git a/packages/web3-signature/src/web3-signature-provider.ts b/packages/web3-signature/src/web3-signature-provider.ts index 64949eddc..00d3d5495 100644 --- a/packages/web3-signature/src/web3-signature-provider.ts +++ b/packages/web3-signature/src/web3-signature-provider.ts @@ -1,6 +1,6 @@ import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { areEqual, normalize, recover } from '@requestnetwork/utils'; import { providers } from 'ethers'; @@ -41,7 +41,7 @@ export default class Web3SignatureProvider implements SignatureProviderTypes.ISi throw Error(`Identity type not supported ${signer.type}`); } - const normalizedData = Utils.crypto.normalize(data); + const normalizedData = normalize(data); const signerEthers = this.web3Provider.getSigner(signer.value); let signatureValue; @@ -82,7 +82,7 @@ export default class Web3SignatureProvider implements SignatureProviderTypes.ISi value, }, }; - if (Utils.identity.areEqual(Utils.signature.recover(signedData), signer)) { + if (areEqual(recover(signedData), signer)) { return signedData; } return null; diff --git a/packages/web3-signature/test/web3-signature-provider.test.ts b/packages/web3-signature/test/web3-signature-provider.test.ts index e34f38f83..eae6173f2 100644 --- a/packages/web3-signature/test/web3-signature-provider.test.ts +++ b/packages/web3-signature/test/web3-signature-provider.test.ts @@ -2,7 +2,7 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import Web3SignatureProvider from '../src/web3-signature-provider'; -import Utils from '@requestnetwork/utils'; +import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; const id1Raw = { identity: { @@ -16,11 +16,8 @@ const id1Raw = { }; const data = { What: 'ever', the: 'data', are: true }; -const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; -const signatureValueExpected = Utils.crypto.EcUtils.sign( - id1Raw.signatureParams.privateKey, - hashData, -); +const hashData = normalizeKeccak256Hash(data).value; +const signatureValueExpected = EcUtils.sign(id1Raw.signatureParams.privateKey, hashData); const mockWeb3: any = { getSigner: jest.fn().mockImplementation(() => ({ From 693c05d1f7a9de3ad9f42a515069fe302e6eafca Mon Sep 17 00:00:00 2001 From: marcohefti Date: Sun, 25 Dec 2022 14:54:42 +0700 Subject: [PATCH 04/13] Apply changes to utils package to payment-processor/test/payment/any-to-near.test.ts --- .../payment-processor/test/payment/any-to-near.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/payment-processor/test/payment/any-to-near.test.ts b/packages/payment-processor/test/payment/any-to-near.test.ts index 8d43edb0d..323bce6a0 100644 --- a/packages/payment-processor/test/payment/any-to-near.test.ts +++ b/packages/payment-processor/test/payment/any-to-near.test.ts @@ -1,10 +1,10 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; import { PaymentReferenceCalculator } from '@requestnetwork/payment-detection'; -import * as Utils from '@requestnetwork/utils'; import { IConversionPaymentSettings, _getPaymentUrl } from '../../src/payment'; import * as nearUtils from '../../src/payment/utils-near'; import { payNearConversionRequest } from '../../src/payment/near-conversion'; +import { deepCopy } from '@requestnetwork/utils'; /* eslint-disable @typescript-eslint/no-unused-expressions */ /* eslint-disable @typescript-eslint/await-thenable */ @@ -101,7 +101,7 @@ describe('payNearWithConversionRequest', () => { state: () => Promise.resolve({ amount: 100 }), }), } as any; - let invalidRequest = Utils.default.deepCopy(request); + let invalidRequest = deepCopy(request); invalidRequest = { ...invalidRequest, extensions: { @@ -129,7 +129,7 @@ describe('payNearWithConversionRequest', () => { state: () => Promise.resolve({ amount: 100 }), }), } as any; - let invalidRequest = Utils.default.deepCopy(request); + let invalidRequest = deepCopy(request); invalidRequest = { ...invalidRequest, currencyInfo: { @@ -154,7 +154,7 @@ describe('payNearWithConversionRequest', () => { state: () => Promise.resolve({ amount: 100 }), }), } as any; - let invalidRequest = Utils.default.deepCopy(request); + let invalidRequest = deepCopy(request); invalidRequest = { ...invalidRequest, extensions: { From 83675c44567ffb192694b5f2b55096410123b4fb Mon Sep 17 00:00:00 2001 From: leoslr <50319677+leoslr@users.noreply.github.com> Date: Thu, 22 Dec 2022 15:26:22 +0100 Subject: [PATCH 05/13] feat: tombchain (#1024) --- packages/currency/src/native.ts | 6 ++++++ .../src/eth/multichainExplorerApiProvider.ts | 1 + packages/smart-contracts/hardhat.config.ts | 5 +++++ .../scripts-create2/contract-setup/adminTasks.ts | 8 +++++++- packages/smart-contracts/scripts-create2/xdeployer.ts | 5 ++++- .../src/lib/artifacts/ERC20FeeProxy/index.ts | 4 ++++ .../src/lib/artifacts/EthereumFeeProxy/index.ts | 4 ++++ .../src/lib/artifacts/RequestDeployer/index.ts | 4 ++++ packages/utils/src/providers.ts | 1 + 9 files changed, 36 insertions(+), 2 deletions(-) diff --git a/packages/currency/src/native.ts b/packages/currency/src/native.ts index 407d903d8..be240b306 100644 --- a/packages/currency/src/native.ts +++ b/packages/currency/src/native.ts @@ -111,6 +111,12 @@ export const nativeCurrencies: Record = { bsc: { chainId: 56, name: 'bsc' }, optimism: { chainId: 10, name: 'optimism' }, moonbeam: { chainId: 1284, name: 'moonbeam' }, + tombchain: { chainId: 6969, name: 'tombchain' }, }; /** diff --git a/packages/smart-contracts/hardhat.config.ts b/packages/smart-contracts/hardhat.config.ts index 2adcbf2bb..e02716a45 100644 --- a/packages/smart-contracts/hardhat.config.ts +++ b/packages/smart-contracts/hardhat.config.ts @@ -135,6 +135,11 @@ export default { chainId: 1284, accounts, }, + tombchain: { + url: url('tombchain'), + chainId: 6969, + accounts, + }, }, etherscan: { apiKey: { diff --git a/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts b/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts index 9cd54929f..f6445261e 100644 --- a/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts +++ b/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts @@ -248,7 +248,13 @@ export const getSignerAndGasFees = async ( provider = utils.getDefaultProvider(network); } const signer = new hre.ethers.Wallet(hre.config.xdeploy.signer).connect(provider); - const txOverrides = await utils.estimateGasFees({ provider }); + + let txOverrides; + try { + txOverrides = await utils.estimateGasFees({ provider }); + } catch (err) { + txOverrides = {}; + } return { signer, diff --git a/packages/smart-contracts/scripts-create2/xdeployer.ts b/packages/smart-contracts/scripts-create2/xdeployer.ts index 26a0392af..c8e8e0088 100644 --- a/packages/smart-contracts/scripts-create2/xdeployer.ts +++ b/packages/smart-contracts/scripts-create2/xdeployer.ts @@ -71,12 +71,15 @@ export const xdeploy = async ( let receipt = undefined; let deployed = false; let error = undefined; + let txOverrides: Overrides; - const txOverrides: Overrides = await utils.estimateGasFees({ provider }); try { + txOverrides = await utils.estimateGasFees({ provider }); const gasLimit = hre.config.xdeploy.gasLimit; txOverrides.gasLimit = gasLimit; } catch (e) { + // NOTE: On some networks utils.estimateGasFees do not work + txOverrides = {}; console.log('Cannot estimate gasLimit'); } diff --git a/packages/smart-contracts/src/lib/artifacts/ERC20FeeProxy/index.ts b/packages/smart-contracts/src/lib/artifacts/ERC20FeeProxy/index.ts index 29b7f5ed6..8ad42c2cc 100644 --- a/packages/smart-contracts/src/lib/artifacts/ERC20FeeProxy/index.ts +++ b/packages/smart-contracts/src/lib/artifacts/ERC20FeeProxy/index.ts @@ -131,6 +131,10 @@ export const erc20FeeProxyArtifact = new ContractArtifact( address: '0x399F5EE127ce7432E4921a61b8CF52b0af52cbfE', creationBlockNumber: 2415492, }, + tombchain: { + address: '0x399F5EE127ce7432E4921a61b8CF52b0af52cbfE', + creationBlockNumber: 2951048, + }, }, }, // Additional deployments of same versions, not worth upgrading the version number but worth using within next versions diff --git a/packages/smart-contracts/src/lib/artifacts/EthereumFeeProxy/index.ts b/packages/smart-contracts/src/lib/artifacts/EthereumFeeProxy/index.ts index 71e97cd5e..7dedc8ed9 100644 --- a/packages/smart-contracts/src/lib/artifacts/EthereumFeeProxy/index.ts +++ b/packages/smart-contracts/src/lib/artifacts/EthereumFeeProxy/index.ts @@ -118,6 +118,10 @@ export const ethereumFeeProxyArtifact = new ContractArtifact( address: '0xe11BF2fDA23bF0A98365e1A4c04A87C9339e8687', creationBlockNumber: 2415490, }, + tombchain: { + address: '0xe11BF2fDA23bF0A98365e1A4c04A87C9339e8687', + creationBlockNumber: 2951047, + }, }, }, }, diff --git a/packages/smart-contracts/src/lib/artifacts/RequestDeployer/index.ts b/packages/smart-contracts/src/lib/artifacts/RequestDeployer/index.ts index 07ee300a7..1269c6abe 100644 --- a/packages/smart-contracts/src/lib/artifacts/RequestDeployer/index.ts +++ b/packages/smart-contracts/src/lib/artifacts/RequestDeployer/index.ts @@ -69,6 +69,10 @@ export const requestDeployer = new ContractArtifact( address: '0xE99Ab70a5FAE59551544FA326fA048f7B95A24B2', creationBlockNumber: 2415122, }, + tombchain: { + address: '0xE99Ab70a5FAE59551544FA326fA048f7B95A24B2', + creationBlockNumber: 2950756, + }, }, }, }, diff --git a/packages/utils/src/providers.ts b/packages/utils/src/providers.ts index 0748e6c5f..93c2e73b6 100644 --- a/packages/utils/src/providers.ts +++ b/packages/utils/src/providers.ts @@ -43,6 +43,7 @@ const networkRpcs: Record = { avalanche: 'https://api.avax.network/ext/bc/C/rpc', optimism: 'https://mainnet.optimism.io', moonbeam: 'https://moonbeam.public.blastapi.io', + tombchain: 'https://rpc.tombchain.com/', }; /** From 171dbcc4480f019e2f2bff178f12e7cf79c662c2 Mon Sep 17 00:00:00 2001 From: leoslr <50319677+leoslr@users.noreply.github.com> Date: Thu, 22 Dec 2022 15:26:22 +0100 Subject: [PATCH 06/13] feat: tombchain (#1024) From acf302291691cb51dd176e60ea32e10cf18283eb Mon Sep 17 00:00:00 2001 From: marcohefti Date: Fri, 23 Dec 2022 00:27:45 +0700 Subject: [PATCH 07/13] running refactored files through prehook (#1015) --- packages/utils/src/amount.ts | 6 +--- packages/utils/src/encryption.ts | 6 +--- packages/utils/src/estimate-gas-fees.ts | 2 +- packages/utils/src/identity.ts | 7 +---- packages/utils/src/index.ts | 40 +++++-------------------- packages/utils/src/signature.ts | 16 ++-------- packages/utils/test/encryption.test.ts | 15 ++-------- packages/utils/test/utils.test.ts | 3 +- 8 files changed, 18 insertions(+), 77 deletions(-) diff --git a/packages/utils/src/amount.ts b/packages/utils/src/amount.ts index 424cf51e5..d54410e1b 100644 --- a/packages/utils/src/amount.ts +++ b/packages/utils/src/amount.ts @@ -6,11 +6,7 @@ import { BigNumber } from 'ethers'; /** * Function to manage amounts */ -export { - add, - isValid, - reduce, -}; +export { add, isValid, reduce }; const regexInteger = RegExp(/^[\d]+$/); diff --git a/packages/utils/src/encryption.ts b/packages/utils/src/encryption.ts index 1f2ffd054..195470d6f 100644 --- a/packages/utils/src/encryption.ts +++ b/packages/utils/src/encryption.ts @@ -4,11 +4,7 @@ import { CryptoWrapper, EcUtils } from './crypto'; /** * Functions to manage encryption */ -export { - decrypt, - encrypt, - getIdentityFromEncryptionParams, -}; +export { decrypt, encrypt, getIdentityFromEncryptionParams }; /** * Function to get the identity from the encryption parameters diff --git a/packages/utils/src/estimate-gas-fees.ts b/packages/utils/src/estimate-gas-fees.ts index ce8496290..068a6b367 100644 --- a/packages/utils/src/estimate-gas-fees.ts +++ b/packages/utils/src/estimate-gas-fees.ts @@ -43,4 +43,4 @@ async function estimateGasFees({ }; } -export { estimateGasFees }; +export { estimateGasFees }; diff --git a/packages/utils/src/identity.ts b/packages/utils/src/identity.ts index 31c8abd14..02b8cea97 100644 --- a/packages/utils/src/identity.ts +++ b/packages/utils/src/identity.ts @@ -8,12 +8,7 @@ const supportedIdentities: IdentityTypes.TYPE[] = [ /** * Module to manage Request Logic Identity */ -export { - areEqual, - hasError, - normalizeIdentityValue, - supportedIdentities, -}; +export { areEqual, hasError, normalizeIdentityValue, supportedIdentities }; /** * Checks if two identities are equals diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index a4f173775..d534ade67 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -2,20 +2,11 @@ * Collection of general purpose utility function */ -export { - add, - isValid, - reduce, -} from './amount'; +export { add, isValid, reduce } from './amount'; -export { - min, - max, -} from './bignumber'; +export { min, max } from './bignumber'; -export { - cachedThrottle, -} from './cached-throttle'; +export { cachedThrottle } from './cached-throttle'; export { CryptoWrapper, @@ -28,20 +19,11 @@ export { normalizeKeccak256Hash, } from './crypto'; -export { - decrypt, - encrypt, - getIdentityFromEncryptionParams, -} from './encryption'; +export { decrypt, encrypt, getIdentityFromEncryptionParams } from './encryption'; export { estimateGasFees } from './estimate-gas-fees'; -export { - areEqual, - hasError, - normalizeIdentityValue, - supportedIdentities, -} from './identity'; +export { areEqual, hasError, normalizeIdentityValue, supportedIdentities } from './identity'; export { setProviderFactory, @@ -53,15 +35,9 @@ export { export { retry } from './retry'; -export { - getIdentityFromSignatureParams, - recover, - sign, -} from './signature'; +export { getIdentityFromSignatureParams, recover, sign } from './signature'; -export { - SimpleLogger, -} from './simple-logger'; +export { SimpleLogger } from './simple-logger'; export { deepCopy, @@ -74,5 +50,3 @@ export { uniqueByProperty, notNull, } from './utils'; - - diff --git a/packages/utils/src/signature.ts b/packages/utils/src/signature.ts index 2ff396645..d1c807308 100644 --- a/packages/utils/src/signature.ts +++ b/packages/utils/src/signature.ts @@ -5,11 +5,7 @@ import { EcUtils, normalize, normalizeKeccak256Hash } from './crypto'; /** * Function to manage Request Logic Signature */ -export { - getIdentityFromSignatureParams, - recover, - sign, -}; +export { getIdentityFromSignatureParams, recover, sign }; // Use to localize the parameter V in an ECDSA signature in hex format const V_POSITION_FROM_END_IN_ECDSA_HEX = -2; @@ -49,19 +45,13 @@ function sign( ): SignatureTypes.ISignedData { let value: string; if (signatureParams.method === SignatureTypes.METHOD.ECDSA) { - value = EcUtils.sign( - signatureParams.privateKey, - normalizeKeccak256Hash(data).value, - ); + value = EcUtils.sign(signatureParams.privateKey, normalizeKeccak256Hash(data).value); return { data, signature: { method: signatureParams.method, value } }; } if (signatureParams.method === SignatureTypes.METHOD.ECDSA_ETHEREUM) { const normalizedData = normalize(data); - value = EcUtils.sign( - signatureParams.privateKey, - ethers.utils.hashMessage(normalizedData), - ); + value = EcUtils.sign(signatureParams.privateKey, ethers.utils.hashMessage(normalizedData)); return { data, signature: { method: signatureParams.method, value } }; } diff --git a/packages/utils/test/encryption.test.ts b/packages/utils/test/encryption.test.ts index 8ecd6ed6d..dd6bfaaa1 100644 --- a/packages/utils/test/encryption.test.ts +++ b/packages/utils/test/encryption.test.ts @@ -57,10 +57,7 @@ describe('Encryption', () => { describe('encrypt', () => { it('can encrypt with ECIES', async () => { - const encryptedData = await encrypt( - JSON.stringify(data), - otherIdRaw.encryptionParams, - ); + const encryptedData = await encrypt(JSON.stringify(data), otherIdRaw.encryptionParams); // 'encrypt() error' expect(encryptedData.value.length).toBe(258); // 'encrypt() error' @@ -72,10 +69,7 @@ describe('Encryption', () => { }); it('can encrypt with AES256-cbc', async () => { - const encryptedData = await encrypt( - JSON.stringify(data), - arbitraryAES256cbcEncryptionParams, - ); + const encryptedData = await encrypt(JSON.stringify(data), arbitraryAES256cbcEncryptionParams); // 'encrypt() error' expect(encryptedData.value.length).toBe(88); // 'encrypt() error' @@ -87,10 +81,7 @@ describe('Encryption', () => { }); it('can encrypt with AES256-gcm', async () => { - const encryptedData = await encrypt( - JSON.stringify(data), - arbitraryAES256gcmEncryptionParams, - ); + const encryptedData = await encrypt(JSON.stringify(data), arbitraryAES256gcmEncryptionParams); // 'encrypt() error' expect(encryptedData.value.length).toBe(100); // 'encrypt() error' diff --git a/packages/utils/test/utils.test.ts b/packages/utils/test/utils.test.ts index 9e500675c..6177dedb7 100644 --- a/packages/utils/test/utils.test.ts +++ b/packages/utils/test/utils.test.ts @@ -259,8 +259,7 @@ describe('Utils', () => { expect.assertions(3); - const promise = new Promise(() => { - }); + const promise = new Promise(() => {}); timeoutPromise(promise, 1000, errorMessage) .then(() => { fail('timeoutPromise should not be fulfilled'); From 997843407a985ed68300aa1a3606b36b8701c321 Mon Sep 17 00:00:00 2001 From: marcohefti Date: Sun, 25 Dec 2022 14:29:29 +0700 Subject: [PATCH 08/13] Apply changes to utils package to monorepo This commit applies the changes made to the utils package to the rest of the monorepo. The changes include replacing the default export with named exports and enforcing the no-default-export ESLint rule. NOTE: Not all changes could be tested (#1029, #1030, #1031) --- .../src/extensions/abstract-extension.ts | 5 +- .../payment-network/address-based.ts | 10 +- .../extensions/payment-network/declarative.ts | 41 +++--- .../payment-network/erc777/stream.ts | 6 +- .../payment-network/fee-reference-based.ts | 20 +-- .../test/advanced-logic.test.ts | 12 +- .../test/extensions/content-data.test.ts | 4 +- .../any-to-erc20-proxy.test.ts | 54 +++---- .../payment-network/any-to-eth-proxy.test.ts | 46 +++--- .../payment-network/any-to-near.test.ts | 4 +- .../bitcoin/mainnet-address-based.test.ts | 36 ++--- .../bitcoin/testnet-address-based.test.ts | 36 ++--- .../payment-network/declarative.test.ts | 50 +++---- .../erc20/address-based.test.ts | 37 ++--- .../erc20/fee-proxy-contract.test.ts | 32 ++--- .../erc20/proxy-contract.test.ts | 32 ++--- .../payment-network/erc777/stream.test.ts | 28 ++-- .../ethereum/fee-proxy-contract.test.ts | 32 ++--- .../ethereum/input-data.test.ts | 32 ++--- packages/currency/src/getHash.ts | 4 +- packages/data-access/src/block.ts | 4 +- packages/data-access/src/data-access.ts | 14 +- .../transaction-index/location-by-topic.ts | 4 +- .../2-request-client/6-signature-provider.md | 8 +- ...thereum-private-key-decryption-provider.ts | 8 +- ...um-private-key-decryption-provider.test.ts | 17 +-- ...ethereum-private-key-signature-provider.ts | 10 +- ...eum-private-key-signature-provider.test.ts | 7 +- .../ethereum-storage/src/ethereum-blocks.ts | 14 +- .../src/ethereum-storage-ethers.ts | 6 +- .../ethereum-storage/src/ethereum-storage.ts | 6 +- .../src/ethereum-tx-submitter.ts | 4 +- .../ethereum-storage/src/gas-fee-definer.ts | 4 +- .../ethereum-storage/src/gas-price-definer.ts | 4 +- .../etherchain-provider.ts | 4 +- .../gas-price-providers/etherscan-provider.ts | 4 +- .../ethgasstation-provider.ts | 4 +- packages/ethereum-storage/src/ipfs-manager.ts | 6 +- packages/ethereum-storage/src/ipfs-storage.ts | 4 +- .../src/smart-contract-manager.ts | 19 ++- .../ethereum-entries-to-ipfs-content.test.ts | 14 +- .../test/ethereum-storage.test.ts | 4 +- packages/integration-test/test/layers.test.ts | 7 +- .../integration-test/test/node-client.test.ts | 20 +-- .../src/any-to-any-detector.ts | 5 +- .../src/any/any-to-erc20-proxy.ts | 5 +- .../src/any/retrievers/any-to-any-proxy.ts | 4 +- .../btc/default-providers/blockchain-info.ts | 6 +- .../btc/default-providers/blockcypher-com.ts | 4 +- .../btc/default-providers/blockstream-info.ts | 6 +- .../src/btc/default-providers/chain-so.ts | 4 +- packages/payment-detection/src/declarative.ts | 4 +- .../src/erc20/address-based-info-retriever.ts | 4 +- .../payment-detection/src/erc20/currency.ts | 11 +- .../src/erc20/escrow-info-retriever.ts | 4 +- .../src/erc20/proxy-info-retriever.ts | 4 +- .../src/erc777/superfluid-retriever.ts | 4 +- .../src/eth/proxy-info-retriever.ts | 4 +- .../src/fee-reference-based-detector.ts | 4 +- packages/payment-detection/src/index.ts | 10 +- .../src/payment-network-factory.ts | 4 +- .../src/payment-reference-calculator.ts | 5 +- .../src/reference-based-detector.ts | 4 +- .../payment/any-to-erc20-batch-proxy.test.ts | 12 +- .../test/payment/any-to-erc20-proxy.test.ts | 7 +- .../test/payment/any-to-eth-proxy.test.ts | 8 +- .../test/payment/erc20-batch-proxy.test.ts | 10 +- .../test/payment/erc20-escrow-payment.test.ts | 22 +-- .../test/payment/erc20-fee-proxy.test.ts | 10 +- .../test/payment/erc20-proxy.test.ts | 10 +- .../test/payment/erc777-stream.test.ts | 10 +- .../test/payment/eth-batch-proxy.test.ts | 10 +- .../test/payment/eth-fee-proxy.test.ts | 10 +- .../test/payment/eth-input-data.test.ts | 8 +- .../test/payment/eth-proxy.test.ts | 8 +- .../test/payment/swap-any-to-erc20.test.ts | 6 +- .../test/payment/swap-erc20-fee-proxy.test.ts | 10 +- .../prototype-estimator/src/mock-storage.ts | 8 +- .../src/api/request-network.ts | 6 +- packages/request-client.js/src/api/request.ts | 7 +- packages/request-client.js/src/api/utils.ts | 4 +- .../request-client.js/src/http-data-access.ts | 6 +- .../src/http-metamask-data-access.ts | 4 +- .../request-client.js/src/mock-storage.ts | 12 +- .../test/api/request-network.test.ts | 8 +- .../test/data-test-real-btc.ts | 4 +- packages/request-client.js/test/data-test.ts | 28 ++-- .../test/declarative-payments.test.ts | 4 +- packages/request-client.js/test/index.test.ts | 16 +-- .../request-logic/specs/example/example.ts | 6 +- packages/request-logic/src/action.ts | 8 +- packages/request-logic/src/actions/accept.ts | 4 +- .../src/actions/addExtensionsData.ts | 4 +- packages/request-logic/src/actions/cancel.ts | 4 +- packages/request-logic/src/actions/create.ts | 34 +++-- .../src/actions/increaseExpectedAmount.ts | 13 +- .../src/actions/reduceExpectedAmount.ts | 10 +- packages/request-logic/src/request-logic.ts | 26 ++-- packages/request-logic/src/request.ts | 4 +- .../request-logic/src/requestLogicCore.ts | 4 +- packages/request-logic/src/role.ts | 6 +- packages/request-logic/test/index.test.ts | 136 ++++++++---------- .../request-logic/test/unit/action.test.ts | 10 +- .../test/unit/actions/accept.test.ts | 32 ++--- .../unit/actions/addExtensionsData.test.ts | 14 +- .../test/unit/actions/cancel.test.ts | 28 ++-- .../test/unit/actions/create.test.ts | 22 +-- .../actions/increaseExpectedAmount.test.ts | 28 ++-- .../unit/actions/reduceExpectedAmount.test.ts | 32 ++--- .../test/unit/requestLogicCore.test.ts | 18 ++- .../test/unit/utils/test-data-generator.ts | 8 +- packages/request-node/src/logger.ts | 4 +- .../src/request/persistTransaction.ts | 4 +- packages/request-node/src/requestNode.ts | 4 +- packages/request-node/src/requestNodeBase.ts | 4 +- packages/request-node/src/thegraph-node.ts | 4 +- .../test/getConfirmedTransaction.test.ts | 4 +- packages/smart-contracts/hardhat.config.ts | 5 +- .../scripts-create2/check-deployer.ts | 6 +- .../contract-setup/adminTasks.ts | 8 +- .../scripts-create2/xdeployer.ts | 8 +- .../contracts/BatchConversionPayments.test.ts | 18 +-- .../BatchNoConversionEthPayments.test.ts | 8 +- .../contracts/ChainlinkConversionPath.test.ts | 4 +- .../thegraph-data-access/src/data-access.ts | 8 +- .../src/chainlinkConversionPathTools.ts | 13 +- .../src/clear-transaction.ts | 4 +- .../src/encrypted-transaction.ts | 6 +- .../src/transaction-manager.ts | 6 +- .../src/transactions-factory.ts | 20 +-- .../transaction-manager/test/index.test.ts | 6 +- .../test/unit/channel-parser.test.ts | 6 +- .../test/unit/clear-transaction.test.ts | 4 +- .../test/unit/encryption-transaction.test.ts | 6 +- .../test/unit/utils/test-data.ts | 8 +- .../usage-examples/src/mock/mock-storage.ts | 8 +- packages/utils/README.md | 22 +-- packages/utils/test/crypto.test.ts | 2 +- .../utils/test/crypto/crypto-wrapper.test.ts | 2 +- .../src/web3-signature-provider.ts | 6 +- .../test/web3-signature-provider.test.ts | 9 +- 141 files changed, 783 insertions(+), 946 deletions(-) diff --git a/packages/advanced-logic/src/extensions/abstract-extension.ts b/packages/advanced-logic/src/extensions/abstract-extension.ts index b0c0f847b..1b545a454 100644 --- a/packages/advanced-logic/src/extensions/abstract-extension.ts +++ b/packages/advanced-logic/src/extensions/abstract-extension.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; /** * Abstract class to create extension @@ -53,8 +53,7 @@ export abstract class AbstractExtension implements Extensio ): RequestLogicTypes.IExtensionStates { this.validate(requestState, extensionAction); - const copiedExtensionState: RequestLogicTypes.IExtensionStates = - Utils.deepCopy(extensionsState); + const copiedExtensionState: RequestLogicTypes.IExtensionStates = deepCopy(extensionsState); if (extensionAction.action === ExtensionTypes.PnFeeReferenceBased.ACTION.CREATE) { if (requestState.extensions[extensionAction.id]) { diff --git a/packages/advanced-logic/src/extensions/payment-network/address-based.ts b/packages/advanced-logic/src/extensions/payment-network/address-based.ts index 15df7d9fa..2588f8a57 100644 --- a/packages/advanced-logic/src/extensions/payment-network/address-based.ts +++ b/packages/advanced-logic/src/extensions/payment-network/address-based.ts @@ -1,6 +1,6 @@ import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { areEqual, deepCopy } from '@requestnetwork/utils'; import DeclarativePaymentNetwork from './declarative'; /** @@ -194,11 +194,11 @@ export default abstract class AddressBasedPaymentNetwork< if (!requestState.payee) { throw Error(`The request must have a payee`); } - if (!Utils.identity.areEqual(actionSigner, requestState.payee)) { + if (!areEqual(actionSigner, requestState.payee)) { throw Error(`The signer must be the payee`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // update payment address copiedExtensionState.values.paymentAddress = extensionAction.parameters.paymentAddress; @@ -241,11 +241,11 @@ export default abstract class AddressBasedPaymentNetwork< if (!requestState.payer) { throw Error(`The request must have a payer`); } - if (!Utils.identity.areEqual(actionSigner, requestState.payer)) { + if (!areEqual(actionSigner, requestState.payer)) { throw Error(`The signer must be the payer`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // update refund address copiedExtensionState.values.refundAddress = extensionAction.parameters.refundAddress; diff --git a/packages/advanced-logic/src/extensions/payment-network/declarative.ts b/packages/advanced-logic/src/extensions/payment-network/declarative.ts index 231a18bd7..114e79453 100644 --- a/packages/advanced-logic/src/extensions/payment-network/declarative.ts +++ b/packages/advanced-logic/src/extensions/payment-network/declarative.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { add, areEqual, deepCopy, isValid } from '@requestnetwork/utils'; import { AbstractExtension } from '../abstract-extension'; const CURRENT_VERSION = '0.1.0'; @@ -239,14 +239,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER); - if (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValid(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment sentPaymentAmount - copiedExtensionState.values.sentPaymentAmount = Utils.amount.add( + copiedExtensionState.values.sentPaymentAmount = add( copiedExtensionState.values.sentPaymentAmount, extensionAction.parameters.amount, ); @@ -285,14 +285,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE); - if (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValid(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment sentRefundAmount - copiedExtensionState.values.sentRefundAmount = Utils.amount.add( + copiedExtensionState.values.sentRefundAmount = add( copiedExtensionState.values.sentRefundAmount, extensionAction.parameters.amount, ); @@ -331,14 +331,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE); - if (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValid(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment receivedPaymentAmount - copiedExtensionState.values.receivedPaymentAmount = Utils.amount.add( + copiedExtensionState.values.receivedPaymentAmount = add( copiedExtensionState.values.receivedPaymentAmount, extensionAction.parameters.amount, ); @@ -377,14 +377,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER); - if (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValid(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment receivedRefundAmount - copiedExtensionState.values.receivedRefundAmount = Utils.amount.add( + copiedExtensionState.values.receivedRefundAmount = add( copiedExtensionState.values.receivedRefundAmount, extensionAction.parameters.amount, ); @@ -427,7 +427,7 @@ export default class DeclarativePaymentNetwork< } this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE); - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // assign paymentInfo copiedExtensionState.values.paymentInfo = extensionAction.parameters.paymentInfo; @@ -463,9 +463,9 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { let delegateStr: string; - if (Utils.identity.areEqual(actionSigner, requestState.payee)) { + if (areEqual(actionSigner, requestState.payee)) { delegateStr = 'payeeDelegate'; - } else if (Utils.identity.areEqual(actionSigner, requestState.payer)) { + } else if (areEqual(actionSigner, requestState.payer)) { delegateStr = 'payerDelegate'; } else { throw Error(`The signer must be the payee or the payer`); @@ -475,7 +475,7 @@ export default class DeclarativePaymentNetwork< throw Error(`The ${delegateStr} is already assigned`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // assign payeeDelegate or payerDelegate copiedExtensionState.values[delegateStr] = extensionAction.parameters.delegate; @@ -515,7 +515,7 @@ export default class DeclarativePaymentNetwork< } this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER); - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // assign refundInfo copiedExtensionState.values.refundInfo = extensionAction.parameters.refundInfo; @@ -566,10 +566,7 @@ export default class DeclarativePaymentNetwork< if (!requestRole) { throw Error(`The request must have a ${requestRoleStr}`); } - if ( - !Utils.identity.areEqual(actionSigner, requestRole) && - !Utils.identity.areEqual(actionSigner, requestRoleDelegate) - ) { + if (!areEqual(actionSigner, requestRole) && !areEqual(actionSigner, requestRoleDelegate)) { throw Error(`The signer must be the ${requestRoleStr} or the ${requestRoleStr}Delegate`); } } diff --git a/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts b/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts index e64f24787..2ceda2206 100644 --- a/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts +++ b/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts @@ -1,6 +1,6 @@ import { ExtensionTypes, RequestLogicTypes, TypesUtils } from '@requestnetwork/types'; import ReferenceBasedPaymentNetwork from '../reference-based'; -import Utils from '@requestnetwork/utils'; +import { isValid } from '@requestnetwork/utils'; const CURRENT_VERSION = '0.1.0'; /** @@ -92,7 +92,7 @@ export default class Erc777StreamPaymentNetwork< if ( !extensionAction.parameters.expectedStartDate || (extensionAction.parameters.expectedStartDate && - !Utils.amount.isValid(extensionAction.parameters.expectedStartDate)) + !isValid(extensionAction.parameters.expectedStartDate)) ) { throw Error('expectedStartDate is empty or invalid'); } @@ -100,7 +100,7 @@ export default class Erc777StreamPaymentNetwork< if ( !extensionAction.parameters.expectedFlowRate || (extensionAction.parameters.expectedFlowRate && - !Utils.amount.isValid(extensionAction.parameters.expectedFlowRate)) + !isValid(extensionAction.parameters.expectedFlowRate)) ) { throw Error('expectedFlowRate is empty or invalid'); } diff --git a/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts b/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts index 26ff07ef8..e4defca02 100644 --- a/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts +++ b/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts @@ -1,6 +1,6 @@ import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; import ReferenceBasedPaymentNetwork from './reference-based'; -import Utils from '@requestnetwork/utils'; +import { areEqual, deepCopy, isValid } from '@requestnetwork/utils'; /** * Core of the reference based with fee payment networks @@ -35,7 +35,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< throw Error('feeAddress is not a valid address'); } - if (creationParameters.feeAmount && !Utils.amount.isValid(creationParameters.feeAmount)) { + if (creationParameters.feeAmount && !isValid(creationParameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -65,7 +65,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< throw Error('feeAddress is not a valid address'); } - if (addFeeParameters.feeAmount && !Utils.amount.isValid(addFeeParameters.feeAmount)) { + if (addFeeParameters.feeAmount && !isValid(addFeeParameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -101,10 +101,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< ) { throw Error('feeAddress is not a valid address'); } - if ( - extensionAction.parameters.feeAmount && - !Utils.amount.isValid(extensionAction.parameters.feeAmount) - ) { + if (extensionAction.parameters.feeAmount && !isValid(extensionAction.parameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -160,10 +157,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< if (extensionState.values.feeAddress) { throw Error(`Fee address already given`); } - if ( - extensionAction.parameters.feeAmount && - !Utils.amount.isValid(extensionAction.parameters.feeAmount) - ) { + if (extensionAction.parameters.feeAmount && !isValid(extensionAction.parameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } if (extensionState.values.feeAmount) { @@ -172,11 +166,11 @@ export abstract class FeeReferenceBasedPaymentNetwork< if (!requestState.payee) { throw Error(`The request must have a payee`); } - if (!Utils.identity.areEqual(actionSigner, requestState.payee)) { + if (!areEqual(actionSigner, requestState.payee)) { throw Error(`The signer must be the payee`); } - const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); + const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // update fee address and amount copiedExtensionState.values.feeAddress = extensionAction.parameters.feeAddress; diff --git a/packages/advanced-logic/test/advanced-logic.test.ts b/packages/advanced-logic/test/advanced-logic.test.ts index 87bc868c7..53cba4d37 100644 --- a/packages/advanced-logic/test/advanced-logic.test.ts +++ b/packages/advanced-logic/test/advanced-logic.test.ts @@ -4,7 +4,7 @@ import * as DataBTCCreate from './utils/payment-network/bitcoin/generator-data-c import * as DataDeclarativeCreate from './utils/payment-network/any/generator-data-create'; import * as DataTestnetBTCCreate from './utils/payment-network/bitcoin/testnet-generator-data-create'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { AdvancedLogic } from '../src/index'; @@ -19,7 +19,7 @@ describe('advanced-logic.ts', () => { }); describe('applyActionToExtensions', () => { it('can applyActionToExtensions', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy(TestData.requestCreatedNoExtension); + const requestCreatedNoExtensionBefore = deepCopy(TestData.requestCreatedNoExtension); const previousState = {}; const newExtensionState = advancedLogic.applyActionToExtensions( @@ -39,9 +39,7 @@ describe('advanced-logic.ts', () => { }); it('can applyActionToExtensions with pn bitcoin address based', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy( - DataBTCCreate.requestStateNoExtensions, - ); + const requestCreatedNoExtensionBefore = deepCopy(DataBTCCreate.requestStateNoExtensions); const newExtensionState = advancedLogic.applyActionToExtensions( requestCreatedNoExtensionBefore.extensions, @@ -58,7 +56,7 @@ describe('advanced-logic.ts', () => { }); it('can applyActionToExtensions with pn testnet bitcoin address based', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy( + const requestCreatedNoExtensionBefore = deepCopy( DataTestnetBTCCreate.requestStateNoExtensions, ); @@ -79,7 +77,7 @@ describe('advanced-logic.ts', () => { }); it('can applyActionToExtensions with declarative payment network', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy( + const requestCreatedNoExtensionBefore = deepCopy( DataDeclarativeCreate.requestStateNoExtensions, ); diff --git a/packages/advanced-logic/test/extensions/content-data.test.ts b/packages/advanced-logic/test/extensions/content-data.test.ts index f832ef72e..a23d9629d 100644 --- a/packages/advanced-logic/test/extensions/content-data.test.ts +++ b/packages/advanced-logic/test/extensions/content-data.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import ContentData from '../../src/extensions/content-data'; @@ -11,7 +11,7 @@ const contentData = new ContentData(); describe('content-data', () => { describe('applyActionToExtension', () => { it('can applyActionToExtensions', () => { - const requestCreatedNoExtensionBefore = Utils.deepCopy(TestData.requestCreatedNoExtension); + const requestCreatedNoExtensionBefore = deepCopy(TestData.requestCreatedNoExtension); const previousState = {}; const newExtensionState = contentData.applyActionToExtension( previousState, diff --git a/packages/advanced-logic/test/extensions/payment-network/any-to-erc20-proxy.test.ts b/packages/advanced-logic/test/extensions/payment-network/any-to-erc20-proxy.test.ts index 6efd8bd62..7975ba1d6 100644 --- a/packages/advanced-logic/test/extensions/payment-network/any-to-erc20-proxy.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/any-to-erc20-proxy.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import AnyToErc20Proxy from '../../../src/extensions/payment-network/any-to-erc20-proxy'; @@ -171,7 +171,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -179,7 +179,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () value: 'ETH', }; - const action: ExtensionTypes.IAction = Utils.deepCopy( + const action: ExtensionTypes.IAction = deepCopy( DataConversionERC20FeeCreate.actionCreationFull, ); action.parameters.network = 'invalid network'; @@ -197,7 +197,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -205,7 +205,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () value: 'invalid value', }; - const action: ExtensionTypes.IAction = Utils.deepCopy( + const action: ExtensionTypes.IAction = deepCopy( DataConversionERC20FeeCreate.actionCreationFull, ); @@ -312,7 +312,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataConversionERC20FeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataConversionERC20FeeAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -327,7 +327,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataConversionERC20FeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataConversionERC20FeeAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -357,7 +357,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('can applyActionToExtensions of creation when address is checksumed', () => { - const request = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateNoExtensions); + const request = deepCopy(DataConversionERC20FeeCreate.requestStateNoExtensions); request.currency = { type: RequestLogicTypes.CURRENCY.ERC20, value: '0x4E15361FD6b4BB609Fa63C81A2be19d873717870', // FTM @@ -389,7 +389,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -411,9 +411,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionERC20FeeCreate.actionCreationFull, - ); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataConversionERC20FeeAddData.invalidAddress; // 'must throw' @@ -431,9 +429,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with no tokens accepted', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionERC20FeeCreate.actionCreationFull, - ); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeCreate.actionCreationFull); testnetPaymentAddress.parameters.acceptedTokens = []; // 'must throw' expect(() => { @@ -448,9 +444,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with token address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionERC20FeeCreate.actionCreationFull, - ); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeCreate.actionCreationFull); testnetPaymentAddress.parameters.acceptedTokens = ['invalid address']; // 'must throw' expect(() => { @@ -465,9 +459,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataConversionERC20FeeCreate.actionCreationFull, - ); + const testnetRefundAddress = deepCopy(DataConversionERC20FeeCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataConversionERC20FeeAddData.invalidAddress; // 'must throw' @@ -535,7 +527,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -550,7 +542,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { anyToErc20Proxy.applyActionToExtension( @@ -577,7 +569,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( + const testnetPaymentAddress = deepCopy( DataConversionERC20FeeAddData.actionAddPaymentAddress, ); testnetPaymentAddress.parameters.paymentAddress = @@ -625,7 +617,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -640,7 +632,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { anyToErc20Proxy.applyActionToExtension( @@ -667,7 +659,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( + const testnetPaymentAddress = deepCopy( DataConversionERC20FeeAddData.actionAddRefundAddress, ); testnetPaymentAddress.parameters.refundAddress = @@ -712,7 +704,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee without a payee', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; expect(() => { anyToErc20Proxy.applyActionToExtension( @@ -726,7 +718,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionERC20FeeCreate.requestStateCreatedEmpty); expect(() => { anyToErc20Proxy.applyActionToExtension( previousState.extensions, @@ -751,7 +743,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee with fee address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionERC20FeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAddress = DataConversionERC20FeeAddData.invalidAddress; expect(() => { anyToErc20Proxy.applyActionToExtension( @@ -765,7 +757,7 @@ describe('extensions/payment-network/erc20/any-to-erc20-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee with fee amount not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionERC20FeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataConversionERC20FeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAmount = 'invalid amount'; expect(() => { anyToErc20Proxy.applyActionToExtension( diff --git a/packages/advanced-logic/test/extensions/payment-network/any-to-eth-proxy.test.ts b/packages/advanced-logic/test/extensions/payment-network/any-to-eth-proxy.test.ts index 95329b82e..9c33c9d56 100644 --- a/packages/advanced-logic/test/extensions/payment-network/any-to-eth-proxy.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/any-to-eth-proxy.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import AnyToEthProxy from '../../../src/extensions/payment-network/any-to-eth-proxy'; @@ -112,7 +112,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with an invalid network/currency pair', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -120,7 +120,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () value: 'ETH', }; - const action: ExtensionTypes.IAction = Utils.deepCopy( + const action: ExtensionTypes.IAction = deepCopy( DataConversionETHFeeCreate.actionCreationFull, ); action.parameters.network = 'invalid network'; @@ -140,7 +140,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -149,7 +149,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () network: 'invalid network', }; - const action: ExtensionTypes.IAction = Utils.deepCopy( + const action: ExtensionTypes.IAction = deepCopy( DataConversionETHFeeCreate.actionCreationFull, ); @@ -256,7 +256,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -271,7 +271,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -301,7 +301,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('can applyActionToExtensions of creation when address is checksumed', () => { - const request = Utils.deepCopy(DataConversionETHFeeCreate.requestStateNoExtensions); + const request = deepCopy(DataConversionETHFeeCreate.requestStateNoExtensions); request.currency = { type: RequestLogicTypes.CURRENCY.ERC20, @@ -334,7 +334,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation on a non supported currency', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -355,7 +355,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionETHFeeCreate.actionCreationFull); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataConversionETHFeeAddData.invalidAddress; // 'must throw' @@ -373,7 +373,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy(DataConversionETHFeeCreate.actionCreationFull); + const testnetRefundAddress = deepCopy(DataConversionETHFeeCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataConversionETHFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -442,7 +442,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -457,7 +457,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { anyToEthProxy.applyActionToExtension( @@ -484,9 +484,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionETHFeeAddData.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeAddData.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataConversionETHFeeAddData.invalidAddress; // 'must throw' @@ -534,7 +532,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -549,7 +547,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { anyToEthProxy.applyActionToExtension( @@ -576,9 +574,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataConversionETHFeeAddData.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeAddData.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataConversionETHFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -622,7 +618,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee without a payee', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; expect(() => { anyToEthProxy.applyActionToExtension( @@ -636,7 +632,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataConversionETHFeeCreate.requestStateCreatedEmpty); expect(() => { anyToEthProxy.applyActionToExtension( previousState.extensions, @@ -661,7 +657,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee with fee address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionETHFeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAddress = DataConversionETHFeeAddData.invalidAddress; expect(() => { anyToEthProxy.applyActionToExtension( @@ -675,7 +671,7 @@ describe('extensions/payment-network/ethereum/any-to-eth-fee-proxy-contract', () }); it('cannot applyActionToExtensions of addFee with fee amount not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataConversionETHFeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataConversionETHFeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAmount = 'invalid amount'; expect(() => { anyToEthProxy.applyActionToExtension( diff --git a/packages/advanced-logic/test/extensions/payment-network/any-to-near.test.ts b/packages/advanced-logic/test/extensions/payment-network/any-to-near.test.ts index c9eaef8ad..b9e099d1c 100644 --- a/packages/advanced-logic/test/extensions/payment-network/any-to-near.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/any-to-near.test.ts @@ -12,7 +12,7 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; import AnyToNearPaymentNetwork from '../../../src/extensions/payment-network/near/any-to-near'; import AnyToNativeTokenPaymentNetwork from '../../../src/extensions/payment-network/any-to-native'; import { CurrencyManager } from '@requestnetwork/currency'; -import utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import AnyToNearTestnetPaymentNetwork from '../../../src/extensions/payment-network/near/any-to-near-testnet'; const salt = arbitrarySalt; @@ -272,7 +272,7 @@ describe('extensions/payment-network/any-to-native-token', () => { ...requestStateNoExtensions, currency: validCurrency, }; - creationAction = utils.deepCopy(actionCreationWithAnyToNativeTokenPayment); + creationAction = deepCopy(actionCreationWithAnyToNativeTokenPayment); }); describe('applyActionToExtension/create action', () => { it('works with valid parameters', () => { diff --git a/packages/advanced-logic/test/extensions/payment-network/bitcoin/mainnet-address-based.test.ts b/packages/advanced-logic/test/extensions/payment-network/bitcoin/mainnet-address-based.test.ts index 5e62bb790..167162523 100644 --- a/packages/advanced-logic/test/extensions/payment-network/bitcoin/mainnet-address-based.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/bitcoin/mainnet-address-based.test.ts @@ -1,7 +1,5 @@ import MainnetBitcoinAddressBasedPN from '../../../../src/extensions/payment-network/bitcoin/mainnet-address-based'; - -import Utils from '@requestnetwork/utils'; - +import { deepCopy } from '@requestnetwork/utils'; import * as DataBTCAddPaymentAddress from '../../../utils/payment-network/bitcoin/generator-data-add-payment-address'; import * as DataBTCCreate from '../../../utils/payment-network/bitcoin/generator-data-create'; import * as TestData from '../../../utils/test-data-generator'; @@ -25,7 +23,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( mainnetBitcoinAddressBasedPN.createCreationAction({ paymentAddress: DataBTCCreate.paymentBTCAddress, }), @@ -36,7 +34,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( mainnetBitcoinAddressBasedPN.createCreationAction({ refundAddress: DataBTCCreate.refundBTCAddress, }), @@ -46,7 +44,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { it('can createCreationAction with nothing', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' - expect(Utils.deepCopy(mainnetBitcoinAddressBasedPN.createCreationAction({}))).toEqual( + expect(deepCopy(mainnetBitcoinAddressBasedPN.createCreationAction({}))).toEqual( DataBTCCreate.actionCreationEmpty, ); }); @@ -119,7 +117,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -173,9 +171,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCCreate.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataBTCCreate.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataBTCAddPaymentAddress.paymentTestnetBTCAddress; // 'must throw' @@ -193,9 +189,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataBTCCreate.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataBTCCreate.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataBTCAddPaymentAddress.refundTestnetBTCAddress; // 'must throw' @@ -262,7 +256,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -276,7 +270,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { mainnetBitcoinAddressBasedPN.applyActionToExtension( @@ -301,9 +295,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCAddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataBTCAddPaymentAddress.paymentTestnetBTCAddress; // 'must throw' @@ -347,7 +339,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -361,7 +353,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { mainnetBitcoinAddressBasedPN.applyActionToExtension( @@ -386,9 +378,7 @@ describe('extensions/payment-network/bitcoin/mainnet-address-based', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCAddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataBTCAddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataBTCAddPaymentAddress.paymentTestnetBTCAddress; // 'must throw' diff --git a/packages/advanced-logic/test/extensions/payment-network/bitcoin/testnet-address-based.test.ts b/packages/advanced-logic/test/extensions/payment-network/bitcoin/testnet-address-based.test.ts index 3b193bcc9..7133bad54 100644 --- a/packages/advanced-logic/test/extensions/payment-network/bitcoin/testnet-address-based.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/bitcoin/testnet-address-based.test.ts @@ -1,7 +1,5 @@ import TestnetBitcoinAddressBasedPN from '../../../../src/extensions/payment-network/bitcoin/testnet-address-based'; - -import Utils from '@requestnetwork/utils'; - +import { deepCopy } from '@requestnetwork/utils'; import * as DataBTCAddPaymentAddress from '../../../utils/payment-network/bitcoin/testnet-generator-data-add-payment-address'; import * as DataBTCCreate from '../../../utils/payment-network/bitcoin/testnet-generator-data-create'; import * as TestData from '../../../utils/test-data-generator'; @@ -25,7 +23,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( testnetBitcoinAddressBasedPN.createCreationAction({ paymentAddress: DataBTCCreate.paymentTestnetBTCAddress, }), @@ -36,7 +34,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( testnetBitcoinAddressBasedPN.createCreationAction({ refundAddress: DataBTCCreate.refundTestnetBTCAddress, }), @@ -46,7 +44,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { it('can createCreationAction with nothing', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' - expect(Utils.deepCopy(testnetBitcoinAddressBasedPN.createCreationAction({}))).toEqual( + expect(deepCopy(testnetBitcoinAddressBasedPN.createCreationAction({}))).toEqual( DataBTCCreate.actionCreationEmpty, ); }); @@ -111,7 +109,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -165,9 +163,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCCreate.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataBTCCreate.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataBTCAddPaymentAddress.paymentBTCAddress; // 'must throw' @@ -185,9 +181,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataBTCCreate.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataBTCCreate.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataBTCAddPaymentAddress.refundBTCAddress; // 'must throw' expect(() => { @@ -253,7 +247,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -267,7 +261,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { testnetBitcoinAddressBasedPN.applyActionToExtension( @@ -292,9 +286,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCAddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataBTCAddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataBTCAddPaymentAddress.paymentBTCAddress; // 'must throw' @@ -338,7 +330,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -352,7 +344,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataBTCCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataBTCCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { testnetBitcoinAddressBasedPN.applyActionToExtension( @@ -377,9 +369,7 @@ describe('extensions/payment-network/bitcoin/testnet-address-based', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataBTCAddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataBTCAddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataBTCAddPaymentAddress.refundBTCAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/declarative.test.ts b/packages/advanced-logic/test/extensions/payment-network/declarative.test.ts index 6628872c8..e500322d4 100644 --- a/packages/advanced-logic/test/extensions/payment-network/declarative.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/declarative.test.ts @@ -1,6 +1,6 @@ import PnAnyDeclarative from '../../../src/extensions/payment-network/declarative'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { ExtensionTypes } from '@requestnetwork/types'; import * as TestDataDeclarative from '../../utils/payment-network/any/generator-data-create'; @@ -26,7 +26,7 @@ describe('extensions/payment-network/any/declarative', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( pnAnyDeclarative.createCreationAction({ paymentInfo: TestDataDeclarative.paymentInfo, }), @@ -37,7 +37,7 @@ describe('extensions/payment-network/any/declarative', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( pnAnyDeclarative.createCreationAction({ refundInfo: TestDataDeclarative.refundInfo, }), @@ -49,7 +49,7 @@ describe('extensions/payment-network/any/declarative', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( pnAnyDeclarative.createCreationAction({ payeeDelegate: TestDataDeclarative.payeeDelegate, }), @@ -150,7 +150,7 @@ describe('extensions/payment-network/any/declarative', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(TestDataDeclarative.actionCreationEmpty); + const unknownAction = deepCopy(TestDataDeclarative.actionCreationEmpty); unknownAction.action = 'unknown action' as any; expect(() => { @@ -226,7 +226,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStatePaymentInstructionAdded); }); it('can applyActionToExtensions of addPaymentInstruction from payeeDelegate', () => { - const expectedFromPayeeDelegate = Utils.deepCopy( + const expectedFromPayeeDelegate = deepCopy( TestDataDeclarative.extensionStatePaymentInstructionAdded, ); expectedFromPayeeDelegate[ @@ -255,7 +255,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentInstruction without a payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -272,7 +272,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentInstruction signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -310,7 +310,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStateRefundInstructionAdded); }); it('can applyActionToExtensions of addRefundInstruction from payerDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy( + const expectedFromThirdParty = deepCopy( TestDataDeclarative.extensionStateRefundInstructionAdded, ); expectedFromThirdParty[ @@ -345,7 +345,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundInstruction without a payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -362,7 +362,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundInstruction signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -400,9 +400,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStateDeclaredSent); }); it('can applyActionToExtensions of declareSentPayment from payerDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy( - TestDataDeclarative.extensionStateDeclaredSent, - ); + const expectedFromThirdParty = deepCopy(TestDataDeclarative.extensionStateDeclaredSent); expectedFromThirdParty[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payerDelegate; @@ -432,7 +430,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareSentPayment without a payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -449,7 +447,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of declareSentPayment signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -489,7 +487,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.declarativeExtStateRefundDeclared); }); it('can applyActionToExtensions of declareReceivedRefund from payerDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy( + const expectedFromThirdParty = deepCopy( TestDataDeclarative.declarativeExtStateRefundDeclared, ); expectedFromThirdParty[ @@ -521,7 +519,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareReceivedRefund without a payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -538,7 +536,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of declareReceivedRefund signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -578,7 +576,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStateSentRefund); }); it('can applyActionToExtensions of declareSentRefund from payeeDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy(TestDataDeclarative.extensionStateSentRefund); + const expectedFromThirdParty = deepCopy(TestDataDeclarative.extensionStateSentRefund); expectedFromThirdParty[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payeeDelegate; @@ -605,7 +603,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareSentRefund without a payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -622,7 +620,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of declareSentRefund signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( @@ -662,9 +660,7 @@ describe('extensions/payment-network/any/declarative', () => { ).toEqual(TestDataDeclarative.extensionStateReceivedPayment); }); it('can applyActionToExtensions of declareReceivedPayment from payeeDelegate', () => { - const expectedFromThirdParty = Utils.deepCopy( - TestDataDeclarative.extensionStateReceivedPayment, - ); + const expectedFromThirdParty = deepCopy(TestDataDeclarative.extensionStateReceivedPayment); expectedFromThirdParty[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payeeDelegate; @@ -691,7 +687,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareReceivedPayment without a payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.PAYMENT_NETWORK_ID.ANY_DECLARATIVE as string @@ -708,7 +704,7 @@ describe('extensions/payment-network/any/declarative', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of declareReceivedPayment signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); + const previousState = deepCopy(TestDataDeclarative.emptyRequestWithPayeeDelegate); expect(() => { pnAnyDeclarative.applyActionToExtension( diff --git a/packages/advanced-logic/test/extensions/payment-network/erc20/address-based.test.ts b/packages/advanced-logic/test/extensions/payment-network/erc20/address-based.test.ts index 7a8c3306c..f55fbe41c 100644 --- a/packages/advanced-logic/test/extensions/payment-network/erc20/address-based.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/erc20/address-based.test.ts @@ -1,10 +1,9 @@ import Erc20AddressBasedPaymentNetwork from '../../../../src/extensions/payment-network/erc20/address-based'; -import Utils from '@requestnetwork/utils'; - import * as DataERC20AddPaymentAddress from '../../../utils/payment-network/erc20/address-based-add-payment-address-data-generator'; import * as DataERC20Create from '../../../utils/payment-network/erc20/address-based-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; +import { deepCopy } from '@requestnetwork/utils'; const erc20AddressBasedPaymentNetwork = new Erc20AddressBasedPaymentNetwork(); /* eslint-disable @typescript-eslint/no-unused-expressions */ @@ -24,7 +23,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( erc20AddressBasedPaymentNetwork.createCreationAction({ paymentAddress: DataERC20Create.paymentAddress, }), @@ -35,7 +34,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( - Utils.deepCopy( + deepCopy( erc20AddressBasedPaymentNetwork.createCreationAction({ refundAddress: DataERC20Create.refundAddress, }), @@ -45,7 +44,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { it('can createCreationAction with nothing', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' - expect(Utils.deepCopy(erc20AddressBasedPaymentNetwork.createCreationAction({}))).toEqual( + expect(deepCopy(erc20AddressBasedPaymentNetwork.createCreationAction({}))).toEqual( DataERC20Create.actionCreationEmpty, ); }); @@ -110,7 +109,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -124,7 +123,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError('Unknown action: unknown action'); }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -178,9 +177,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20Create.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataERC20Create.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -197,9 +194,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataERC20Create.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataERC20Create.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -265,7 +260,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -279,7 +274,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20AddressBasedPaymentNetwork.applyActionToExtension( @@ -304,9 +299,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20AddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -349,7 +342,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -363,7 +356,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20AddressBasedPaymentNetwork.applyActionToExtension( @@ -388,9 +381,7 @@ describe('extensions/payment-network/erc20/mainnet-address-based', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20AddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC20AddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/erc20/fee-proxy-contract.test.ts b/packages/advanced-logic/test/extensions/payment-network/erc20/fee-proxy-contract.test.ts index b7c007945..824f0a3f8 100644 --- a/packages/advanced-logic/test/extensions/payment-network/erc20/fee-proxy-contract.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/erc20/fee-proxy-contract.test.ts @@ -1,11 +1,11 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Erc20FeeProxyContract from '../../../../src/extensions/payment-network/erc20/fee-proxy-contract'; import * as DataERC20FeeAddData from '../../../utils/payment-network/erc20/fee-proxy-contract-add-data-generator'; import * as DataERC20FeeCreate from '../../../utils/payment-network/erc20/fee-proxy-contract-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; +import { deepCopy } from '@requestnetwork/utils'; const erc20FeeProxyContract = new Erc20FeeProxyContract(); @@ -205,7 +205,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -220,7 +220,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -263,7 +263,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation on a non ERC20 request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -283,7 +283,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeCreate.actionCreationFull); + const testnetPaymentAddress = deepCopy(DataERC20FeeCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -300,7 +300,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy(DataERC20FeeCreate.actionCreationFull); + const testnetRefundAddress = deepCopy(DataERC20FeeCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -368,7 +368,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -383,7 +383,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20FeeProxyContract.applyActionToExtension( @@ -410,7 +410,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); + const testnetPaymentAddress = deepCopy(DataERC20FeeAddData.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -455,7 +455,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -470,7 +470,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20FeeProxyContract.applyActionToExtension( @@ -497,7 +497,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddRefundAddress); + const testnetPaymentAddress = deepCopy(DataERC20FeeAddData.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -540,7 +540,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee without a payee', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -555,7 +555,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20FeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20FeeProxyContract.applyActionToExtension( @@ -582,7 +582,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee with fee address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataERC20FeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAddress = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -597,7 +597,7 @@ describe('extensions/payment-network/erc20/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee with fee amount not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC20FeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataERC20FeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAmount = DataERC20FeeAddData.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/erc20/proxy-contract.test.ts b/packages/advanced-logic/test/extensions/payment-network/erc20/proxy-contract.test.ts index 822f168fa..af4e4e420 100644 --- a/packages/advanced-logic/test/extensions/payment-network/erc20/proxy-contract.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/erc20/proxy-contract.test.ts @@ -1,11 +1,11 @@ import { ExtensionTypes, RequestLogicTypes, IdentityTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Erc20ProxyContract from '../../../../src/extensions/payment-network/erc20/proxy-contract'; import * as DataERC20AddPaymentAddress from '../../../utils/payment-network/erc20/proxy-contract-add-payment-address-data-generator'; import * as DataERC20Create from '../../../utils/payment-network/erc20/proxy-contract-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; +import { deepCopy } from '@requestnetwork/utils'; const erc20ProxyContract = new Erc20ProxyContract(); @@ -125,7 +125,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -140,7 +140,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -183,7 +183,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }); it('cannot applyActionToExtensions of creation on a not Eth request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -203,9 +203,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20Create.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataERC20Create.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -222,9 +220,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataERC20Create.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataERC20Create.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -290,7 +286,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -304,7 +300,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20ProxyContract.applyActionToExtension( @@ -340,9 +336,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20AddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC20AddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -385,7 +379,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -399,7 +393,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataERC20Create.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC20Create.requestStateCreatedEmpty); // 'must throw' expect(() => { erc20ProxyContract.applyActionToExtension( @@ -424,9 +418,7 @@ describe('extensions/payment-network/erc20/proxy-contract', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC20AddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC20AddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataERC20AddPaymentAddress.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/erc777/stream.test.ts b/packages/advanced-logic/test/extensions/payment-network/erc777/stream.test.ts index d45766ad1..640eec554 100644 --- a/packages/advanced-logic/test/extensions/payment-network/erc777/stream.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/erc777/stream.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import Erc777StreamPaymentNetwork from '../../../../src/extensions/payment-network/erc777/stream'; @@ -88,7 +88,7 @@ describe('extensions/payment-network/erc777/stream', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -103,7 +103,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -146,7 +146,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of creation on a non ERC777 request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -166,7 +166,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataERC777StreamCreate.actionCreationFull); + const testnetPaymentAddress = deepCopy(DataERC777StreamCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { @@ -183,7 +183,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy(DataERC777StreamCreate.actionCreationFull); + const testnetRefundAddress = deepCopy(DataERC777StreamCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { @@ -251,7 +251,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -266,7 +266,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( @@ -293,9 +293,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC777StreamAddData.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { @@ -340,7 +338,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -355,7 +353,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( @@ -382,9 +380,7 @@ describe('extensions/payment-network/erc777/stream', () => { }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataERC777StreamAddData.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataERC777StreamAddData.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/ethereum/fee-proxy-contract.test.ts b/packages/advanced-logic/test/extensions/payment-network/ethereum/fee-proxy-contract.test.ts index 226c27f6e..8bfd5557b 100644 --- a/packages/advanced-logic/test/extensions/payment-network/ethereum/fee-proxy-contract.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/ethereum/fee-proxy-contract.test.ts @@ -1,11 +1,11 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import EthereumFeeProxyContract from '../../../../src/extensions/payment-network/ethereum/fee-proxy-contract'; import * as DataEthFeeAddData from '../../../utils/payment-network/ethereum/fee-proxy-contract-add-data-generator'; import * as DataEthFeeCreate from '../../../utils/payment-network/ethereum/fee-proxy-contract-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; +import { deepCopy } from '@requestnetwork/utils'; const ethFeeProxyContract = new EthereumFeeProxyContract(); @@ -205,7 +205,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataEthFeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataEthFeeAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -220,7 +220,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataEthFeeAddData.actionAddPaymentAddress); + const unknownAction = deepCopy(DataEthFeeAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -263,7 +263,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation on a non ETH request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -283,7 +283,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeCreate.actionCreationFull); + const testnetPaymentAddress = deepCopy(DataEthFeeCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -300,7 +300,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy(DataEthFeeCreate.actionCreationFull); + const testnetRefundAddress = deepCopy(DataEthFeeCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -368,7 +368,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -383,7 +383,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethFeeProxyContract.applyActionToExtension( @@ -410,7 +410,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeAddData.actionAddPaymentAddress); + const testnetPaymentAddress = deepCopy(DataEthFeeAddData.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -455,7 +455,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -470,7 +470,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethFeeProxyContract.applyActionToExtension( @@ -497,7 +497,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeAddData.actionAddRefundAddress); + const testnetPaymentAddress = deepCopy(DataEthFeeAddData.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -540,7 +540,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee without a payee', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -555,7 +555,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthFeeCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethFeeProxyContract.applyActionToExtension( @@ -582,7 +582,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee with fee address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataEthFeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAddress = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { @@ -597,7 +597,7 @@ describe('extensions/payment-network/ethereum/fee-proxy-contract', () => { }); it('cannot applyActionToExtensions of addFee with fee amount not valid', () => { - const testnetPaymentAddress = Utils.deepCopy(DataEthFeeAddData.actionAddFee); + const testnetPaymentAddress = deepCopy(DataEthFeeAddData.actionAddFee); testnetPaymentAddress.parameters.feeAmount = DataEthFeeAddData.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/advanced-logic/test/extensions/payment-network/ethereum/input-data.test.ts b/packages/advanced-logic/test/extensions/payment-network/ethereum/input-data.test.ts index dba01e5d3..a29f0e2d7 100644 --- a/packages/advanced-logic/test/extensions/payment-network/ethereum/input-data.test.ts +++ b/packages/advanced-logic/test/extensions/payment-network/ethereum/input-data.test.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import EthereumInputDataPaymentNetwork from '../../../../src/extensions/payment-network/ethereum/input-data'; @@ -125,7 +125,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { - const unknownAction = Utils.deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { @@ -140,7 +140,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }); it('cannot applyActionToExtensions of unknown id', () => { - const unknownAction = Utils.deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); + const unknownAction = deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { @@ -183,7 +183,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }); it('cannot applyActionToExtensions of creation on a not Eth request', () => { - const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( + const requestCreatedNoExtension: RequestLogicTypes.IRequest = deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { @@ -203,9 +203,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataEthCreate.actionCreationWithPaymentAndRefund, - ); + const testnetPaymentAddress = deepCopy(DataEthCreate.actionCreationWithPaymentAndRefund); testnetPaymentAddress.parameters.paymentAddress = DataEthAddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -222,9 +220,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { - const testnetRefundAddress = Utils.deepCopy( - DataEthCreate.actionCreationWithPaymentAndRefund, - ); + const testnetRefundAddress = deepCopy(DataEthCreate.actionCreationWithPaymentAndRefund); testnetRefundAddress.parameters.refundAddress = DataEthAddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -290,7 +286,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { - const previousState = Utils.deepCopy(DataEthCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { @@ -304,7 +300,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { - const previousState = Utils.deepCopy(DataEthCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethereumInputDataPaymentNetwork.applyActionToExtension( @@ -329,9 +325,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataEthAddPaymentAddress.actionAddPaymentAddress, - ); + const testnetPaymentAddress = deepCopy(DataEthAddPaymentAddress.actionAddPaymentAddress); testnetPaymentAddress.parameters.paymentAddress = DataEthAddPaymentAddress.invalidAddress; // 'must throw' expect(() => { @@ -374,7 +368,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { - const previousState = Utils.deepCopy(DataEthCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { @@ -388,7 +382,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { - const previousState = Utils.deepCopy(DataEthCreate.requestStateCreatedEmpty); + const previousState = deepCopy(DataEthCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { ethereumInputDataPaymentNetwork.applyActionToExtension( @@ -413,9 +407,7 @@ describe('extensions/payment-network/ethereum/input-data', () => { }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { - const testnetPaymentAddress = Utils.deepCopy( - DataEthAddPaymentAddress.actionAddRefundAddress, - ); + const testnetPaymentAddress = deepCopy(DataEthAddPaymentAddress.actionAddRefundAddress); testnetPaymentAddress.parameters.refundAddress = DataEthAddPaymentAddress.invalidAddress; // 'must throw' expect(() => { diff --git a/packages/currency/src/getHash.ts b/packages/currency/src/getHash.ts index de53e5a98..66e970df6 100644 --- a/packages/currency/src/getHash.ts +++ b/packages/currency/src/getHash.ts @@ -1,11 +1,11 @@ import { RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { last20bytesOfNormalizedKeccak256Hash } from '@requestnetwork/utils'; export const getHash = (curr: RequestLogicTypes.ICurrency): string => { return curr.type === RequestLogicTypes.CURRENCY.ERC20 || curr.type === RequestLogicTypes.CURRENCY.ERC777 ? curr.value - : Utils.crypto.last20bytesOfNormalizedKeccak256Hash({ + : last20bytesOfNormalizedKeccak256Hash({ type: curr.type, value: curr.value, // FIXME network should be included for native tokens. diff --git a/packages/data-access/src/block.ts b/packages/data-access/src/block.ts index 4232f5dd6..b12f63de0 100644 --- a/packages/data-access/src/block.ts +++ b/packages/data-access/src/block.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; import { DataAccessTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; /** * Module to manage a block in the data access-layer @@ -125,7 +125,7 @@ function pushTransaction( throw new Error('The transaction is missing the data property or encryptedData property'); } // we don't want to modify the original block state - const copiedBlock: DataAccessTypes.IBlock = Utils.deepCopy(block); + const copiedBlock: DataAccessTypes.IBlock = deepCopy(block); const newTransactionPosition = copiedBlock.transactions.length; copiedBlock.transactions.push(transaction); diff --git a/packages/data-access/src/data-access.ts b/packages/data-access/src/data-access.ts index df9ddf872..47a961b89 100644 --- a/packages/data-access/src/data-access.ts +++ b/packages/data-access/src/data-access.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; import { DataAccessTypes, LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy, getCurrentTimestampInSecond, SimpleLogger, unique } from '@requestnetwork/utils'; import * as Bluebird from 'bluebird'; import { EventEmitter } from 'events'; @@ -96,7 +96,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { public constructor(storage: StorageTypes.IStorage, options?: Partial) { const defaultOptions: IDataAccessOptions = { ignoredLocationIndex: new IgnoredLocationIndex(), - logger: new Utils.SimpleLogger(), + logger: new SimpleLogger(), synchronizationIntervalTime: DEFAULT_INTERVAL_TIME, transactionIndex: new TransactionIndex(), autoStartSynchronization: false, @@ -140,7 +140,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { // if transaction index already has data, then sync from the last available timestamp const lastSynced = await this.transactionIndex.getLastTransactionTimestamp(); - const now = Utils.getCurrentTimestampInSecond(); + const now = getCurrentTimestampInSecond(); // initialize the dataId topic with the previous block const allDataWithMeta = await this.storage.getData( @@ -368,7 +368,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { channelIdAndTransactions.transactionsWithMeta.result.transactions; return finalResult; - }, Utils.deepCopy(emptyChannelsWithTopics)); + }, deepCopy(emptyChannelsWithTopics)); } /** @@ -420,7 +420,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { channelIdAndTransactions.transactionsWithMeta.result.transactions; return finalResult; - }, Utils.deepCopy(emptyChannelsWithTopics)); + }, deepCopy(emptyChannelsWithTopics)); } /** @@ -428,7 +428,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { */ public async synchronizeNewDataIds(): Promise { this.checkInitialized(); - const synchronizationTo = Utils.getCurrentTimestampInSecond(); + const synchronizationTo = getCurrentTimestampInSecond(); // We increment lastSyncStorageTimestamp because the data located at lastSyncStorageTimestamp // 0 means it's the first synchronization @@ -592,7 +592,7 @@ export default class DataAccess implements DataAccessTypes.IDataAccess { // Gets the transaction from the positions const transactions: DataAccessTypes.ITimestampedTransaction[] = // first remove de duplicates - Utils.unique(transactionPositions).uniqueItems.map( + unique(transactionPositions).uniqueItems.map( // Get the transaction from their position and add the timestamp (position: number) => ({ state: diff --git a/packages/data-access/src/transaction-index/location-by-topic.ts b/packages/data-access/src/transaction-index/location-by-topic.ts index 93c626384..c84cc6d84 100644 --- a/packages/data-access/src/transaction-index/location-by-topic.ts +++ b/packages/data-access/src/transaction-index/location-by-topic.ts @@ -1,7 +1,7 @@ import { DataAccessTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Keyv from 'keyv'; +import { flatten2DimensionsArray, unique } from '@requestnetwork/utils'; // Serialize function used for keyv to serialize a Set data structure into a string // There is no way to directly stringify a Set, we need to convert it to an array before @@ -105,7 +105,7 @@ export default class LocationByTopicTransactionIndex { const channelIds = await Promise.all(channelIdsPromises); // flatten the array of array and remove the duplicates - return Utils.unique(Utils.flatten2DimensionsArray(channelIds)).uniqueItems; + return unique(flatten2DimensionsArray(channelIds)).uniqueItems; } /** * Function to get storage locations from a channel id diff --git a/packages/docs/docs/guides/2-request-client/6-signature-provider.md b/packages/docs/docs/guides/2-request-client/6-signature-provider.md index e293092f3..534477d0d 100644 --- a/packages/docs/docs/guides/2-request-client/6-signature-provider.md +++ b/packages/docs/docs/guides/2-request-client/6-signature-provider.md @@ -37,7 +37,7 @@ Your signature provider would look like: ```typescript import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; // Your package import mySignaturePackage from 'mySignaturePackage'; @@ -68,7 +68,7 @@ export default class MySignatureProvider implements SignatureProviderTypes.ISign } // Hash the normalized data (e.g. avoid case sensitivity) - const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; + const hashData = normalizeKeccak256Hash(data).value; // use your signature package const signatureValue = mySignaturePackage.sign(hashData, signer.value); @@ -118,7 +118,7 @@ Your signature provider would look like: ```typescript import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; // Your package import mySignaturePackage from 'mySignaturePackage'; @@ -170,7 +170,7 @@ export default class MySignatureProvider implements SignatureProviderTypes.ISign } // Hash the normalized data (e.g. avoid case sensitivity) - const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; + const hashData = normalizeKeccak256Hash(data).value; // convert the hash from a string '0x...' to a Buffer const hashDataBuffer = Buffer.from(hashData.slice(2), 'hex'); diff --git a/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts b/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts index 974fec219..95f5aacef 100644 --- a/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts +++ b/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts @@ -1,6 +1,6 @@ import { DecryptionProviderTypes, EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { decrypt, EcUtils } from '@requestnetwork/utils'; /** Type of the dictionary of decryptionParameters (private keys) indexed by ethereum address */ type IDecryptionParametersDictionary = Map; @@ -55,7 +55,7 @@ export default class EthereumPrivateKeyDecryptionProvider throw Error(`private key unknown for the identity: ${identity.value}`); } - return Utils.encryption.decrypt(encryptedData, decryptionParameters); + return decrypt(encryptedData, decryptionParameters); } /** @@ -87,9 +87,7 @@ export default class EthereumPrivateKeyDecryptionProvider // compute the address from private key // toLowerCase to avoid mismatch because of case - const address = Utils.crypto.EcUtils.getAddressFromPrivateKey( - decryptionParameters.key, - ).toLowerCase(); + const address = EcUtils.getAddressFromPrivateKey(decryptionParameters.key).toLowerCase(); this.decryptionParametersDictionary.set(address, decryptionParameters); diff --git a/packages/epk-decryption/test/ethereum-private-key-decryption-provider.test.ts b/packages/epk-decryption/test/ethereum-private-key-decryption-provider.test.ts index 786909824..da1183180 100644 --- a/packages/epk-decryption/test/ethereum-private-key-decryption-provider.test.ts +++ b/packages/epk-decryption/test/ethereum-private-key-decryption-provider.test.ts @@ -1,7 +1,7 @@ import { EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import EthereumPrivateKeyDecryptionProvider from '../src/ethereum-private-key-decryption-provider'; +import { encrypt } from '@requestnetwork/utils'; export const id1Raw = { address: '0xaf083f77f1ffd54218d91491afd06c9296eac3ce', @@ -153,10 +153,7 @@ describe('ethereum-private-key-decryption-provider', () => { describe('decrypt', () => { it('can decrypt', async () => { - const encryptedData = await Utils.encryption.encrypt( - decryptedDataExpected, - id1Raw.encryptionParams, - ); + const encryptedData = await encrypt(decryptedDataExpected, id1Raw.encryptionParams); const decryptionProvider = new EthereumPrivateKeyDecryptionProvider(id1Raw.decryptionParams); @@ -179,10 +176,7 @@ describe('ethereum-private-key-decryption-provider', () => { }); it('cannot decrypt if identity not supported', async () => { - const encryptedData = await Utils.encryption.encrypt( - decryptedDataExpected, - id1Raw.encryptionParams, - ); + const encryptedData = await encrypt(decryptedDataExpected, id1Raw.encryptionParams); const decryptionProvider = new EthereumPrivateKeyDecryptionProvider(id1Raw.decryptionParams); const arbitraryIdentity: any = { type: 'unknown type', value: '0x000' }; @@ -192,10 +186,7 @@ describe('ethereum-private-key-decryption-provider', () => { }); it('cannot decrypt if private key of the identity not given', async () => { - const encryptedData = await Utils.encryption.encrypt( - decryptedDataExpected, - id1Raw.encryptionParams, - ); + const encryptedData = await encrypt(decryptedDataExpected, id1Raw.encryptionParams); const decryptionProvider = new EthereumPrivateKeyDecryptionProvider(id1Raw.decryptionParams); const arbitraryIdentity: IdentityTypes.IIdentity = { diff --git a/packages/epk-signature/src/ethereum-private-key-signature-provider.ts b/packages/epk-signature/src/ethereum-private-key-signature-provider.ts index 3991ac105..07414f04e 100644 --- a/packages/epk-signature/src/ethereum-private-key-signature-provider.ts +++ b/packages/epk-signature/src/ethereum-private-key-signature-provider.ts @@ -1,6 +1,6 @@ import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** Type of the dictionary of signatureParameters (private keys) indexed by ethereum address */ type ISignatureParametersDictionary = Map; @@ -55,8 +55,8 @@ export default class EthereumPrivateKeySignatureProvider } // the hash format in request start by 01 but the ec-utils need a hash starting by 0x - const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; - const signatureValue = Utils.crypto.EcUtils.sign(signatureParameter.privateKey, hashData); + const hashData = normalizeKeccak256Hash(data).value; + const signatureValue = EcUtils.sign(signatureParameter.privateKey, hashData); return { data, @@ -83,9 +83,7 @@ export default class EthereumPrivateKeySignatureProvider // compute the address from private key // toLowerCase to avoid mismatch because of case - const address = Utils.crypto.EcUtils.getAddressFromPrivateKey( - signatureParams.privateKey, - ).toLowerCase(); + const address = EcUtils.getAddressFromPrivateKey(signatureParams.privateKey).toLowerCase(); this.signatureParametersDictionary.set(address, signatureParams); diff --git a/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts b/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts index fbf75dc8f..451de7200 100644 --- a/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts +++ b/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts @@ -1,8 +1,7 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import EthereumPrivateKeySignatureProvider from '../src/ethereum-private-key-signature-provider'; - -import Utils from '@requestnetwork/utils'; +import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; const id1Raw = { address: '0xaf083f77f1ffd54218d91491afd06c9296eac3ce', @@ -35,8 +34,8 @@ export const id2Raw = { }; const data = { What: 'ever', the: 'data', are: true }; -const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; -const signatureValueExpected = Utils.crypto.EcUtils.sign(id1Raw.privateKey, hashData); +const hashData = normalizeKeccak256Hash(data).value; +const signatureValueExpected = EcUtils.sign(id1Raw.privateKey, hashData); const signedDataExpected = { data, signature: { diff --git a/packages/ethereum-storage/src/ethereum-blocks.ts b/packages/ethereum-storage/src/ethereum-blocks.ts index 249d69509..01623fe03 100644 --- a/packages/ethereum-storage/src/ethereum-blocks.ts +++ b/packages/ethereum-storage/src/ethereum-blocks.ts @@ -1,5 +1,5 @@ import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { cachedThrottle, retry, SimpleLogger } from '@requestnetwork/utils'; /** * Manages every info linked to the ethereum blocks (blockNumber, blockTimestamp, confirmations ... ) @@ -61,16 +61,16 @@ export default class EthereumBlocks { this.getLastBlockNumberMinDelay = getLastBlockNumberMinDelay; - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); // Get retry parameter values from config this.retryDelay = retryDelay; this.maxRetries = maxRetries; // Setup the throttled and retriable getLastBlockNumber function - this.getLastBlockNumber = Utils.cachedThrottle( + this.getLastBlockNumber = cachedThrottle( () => - Utils.retry( + retry( () => { this.logger.debug(`Getting last block number`, ['ethereum', 'ethereum-blocks']); return this.eth.getBlockNumber(); @@ -96,8 +96,8 @@ export default class EthereumBlocks { } // if we don't know the information, let's get it - // Use Utils.retry to rerun if getBlock fails - const block = await Utils.retry((bn: number) => this.eth.getBlock(bn), { + // Use retry to rerun if getBlock fails + const block = await retry((bn: number) => this.eth.getBlock(bn), { maxRetries: this.maxRetries, retryDelay: this.retryDelay, })(blockNumber); @@ -194,7 +194,7 @@ export default class EthereumBlocks { * @returns An Ethereum block */ public async getBlock(blockNumber: number | string): Promise { - return Utils.retry(this.eth.getBlock, { + return retry(this.eth.getBlock, { context: this.eth, maxRetries: this.maxRetries, retryDelay: this.retryDelay, diff --git a/packages/ethereum-storage/src/ethereum-storage-ethers.ts b/packages/ethereum-storage/src/ethereum-storage-ethers.ts index c7a687886..05e7737dd 100644 --- a/packages/ethereum-storage/src/ethereum-storage-ethers.ts +++ b/packages/ethereum-storage/src/ethereum-storage-ethers.ts @@ -1,10 +1,10 @@ import { EventEmitter } from 'events'; import { BigNumber, ContractReceipt, providers, Signer } from 'ethers'; import TypedEmitter from 'typed-emitter'; -import Utils from '@requestnetwork/utils'; import { LogTypes, StorageTypes } from '@requestnetwork/types'; import { requestHashSubmitterArtifact } from '@requestnetwork/smart-contracts'; import { EthereumTransactionSubmitter } from './ethereum-tx-submitter'; +import { getCurrentTimestampInSecond, SimpleLogger } from '@requestnetwork/utils'; export type GasDefinerProps = { gasPriceMin?: BigNumber; @@ -33,7 +33,7 @@ export class EthereumStorageEthers implements StorageTypes.IStorageWrite { private readonly txSubmitter: EthereumTransactionSubmitter; constructor({ network, signer, ipfsStorage, logger, gasPriceMin }: StorageProps) { - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.ipfsStorage = ipfsStorage; this.network = network; this.txSubmitter = new EthereumTransactionSubmitter({ network, signer, logger, gasPriceMin }); @@ -68,7 +68,7 @@ export class EthereumStorageEthers implements StorageTypes.IStorageWrite { }, state: StorageTypes.ContentState.PENDING, storageType: StorageTypes.StorageSystemType.LOCAL, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }, }; diff --git a/packages/ethereum-storage/src/ethereum-storage.ts b/packages/ethereum-storage/src/ethereum-storage.ts index e38eed5dd..52180f5bf 100644 --- a/packages/ethereum-storage/src/ethereum-storage.ts +++ b/packages/ethereum-storage/src/ethereum-storage.ts @@ -1,5 +1,4 @@ import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Bluebird from 'bluebird'; import { EventEmitter } from 'events'; import { getMaxConcurrency } from './config'; @@ -11,6 +10,7 @@ import SmartContractManager from './smart-contract-manager'; import * as Keyv from 'keyv'; import { BigNumber } from 'ethers'; +import { getCurrentTimestampInSecond, SimpleLogger } from '@requestnetwork/utils'; // time to wait before considering the web3 provider is not reachable const WEB3_PROVIDER_TIMEOUT = 10000; @@ -90,7 +90,7 @@ export class EthereumStorage implements StorageTypes.IStorage { metadataStore?: Keyv.Store, ) { this.maxConcurrency = maxConcurrency || getMaxConcurrency(); - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.ipfsStorage = ipfsStorage; this.smartContractManager = new SmartContractManager(web3Connection, { getLastBlockNumberDelay, @@ -167,7 +167,7 @@ export class EthereumStorage implements StorageTypes.IStorage { const { ipfsHash, ipfsSize } = await this.ipfsStorage.ipfsAdd(content); - const timestamp = Utils.getCurrentTimestampInSecond(); + const timestamp = getCurrentTimestampInSecond(); const result: StorageTypes.IAppendResult = Object.assign(new EventEmitter(), { content, id: ipfsHash, diff --git a/packages/ethereum-storage/src/ethereum-tx-submitter.ts b/packages/ethereum-storage/src/ethereum-tx-submitter.ts index 1e8233b56..672d4503f 100644 --- a/packages/ethereum-storage/src/ethereum-tx-submitter.ts +++ b/packages/ethereum-storage/src/ethereum-tx-submitter.ts @@ -1,10 +1,10 @@ import { ContractTransaction, providers, utils } from 'ethers'; -import Utils from '@requestnetwork/utils'; import { LogTypes } from '@requestnetwork/types'; import { requestHashSubmitterArtifact } from '@requestnetwork/smart-contracts'; import { RequestOpenHashSubmitter } from '@requestnetwork/smart-contracts/types'; import { SubmitterProps } from './ethereum-storage-ethers'; import { GasFeeDefiner } from './gas-fee-definer'; +import { SimpleLogger } from '@requestnetwork/utils'; /** * Handles the submission of a hash on the request HashSubmitter contract @@ -17,7 +17,7 @@ export class EthereumTransactionSubmitter { private readonly gasFeeDefiner: GasFeeDefiner; constructor({ network, signer, logger, gasPriceMin }: SubmitterProps) { - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); const provider = signer.provider as providers.JsonRpcProvider; this.provider = provider; this.hashSubmitter = requestHashSubmitterArtifact.connect( diff --git a/packages/ethereum-storage/src/gas-fee-definer.ts b/packages/ethereum-storage/src/gas-fee-definer.ts index fff8224c2..09afa7c8d 100644 --- a/packages/ethereum-storage/src/gas-fee-definer.ts +++ b/packages/ethereum-storage/src/gas-fee-definer.ts @@ -1,6 +1,6 @@ import { BigNumber, providers, constants } from 'ethers'; -import Utils from '@requestnetwork/utils'; import { GasDefinerProps } from './ethereum-storage-ethers'; +import { estimateGasFees } from '@requestnetwork/utils'; export class GasFeeDefiner { private readonly provider: providers.JsonRpcProvider; @@ -18,6 +18,6 @@ export class GasFeeDefiner { maxFeePerGas?: BigNumber; maxPriorityFeePerGas?: BigNumber; }> { - return Utils.estimateGasFees({ provider: this.provider, gasPriceMin: this.gasPriceMin }); + return estimateGasFees({ provider: this.provider, gasPriceMin: this.gasPriceMin }); } } diff --git a/packages/ethereum-storage/src/gas-price-definer.ts b/packages/ethereum-storage/src/gas-price-definer.ts index 6cc60927a..7bd232392 100644 --- a/packages/ethereum-storage/src/gas-price-definer.ts +++ b/packages/ethereum-storage/src/gas-price-definer.ts @@ -5,11 +5,11 @@ import EtherscanProvider from './gas-price-providers/etherscan-provider'; import EthGasStationProvider from './gas-price-providers/ethgasstation-provider'; import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { BigNumber } from 'ethers'; import XDaiFixedProvider from './gas-price-providers/xdai-fixed-provider'; import { GasDefinerProps } from './ethereum-storage-ethers'; +import { SimpleLogger } from '@requestnetwork/utils'; /** * Determines the gas price to use depending on the used network @@ -48,7 +48,7 @@ export class GasPriceDefiner { logger, gasPriceMin, }: GasDefinerProps & { logger?: LogTypes.ILogger } = {}) { - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.gasPriceMin = gasPriceMin; } diff --git a/packages/ethereum-storage/src/gas-price-providers/etherchain-provider.ts b/packages/ethereum-storage/src/gas-price-providers/etherchain-provider.ts index 8c711653f..3f7b9e5a7 100644 --- a/packages/ethereum-storage/src/gas-price-providers/etherchain-provider.ts +++ b/packages/ethereum-storage/src/gas-price-providers/etherchain-provider.ts @@ -1,11 +1,11 @@ import EthereumUtils from '../ethereum-utils'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const ETHERCHAIN_REQUEST_MAX_RETRY = 3; @@ -32,7 +32,7 @@ export default class EtherchainProvider implements StorageTypes.IGasPriceProvide * @returns Requested gas price */ public async getGasPrice(type: StorageTypes.GasPriceType): Promise { - const res = await Utils.retry(async () => Axios.get(this.providerUrl), { + const res = await retry(async () => Axios.get(this.providerUrl), { maxRetries: ETHERCHAIN_REQUEST_MAX_RETRY, retryDelay: ETHERCHAIN_REQUEST_RETRY_DELAY, })(); diff --git a/packages/ethereum-storage/src/gas-price-providers/etherscan-provider.ts b/packages/ethereum-storage/src/gas-price-providers/etherscan-provider.ts index e2eb0fdb5..f84928d4a 100644 --- a/packages/ethereum-storage/src/gas-price-providers/etherscan-provider.ts +++ b/packages/ethereum-storage/src/gas-price-providers/etherscan-provider.ts @@ -1,11 +1,11 @@ import EthereumUtils from '../ethereum-utils'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const ETHERSCAN_REQUEST_MAX_RETRY = 3; @@ -32,7 +32,7 @@ export default class EtherscanProvider implements StorageTypes.IGasPriceProvider * @returns Requested gas price */ public async getGasPrice(type: StorageTypes.GasPriceType): Promise { - const res = await Utils.retry(async () => Axios.get(this.providerUrl), { + const res = await retry(async () => Axios.get(this.providerUrl), { maxRetries: ETHERSCAN_REQUEST_MAX_RETRY, retryDelay: ETHERSCAN_REQUEST_RETRY_DELAY, })(); diff --git a/packages/ethereum-storage/src/gas-price-providers/ethgasstation-provider.ts b/packages/ethereum-storage/src/gas-price-providers/ethgasstation-provider.ts index f405cab96..411a75e0b 100644 --- a/packages/ethereum-storage/src/gas-price-providers/ethgasstation-provider.ts +++ b/packages/ethereum-storage/src/gas-price-providers/ethgasstation-provider.ts @@ -1,10 +1,10 @@ import EthereumUtils from '../ethereum-utils'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const ETHGASSTATION_REQUEST_MAX_RETRY = 3; @@ -31,7 +31,7 @@ export default class EthGasStationProvider implements StorageTypes.IGasPriceProv * @returns Requested gas price */ public async getGasPrice(type: StorageTypes.GasPriceType): Promise { - const res = await Utils.retry(async () => Axios.get(this.providerUrl), { + const res = await retry(async () => Axios.get(this.providerUrl), { maxRetries: ETHGASSTATION_REQUEST_MAX_RETRY, retryDelay: ETHGASSTATION_RETRY_DELAY, })(); diff --git a/packages/ethereum-storage/src/ipfs-manager.ts b/packages/ethereum-storage/src/ipfs-manager.ts index 65fc0938a..a4d2cd848 100644 --- a/packages/ethereum-storage/src/ipfs-manager.ts +++ b/packages/ethereum-storage/src/ipfs-manager.ts @@ -1,11 +1,11 @@ import { UnixFS } from 'ipfs-unixfs'; import * as qs from 'qs'; import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios'; -import Utils from '@requestnetwork/utils'; import { LogTypes, StorageTypes } from '@requestnetwork/types'; import { getDefaultIpfs, getIpfsErrorHandlingConfig } from './config'; import * as FormData from 'form-data'; +import { retry, SimpleLogger } from '@requestnetwork/utils'; /** A mapping between IPFS Paths and the response type */ type IpfsPaths = { @@ -43,7 +43,7 @@ export default class IpfsManager { }) { this.ipfsGatewayConnection = options?.ipfsGatewayConnection || getDefaultIpfs(); this.ipfsErrorHandling = options?.ipfsErrorHandling || getIpfsErrorHandlingConfig(); - this.logger = options?.logger || new Utils.SimpleLogger(); + this.logger = options?.logger || new SimpleLogger(); this.axiosInstance = axios.create({ baseURL: `${this.ipfsGatewayConnection.protocol}://${this.ipfsGatewayConnection.host}:${this.ipfsGatewayConnection.port}/${this.BASE_PATH}/`, @@ -55,7 +55,7 @@ export default class IpfsManager { } private async ipfs(path: T, config?: AxiosRequestConfig) { - const _post = Utils.retry(this.axiosInstance.post, { + const _post = retry(this.axiosInstance.post, { context: this.axiosInstance, maxRetries: this.ipfsErrorHandling.maxRetries, retryDelay: this.ipfsErrorHandling.delayBetweenRetries, diff --git a/packages/ethereum-storage/src/ipfs-storage.ts b/packages/ethereum-storage/src/ipfs-storage.ts index 603dd4ff6..6df4a11b1 100644 --- a/packages/ethereum-storage/src/ipfs-storage.ts +++ b/packages/ethereum-storage/src/ipfs-storage.ts @@ -1,8 +1,8 @@ import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { getIpfsExpectedBootstrapNodes, getPinRequestConfig } from './config'; import IpfsManager from './ipfs-manager'; +import { SimpleLogger } from '@requestnetwork/utils'; export type IpfsStorageProps = { logger?: LogTypes.ILogger; @@ -15,7 +15,7 @@ export class IpfsStorage implements StorageTypes.IIpfsStorage { constructor({ ipfsGatewayConnection, logger }: IpfsStorageProps) { this.ipfsManager = new IpfsManager({ ipfsGatewayConnection, logger }); - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); } public async initialize(): Promise { diff --git a/packages/ethereum-storage/src/smart-contract-manager.ts b/packages/ethereum-storage/src/smart-contract-manager.ts index fa15336e8..2c184c37a 100644 --- a/packages/ethereum-storage/src/smart-contract-manager.ts +++ b/packages/ethereum-storage/src/smart-contract-manager.ts @@ -1,6 +1,5 @@ import * as SmartContracts from '@requestnetwork/smart-contracts'; import { LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Bluebird from 'bluebird'; import * as config from './config'; import EthereumBlocks from './ethereum-blocks'; @@ -13,6 +12,12 @@ const web3Eth = require('web3-eth'); const web3Utils = require('web3-utils'); import { BigNumber } from 'ethers'; +import { + flatten2DimensionsArray, + retry, + SimpleLogger, + timeoutPromise, +} from '@requestnetwork/utils'; // Maximum number of attempt to create ethereum metadata when transaction to add hash and size to Ethereum is confirmed // 23 is the number of call of the transaction's confirmation event function @@ -105,7 +110,7 @@ export default class SmartContractManager { }, ) { this.maxConcurrency = maxConcurrency; - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.maxRetries = maxRetries; this.retryDelay = retryDelay; @@ -235,7 +240,7 @@ export default class SmartContractManager { public async getMainAccount(): Promise { // Get the accounts on the provider // Throws an error if timeout is reached - const accounts = await Utils.timeoutPromise( + const accounts = await timeoutPromise( this.eth.getAccounts(), this.timeout, 'Web3 getAccounts connection timeout', @@ -265,7 +270,7 @@ export default class SmartContractManager { // Get the fee from the size of the content // Throws an error if timeout is reached - const fee = await Utils.timeoutPromise( + const fee = await timeoutPromise( this.requestHashSubmitter.methods.getFeesAmount(feesParameters.contentSize).call(), this.timeout, 'Web3 getFeesAmount connection timeout', @@ -532,9 +537,9 @@ export default class SmartContractManager { // If getPastEvents doesn't throw, we can return the returned events from the function let events: any; try { - events = await Utils.retry( + events = await retry( (args) => - Utils.timeoutPromise( + timeoutPromise( this.requestHashStorage.getPastEvents(args), this.timeout, 'Web3 getPastEvents connection timeout', @@ -564,7 +569,7 @@ export default class SmartContractManager { ); return Promise.all([eventsFirstHalfPromise, eventsSecondHalfPromise]) - .then((halves) => Utils.flatten2DimensionsArray(halves)) + .then((halves) => flatten2DimensionsArray(halves)) .catch((err) => { throw err; }); diff --git a/packages/ethereum-storage/test/ethereum-entries-to-ipfs-content.test.ts b/packages/ethereum-storage/test/ethereum-entries-to-ipfs-content.test.ts index d08723555..2ba90d6a0 100644 --- a/packages/ethereum-storage/test/ethereum-entries-to-ipfs-content.test.ts +++ b/packages/ethereum-storage/test/ethereum-entries-to-ipfs-content.test.ts @@ -1,5 +1,5 @@ import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { SimpleLogger } from '@requestnetwork/utils'; import ethereumEntriesToIpfsContent from '../src/ethereum-entries-to-ipfs-content'; import IgnoredDataIndex from '../src/ignored-dataIds'; @@ -60,7 +60,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); @@ -175,7 +175,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); @@ -246,7 +246,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); @@ -287,7 +287,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); expect(result.length).toBe(1); @@ -316,7 +316,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); expect(result.length).toBe(0); @@ -349,7 +349,7 @@ describe('ethereum-entries-to-ipfs-content', () => { ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, - new Utils.SimpleLogger(), + new SimpleLogger(), 5, ); expect(result.length).toBe(0); diff --git a/packages/ethereum-storage/test/ethereum-storage.test.ts b/packages/ethereum-storage/test/ethereum-storage.test.ts index ab02c30ba..bcc4ffa62 100644 --- a/packages/ethereum-storage/test/ethereum-storage.test.ts +++ b/packages/ethereum-storage/test/ethereum-storage.test.ts @@ -1,6 +1,6 @@ import * as SmartContracts from '@requestnetwork/smart-contracts'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { getCurrentTimestampInSecond } from '@requestnetwork/utils'; import { EventEmitter } from 'events'; import { EthereumStorage } from '../src/ethereum-storage'; @@ -222,7 +222,7 @@ describe('EthereumStorage', () => { it('allows to append a file', async () => { jest.useFakeTimers('modern'); jest.setSystemTime(0); - const timestamp = Utils.getCurrentTimestampInSecond(); + const timestamp = getCurrentTimestampInSecond(); const result = await ethereumStorage.append(content1); const resultExpected: StorageTypes.IAppendResult = Object.assign(new EventEmitter(), { diff --git a/packages/integration-test/test/layers.test.ts b/packages/integration-test/test/layers.test.ts index 2d9b09d3d..1e72d03a6 100644 --- a/packages/integration-test/test/layers.test.ts +++ b/packages/integration-test/test/layers.test.ts @@ -1,3 +1,5 @@ +import { getCurrentTimestampInSecond } from '@requestnetwork/utils'; + const web3Eth = require('web3-eth'); import { AdvancedLogic } from '@requestnetwork/advanced-logic'; @@ -17,7 +19,6 @@ import { SignatureTypes, StorageTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; let advancedLogic: AdvancedLogicTypes.IAdvancedLogic; let requestLogic: RequestLogicTypes.IRequestLogic; @@ -367,7 +368,7 @@ describe('Request system', () => { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0x740fc87Bd3f41d07d23A01DEc90623eBC5fed9D6', }, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }; // create a unique topic just to not have collisions in tests const topics1 = [request1CreationHash]; @@ -390,7 +391,7 @@ describe('Request system', () => { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0x740fc87Bd3f41d07d23A01DEc90623eBC5fed9D6', }, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }; const resultCreation2 = await requestLogic.createRequest( request2CreationHash, diff --git a/packages/integration-test/test/node-client.test.ts b/packages/integration-test/test/node-client.test.ts index f5e7a546a..41a1ae528 100644 --- a/packages/integration-test/test/node-client.test.ts +++ b/packages/integration-test/test/node-client.test.ts @@ -8,7 +8,6 @@ import { RequestLogicTypes, ExtensionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { payRequest, approveErc20ForProxyConversionIfNeeded, @@ -24,6 +23,7 @@ import { requestNetwork, signatureProvider, } from './scheduled/fixtures'; +import { getCurrentTimestampInSecond, normalizeKeccak256Hash } from '@requestnetwork/utils'; const mnemonic = 'candy maple cake sugar pudding cream honey rich smooth crumble sweet treat'; const provider = new providers.JsonRpcProvider('http://localhost:8545'); @@ -175,11 +175,11 @@ describe('Request client using a request node', () => { expectedAmount: '100000000', payee: payeeIdentity, payer: payerIdentity, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }; const topicsRequest1and2: string[] = [ - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(requestCreationHash1)), + MultiFormat.serialize(normalizeKeccak256Hash(requestCreationHash1)), ]; const request1: Request = await requestNetwork.createRequest({ @@ -188,7 +188,7 @@ describe('Request client using a request node', () => { topics: topicsRequest1and2, }); await request1.waitForConfirmation(); - const timestampBeforeReduce = Utils.getCurrentTimestampInSecond(); + const timestampBeforeReduce = getCurrentTimestampInSecond(); // make sure that request 2 timestamp is greater than request 1 timestamp const waitNextSecond = (timestampBeforeReduce + 1) * 1000 - Date.now(); @@ -200,7 +200,7 @@ describe('Request client using a request node', () => { expectedAmount: '1000', payee: payeeIdentity, payer: payerIdentity, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }; const request2: Request = await requestNetwork.createRequest({ @@ -251,11 +251,11 @@ describe('Request client using a request node', () => { value: '0xf17f52151ebef6c7334fad080c5704d77216b732', }; - const timestampCreation = Utils.getCurrentTimestampInSecond(); + const timestampCreation = getCurrentTimestampInSecond(); // create request 1 const topicsRequest1and2: string[] = [ - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(timestampCreation)), + MultiFormat.serialize(normalizeKeccak256Hash(timestampCreation)), ]; const request1: Request = await requestNetwork.createRequest({ requestInfo: { @@ -263,7 +263,7 @@ describe('Request client using a request node', () => { expectedAmount: '100000000', payee: payeeIdentity, payer: payerSmartContract, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }, signer: payeeIdentity, topics: topicsRequest1and2, @@ -276,7 +276,7 @@ describe('Request client using a request node', () => { expectedAmount: '1000', payee: payeeIdentity, payer: payerIdentity, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), }, signer: payeeIdentity, topics: topicsRequest1and2, @@ -473,7 +473,7 @@ describe('Request client using a request node', () => { it('cannot decrypt a request with the wrong decryption provider', async () => { const timestamp = Date.now(); - const myRandomTopic = `topic ${Utils.getCurrentTimestampInSecond()}`; + const myRandomTopic = `topic ${getCurrentTimestampInSecond()}`; const requestNetwork = new RequestNetwork({ httpConfig, decryptionProvider, diff --git a/packages/payment-detection/src/any-to-any-detector.ts b/packages/payment-detection/src/any-to-any-detector.ts index e760cd1e6..1e135712f 100644 --- a/packages/payment-detection/src/any-to-any-detector.ts +++ b/packages/payment-detection/src/any-to-any-detector.ts @@ -1,8 +1,7 @@ import { ExtensionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { FeeReferenceBasedDetector } from './fee-reference-based-detector'; - import { ICurrencyManager } from '@requestnetwork/currency'; +import { generate8randomBytes } from '@requestnetwork/utils'; /** * Abstract class to extend to get the payment balance of conversion requests @@ -34,7 +33,7 @@ export abstract class AnyToAnyDetector< ): Promise { // If no salt is given, generate one paymentNetworkCreationParameters.salt = - paymentNetworkCreationParameters.salt || (await Utils.crypto.generate8randomBytes()); + paymentNetworkCreationParameters.salt || (await generate8randomBytes()); return this.extension.createCreationAction(paymentNetworkCreationParameters); } diff --git a/packages/payment-detection/src/any/any-to-erc20-proxy.ts b/packages/payment-detection/src/any/any-to-erc20-proxy.ts index 2ff462823..9e336cc8c 100644 --- a/packages/payment-detection/src/any/any-to-erc20-proxy.ts +++ b/packages/payment-detection/src/any/any-to-erc20-proxy.ts @@ -1,11 +1,11 @@ import { erc20ConversionProxy } from '@requestnetwork/smart-contracts'; import { ExtensionTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { ERC20FeeProxyPaymentDetectorBase } from '../erc20/fee-proxy-contract'; import { AnyToErc20InfoRetriever } from './retrievers/any-to-erc20-proxy'; import { TheGraphInfoRetriever } from '../thegraph'; import { makeGetDeploymentInformation } from '../utils'; import { PaymentNetworkOptions, ReferenceBasedDetectorOptions } from '../types'; +import { generate8randomBytes } from '@requestnetwork/utils'; const PROXY_CONTRACT_ADDRESS_MAP = { ['0.1.0']: '0.1.0', @@ -48,8 +48,7 @@ export class AnyToERC20PaymentDetector extends ERC20FeeProxyPaymentDetectorBase< paymentNetworkCreationParameters: PaymentTypes.IAnyToErc20CreationParameters, ): Promise { // If no salt is given, generate one - const salt = - paymentNetworkCreationParameters.salt || (await Utils.crypto.generate8randomBytes()); + const salt = paymentNetworkCreationParameters.salt || (await generate8randomBytes()); return this.extension.createCreationAction({ feeAddress: paymentNetworkCreationParameters.feeAddress, diff --git a/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts b/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts index b8e3f42ed..adba109f1 100644 --- a/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts +++ b/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts @@ -1,9 +1,9 @@ import { CurrencyDefinition } from '@requestnetwork/currency'; import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { BigNumber, ethers } from 'ethers'; import { parseLogArgs, unpadAmountFromChainlink } from '../../utils'; import type { JsonFragment } from '@ethersproject/abi'; +import { getDefaultProvider } from '../../index'; /** TransferWithConversionAndReference event */ type TransferWithConversionAndReferenceArgs = { @@ -53,7 +53,7 @@ export abstract class ConversionInfoRetriever { protected maxRateTimespan: number = 0, ) { // Creates a local or default provider - this.provider = Utils.getDefaultProvider(this.network); + this.provider = getDefaultProvider(this.network); // Setup the conversion proxy contract interface this.contractConversionProxy = new ethers.Contract( diff --git a/packages/payment-detection/src/btc/default-providers/blockchain-info.ts b/packages/payment-detection/src/btc/default-providers/blockchain-info.ts index 19a37a7c2..941963301 100644 --- a/packages/payment-detection/src/btc/default-providers/blockchain-info.ts +++ b/packages/payment-detection/src/btc/default-providers/blockchain-info.ts @@ -1,8 +1,8 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const BLOCKCHAININFO_REQUEST_MAX_RETRY = 3; @@ -34,7 +34,7 @@ export class BlockchainInfoProvider implements PaymentTypes.IBitcoinDetectionPro const queryUrl = `${blockchainInfoUrl}/rawaddr/${address}?cors=true`; try { - const res = await Utils.retry(async () => Axios.get(queryUrl), { + const res = await retry(async () => Axios.get(queryUrl), { maxRetries: BLOCKCHAININFO_REQUEST_MAX_RETRY, retryDelay: BLOCKCHAININFO_REQUEST_RETRY_DELAY, })(); @@ -50,7 +50,7 @@ export class BlockchainInfoProvider implements PaymentTypes.IBitcoinDetectionPro // get all the transactions from the whole pagination for (let i = 1; i <= numberOfExtraPages; i++) { - const resExtraPage = await Utils.retry( + const resExtraPage = await retry( async () => fetch(`${blockchainInfoUrl}/rawaddr/${address}?cors=true&offset=${i * TXS_PER_PAGE}`), { diff --git a/packages/payment-detection/src/btc/default-providers/blockcypher-com.ts b/packages/payment-detection/src/btc/default-providers/blockcypher-com.ts index a161e6150..e9914b2d0 100644 --- a/packages/payment-detection/src/btc/default-providers/blockcypher-com.ts +++ b/packages/payment-detection/src/btc/default-providers/blockcypher-com.ts @@ -1,7 +1,7 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const BLOCKCYPHER_REQUEST_MAX_RETRY = 3; @@ -29,7 +29,7 @@ export class BlockcypherComProvider implements PaymentTypes.IBitcoinDetectionPro const baseUrl = this.getBaseUrl(bitcoinNetworkId); const queryUrl = `${baseUrl}/addrs/${address}`; try { - const res = await Utils.retry(async () => Axios.get(queryUrl), { + const res = await retry(async () => Axios.get(queryUrl), { maxRetries: BLOCKCYPHER_REQUEST_MAX_RETRY, retryDelay: BLOCKCYPHER_REQUEST_RETRY_DELAY, })(); diff --git a/packages/payment-detection/src/btc/default-providers/blockstream-info.ts b/packages/payment-detection/src/btc/default-providers/blockstream-info.ts index 4d7d4290a..83ec48fa7 100644 --- a/packages/payment-detection/src/btc/default-providers/blockstream-info.ts +++ b/packages/payment-detection/src/btc/default-providers/blockstream-info.ts @@ -1,7 +1,7 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const BLOCKSTREAMINFO_REQUEST_MAX_RETRY = 3; @@ -32,7 +32,7 @@ export class BlockStreamInfoProvider implements PaymentTypes.IBitcoinDetectionPr const baseUrl = this.getBaseUrl(bitcoinNetworkId); const queryUrl = `${baseUrl}/address/${address}/txs`; try { - const res = await Utils.retry(async () => Axios.get(queryUrl), { + const res = await retry(async () => Axios.get(queryUrl), { maxRetries: BLOCKSTREAMINFO_REQUEST_MAX_RETRY, retryDelay: BLOCKSTREAMINFO_REQUEST_RETRY_DELAY, })(); @@ -48,7 +48,7 @@ export class BlockStreamInfoProvider implements PaymentTypes.IBitcoinDetectionPr while (checkForMoreTransactions) { const lastTxHash = txs[txs.length - 1].txid; - const resExtraPage = await Utils.retry( + const resExtraPage = await retry( async () => fetch(`${baseUrl}/address/${address}/txs/chain/${lastTxHash}`), { maxRetries: BLOCKSTREAMINFO_REQUEST_MAX_RETRY, diff --git a/packages/payment-detection/src/btc/default-providers/chain-so.ts b/packages/payment-detection/src/btc/default-providers/chain-so.ts index 6ac867f73..8258ce457 100644 --- a/packages/payment-detection/src/btc/default-providers/chain-so.ts +++ b/packages/payment-detection/src/btc/default-providers/chain-so.ts @@ -1,8 +1,8 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Axios from 'axios'; import * as converterBTC from 'satoshi-bitcoin'; import { BigNumber } from 'ethers'; +import { retry } from '@requestnetwork/utils'; // Maximum number of api requests to retry when an error is encountered (ECONNRESET, EPIPE, ENOTFOUND) const CHAINSO_REQUEST_MAX_RETRY = 3; @@ -31,7 +31,7 @@ export class ChainSoProvider implements PaymentTypes.IBitcoinDetectionProvider { const queryUrl = `${baseUrl}${address}`; try { - const res = await Utils.retry(async () => Axios.get(queryUrl), { + const res = await retry(async () => Axios.get(queryUrl), { maxRetries: CHAINSO_REQUEST_MAX_RETRY, retryDelay: CHAINSO_REQUEST_RETRY_DELAY, })(); diff --git a/packages/payment-detection/src/declarative.ts b/packages/payment-detection/src/declarative.ts index 9a799e64b..c138c985d 100644 --- a/packages/payment-detection/src/declarative.ts +++ b/packages/payment-detection/src/declarative.ts @@ -4,8 +4,8 @@ import { PaymentTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { PaymentDetectorBase } from './payment-detector-base'; +import { notNull } from '@requestnetwork/utils'; /** * Handles payment detection for a declarative request, or derived. @@ -184,7 +184,7 @@ export abstract class DeclarativePaymentDetectorBase< } return null; }) - .filter(Utils.notNull); + .filter(notNull); } } diff --git a/packages/payment-detection/src/erc20/address-based-info-retriever.ts b/packages/payment-detection/src/erc20/address-based-info-retriever.ts index 85cf51921..d8dec80d4 100644 --- a/packages/payment-detection/src/erc20/address-based-info-retriever.ts +++ b/packages/payment-detection/src/erc20/address-based-info-retriever.ts @@ -1,7 +1,7 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { IPaymentRetriever } from '../types'; import { ethers } from 'ethers'; +import { getDefaultProvider } from '@requestnetwork/utils'; // The ERC20 smart contract ABI fragment containing decimals property and Transfer event const erc20BalanceOfAbiFragment = [ @@ -69,7 +69,7 @@ export default class ERC20InfoRetriever */ public async getTransferEvents(): Promise { // Creates a local or default provider - const provider = Utils.getDefaultProvider(this.network); + const provider = getDefaultProvider(this.network); // Set up the ERC20 contract interface const contract = new ethers.Contract( diff --git a/packages/payment-detection/src/erc20/currency.ts b/packages/payment-detection/src/erc20/currency.ts index 13508da64..68b8888a1 100644 --- a/packages/payment-detection/src/erc20/currency.ts +++ b/packages/payment-detection/src/erc20/currency.ts @@ -1,4 +1,3 @@ -import { utils } from 'ethers'; import { CurrencyDefinition, CurrencyManager, @@ -7,20 +6,18 @@ import { } from '@requestnetwork/currency'; import { RequestLogicTypes } from '@requestnetwork/types'; import { ERC20__factory } from '@requestnetwork/smart-contracts/types'; -import Utils from '@requestnetwork/utils'; +import { isAddress } from 'ethers/lib/utils'; +import { getDefaultProvider } from '@requestnetwork/utils'; export const loadCurrencyFromContract = async ( currency: StorageCurrency, ): Promise => { - if (!currency.network || !utils.isAddress(currency.value)) { + if (!currency.network || !isAddress(currency.value)) { return null; } try { - const contract = ERC20__factory.connect( - currency.value, - Utils.getDefaultProvider(currency.network), - ); + const contract = ERC20__factory.connect(currency.value, getDefaultProvider(currency.network)); const decimals = await contract.decimals(); if (!decimals) { diff --git a/packages/payment-detection/src/erc20/escrow-info-retriever.ts b/packages/payment-detection/src/erc20/escrow-info-retriever.ts index 4fff9e8ad..2f128d97e 100644 --- a/packages/payment-detection/src/erc20/escrow-info-retriever.ts +++ b/packages/payment-detection/src/erc20/escrow-info-retriever.ts @@ -1,9 +1,9 @@ import { PaymentTypes } from '@requestnetwork/types'; import { erc20EscrowToPayArtifact } from '@requestnetwork/smart-contracts'; -import Utils from '@requestnetwork/utils'; import { BigNumber, ethers } from 'ethers'; import { IEventRetriever } from '../types'; import { makeGetDeploymentInformation, parseLogArgs } from '../utils'; +import { getDefaultProvider } from '@requestnetwork/utils'; const ESCROW_CONTRACT_ADDRESS_MAP = { ['0.1.0']: '0.1.0', @@ -55,7 +55,7 @@ export class EscrowERC20InfoRetriever private eventName?: PaymentTypes.ESCROW_EVENTS_NAMES, ) { // Creates a local or default provider. - this.provider = Utils.getDefaultProvider(this.network); + this.provider = getDefaultProvider(this.network); // Set up the ERC20 escrow contract interface. this.contractEscrow = new ethers.Contract( diff --git a/packages/payment-detection/src/erc20/proxy-info-retriever.ts b/packages/payment-detection/src/erc20/proxy-info-retriever.ts index 41a0cae66..2ce08aa64 100644 --- a/packages/payment-detection/src/erc20/proxy-info-retriever.ts +++ b/packages/payment-detection/src/erc20/proxy-info-retriever.ts @@ -1,8 +1,8 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { IPaymentRetriever } from '../types'; import { BigNumber, ethers } from 'ethers'; import { parseLogArgs } from '../utils'; +import { getDefaultProvider } from '@requestnetwork/utils'; // The ERC20 proxy smart contract ABI fragment containing TransferWithReference event const erc20proxyContractAbiFragment = [ @@ -52,7 +52,7 @@ export default class ProxyERC20InfoRetriever private network: string, ) { // Creates a local or default provider - this.provider = Utils.getDefaultProvider(this.network); + this.provider = getDefaultProvider(this.network); // Set up the ERC20 proxy contract interface this.contractProxy = new ethers.Contract( diff --git a/packages/payment-detection/src/erc777/superfluid-retriever.ts b/packages/payment-detection/src/erc777/superfluid-retriever.ts index 609005216..ff21683f4 100644 --- a/packages/payment-detection/src/erc777/superfluid-retriever.ts +++ b/packages/payment-detection/src/erc777/superfluid-retriever.ts @@ -1,11 +1,11 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { FlowUpdatedEvent, SentEvent } from '../thegraph/generated/graphql-superfluid'; import { getTheGraphSuperfluidClient, TheGraphSuperfluidClient, TheGraphClientOptions, } from '../thegraph/superfluid'; +import { getCurrentTimestampInSecond } from '@requestnetwork/utils'; /** Parameters for getting payment events from theGraph */ type GraphPaymentQueryParams = { @@ -96,7 +96,7 @@ export class SuperFluidInfoRetriever { streamEvents.push({ oldFlowRate: streamEvents[streamEvents.length - 1].flowRate, flowRate: 0, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), blockNumber: parseInt(streamEvents[streamEvents.length - 1].blockNumber.toString()), transactionHash: streamEvents[streamEvents.length - 1].transactionHash, } as FlowUpdatedEvent); diff --git a/packages/payment-detection/src/eth/proxy-info-retriever.ts b/packages/payment-detection/src/eth/proxy-info-retriever.ts index cca9da8ee..789cefdd2 100644 --- a/packages/payment-detection/src/eth/proxy-info-retriever.ts +++ b/packages/payment-detection/src/eth/proxy-info-retriever.ts @@ -1,8 +1,8 @@ import { PaymentTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { IPaymentRetriever } from '../types'; import { BigNumber, ethers } from 'ethers'; import { parseLogArgs } from '../utils'; +import { getDefaultProvider } from '@requestnetwork/utils'; // The Ethereum proxy smart contract ABI fragment containing TransferWithReference event const ethProxyContractAbiFragment = [ @@ -49,7 +49,7 @@ export class EthProxyInfoRetriever private network: string, ) { // Creates a local or default provider - this.provider = Utils.getDefaultProvider(this.network); + this.provider = getDefaultProvider(this.network); // Set up the Ethereum proxy contract interface this.contractProxy = new ethers.Contract( diff --git a/packages/payment-detection/src/fee-reference-based-detector.ts b/packages/payment-detection/src/fee-reference-based-detector.ts index 7df572426..1922c6563 100644 --- a/packages/payment-detection/src/fee-reference-based-detector.ts +++ b/packages/payment-detection/src/fee-reference-based-detector.ts @@ -1,8 +1,8 @@ import { BigNumber } from 'ethers'; import { ExtensionTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types'; import { ICurrencyManager } from '@requestnetwork/currency'; -import Utils from '@requestnetwork/utils'; import { ReferenceBasedDetector } from './reference-based-detector'; +import { generate8randomBytes } from '@requestnetwork/utils'; /** * Abstract class to extend to get the payment balance of reference based requests @@ -38,7 +38,7 @@ export abstract class FeeReferenceBasedDetector< ): Promise { // If no salt is given, generate one paymentNetworkCreationParameters.salt = - paymentNetworkCreationParameters.salt || (await Utils.crypto.generate8randomBytes()); + paymentNetworkCreationParameters.salt || (await generate8randomBytes()); return this.extension.createCreationAction({ feeAddress: paymentNetworkCreationParameters.feeAddress, diff --git a/packages/payment-detection/src/index.ts b/packages/payment-detection/src/index.ts index 6dd873651..3ba743999 100644 --- a/packages/payment-detection/src/index.ts +++ b/packages/payment-detection/src/index.ts @@ -1,4 +1,8 @@ -import Utils from '@requestnetwork/utils'; +import { + getDefaultProvider, + initPaymentDetectionApiKeys, + setProviderFactory, +} from '@requestnetwork/utils'; import { PaymentNetworkFactory } from './payment-network-factory'; import PaymentReferenceCalculator from './payment-reference-calculator'; import * as BtcPaymentNetwork from './btc'; @@ -25,10 +29,6 @@ import { PaymentNetworkOptions } from './types'; export type { TheGraphClient } from './thegraph'; -const setProviderFactory = Utils.setProviderFactory; -const initPaymentDetectionApiKeys = Utils.initPaymentDetectionApiKeys; -const getDefaultProvider = Utils.getDefaultProvider; - export { PaymentNetworkFactory, PaymentNetworkOptions, diff --git a/packages/payment-detection/src/payment-network-factory.ts b/packages/payment-detection/src/payment-network-factory.ts index 904485b1c..8204115fb 100644 --- a/packages/payment-detection/src/payment-network-factory.ts +++ b/packages/payment-detection/src/payment-network-factory.ts @@ -4,7 +4,6 @@ import { PaymentTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { ICurrencyManager } from '@requestnetwork/currency'; import { ContractBasedDetector, @@ -25,6 +24,7 @@ import { AnyToERC20PaymentDetector, AnyToEthFeeProxyPaymentDetector } from './an import { NearConversionNativeTokenPaymentDetector, NearNativeTokenPaymentDetector } from './near'; import { getPaymentNetworkExtension } from './utils'; import { getTheGraphClient } from './thegraph'; +import { getDefaultProvider } from 'ethers'; const PN_ID = ExtensionTypes.PAYMENT_NETWORK_ID; @@ -99,7 +99,7 @@ export class PaymentNetworkFactory { ); }, explorerApiKeys: {}, - getRpcProvider: Utils.getDefaultProvider, + getRpcProvider: getDefaultProvider, }; return { ...defaultOptions, ...options }; } diff --git a/packages/payment-detection/src/payment-reference-calculator.ts b/packages/payment-detection/src/payment-reference-calculator.ts index 842b98518..59be64543 100644 --- a/packages/payment-detection/src/payment-reference-calculator.ts +++ b/packages/payment-detection/src/payment-reference-calculator.ts @@ -1,4 +1,4 @@ -import Utils from '@requestnetwork/utils'; +import { keccak256Hash } from '@requestnetwork/utils'; /** * Compute the payment reference @@ -7,13 +7,14 @@ import Utils from '@requestnetwork/utils'; * @param salt The salt for the request * @param address Payment or refund address */ + function calculate(requestId: string, salt: string, address: string): string { if (!requestId || !salt || !address) { throw new Error('RequestId, salt and address are mandatory to calculate the payment reference'); } // "The value is the last 8 bytes of a salted hash of the requestId: `last8Bytes(hash(requestId + salt + address))`" /* eslint-disable no-magic-numbers */ - return Utils.crypto.keccak256Hash((requestId + salt + address).toLowerCase()).slice(-16); + return keccak256Hash((requestId + salt + address).toLowerCase()).slice(-16); } export default { calculate }; diff --git a/packages/payment-detection/src/reference-based-detector.ts b/packages/payment-detection/src/reference-based-detector.ts index 111d95326..934e2c34e 100644 --- a/packages/payment-detection/src/reference-based-detector.ts +++ b/packages/payment-detection/src/reference-based-detector.ts @@ -1,9 +1,9 @@ import { ExtensionTypes, PaymentTypes, RequestLogicTypes, TypesUtils } from '@requestnetwork/types'; import { ICurrencyManager } from '@requestnetwork/currency'; -import Utils from '@requestnetwork/utils'; import PaymentReferenceCalculator from './payment-reference-calculator'; import { DeclarativePaymentDetectorBase } from './declarative'; +import { generate8randomBytes } from '@requestnetwork/utils'; /** * Abstract class to extend to get the payment balance of reference based requests @@ -45,7 +45,7 @@ export abstract class ReferenceBasedDetector< ): Promise { // If no salt is given, generate one paymentNetworkCreationParameters.salt = - paymentNetworkCreationParameters.salt || (await Utils.crypto.generate8randomBytes()); + paymentNetworkCreationParameters.salt || (await generate8randomBytes()); return this.extension.createCreationAction({ paymentAddress: paymentNetworkCreationParameters.paymentAddress, diff --git a/packages/payment-processor/test/payment/any-to-erc20-batch-proxy.test.ts b/packages/payment-processor/test/payment/any-to-erc20-batch-proxy.test.ts index 773bc66dd..14e521603 100644 --- a/packages/payment-processor/test/payment/any-to-erc20-batch-proxy.test.ts +++ b/packages/payment-processor/test/payment/any-to-erc20-batch-proxy.test.ts @@ -7,7 +7,7 @@ import { RequestLogicTypes, } from '@requestnetwork/types'; import { getErc20Balance } from '../../src/payment/erc20'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { revokeErc20Approval } from '@requestnetwork/payment-processor/src/payment/utils'; import { EnrichedRequest, IConversionPaymentSettings } from '../../src/index'; import { batchConversionPaymentsArtifact } from '@requestnetwork/smart-contracts'; @@ -59,7 +59,7 @@ const paymentSettings: IConversionPaymentSettings = { currencyManager: currencyManager, }; -const conversionPaymentSettings = Utils.deepCopy(paymentSettings); +const conversionPaymentSettings = deepCopy(paymentSettings); // conversionPaymentSettings.currencyManager = undefined; const options: IRequestPaymentOptions = { @@ -165,7 +165,7 @@ const DAIValidRequest: ClientTypes.IRequestData = { version: '1.0', }; -const FAUValidRequest = Utils.deepCopy(DAIValidRequest) as ClientTypes.IRequestData; +const FAUValidRequest = deepCopy(DAIValidRequest) as ClientTypes.IRequestData; FAUValidRequest.currencyInfo = { network: 'private', type: RequestLogicTypes.CURRENCY.ERC20 as any, @@ -220,7 +220,7 @@ describe('erc20-batch-conversion-proxy', () => { describe(`Conversion:`, () => { beforeEach(() => { jest.restoreAllMocks(); - EURRequest = Utils.deepCopy(EURValidRequest); + EURRequest = deepCopy(EURValidRequest); enrichedRequests = [ { paymentNetworkId: ExtensionTypes.PAYMENT_NETWORK_ID.ANY_TO_ERC20_PROXY, @@ -263,7 +263,7 @@ describe('erc20-batch-conversion-proxy', () => { ); }); it('should throw an error if request has no currency within paymentSettings', async () => { - const wrongPaymentSettings = Utils.deepCopy(conversionPaymentSettings); + const wrongPaymentSettings = deepCopy(conversionPaymentSettings); wrongPaymentSettings.currency = undefined; await expect( payBatchConversionProxyRequest( @@ -546,7 +546,7 @@ describe('erc20-batch-conversion-proxy', () => { describe('No conversion:', () => { beforeEach(() => { - FAURequest = Utils.deepCopy(FAUValidRequest); + FAURequest = deepCopy(FAUValidRequest); enrichedRequests = [ { paymentNetworkId: ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_FEE_PROXY_CONTRACT, diff --git a/packages/payment-processor/test/payment/any-to-erc20-proxy.test.ts b/packages/payment-processor/test/payment/any-to-erc20-proxy.test.ts index da95d9f1b..48822ca8d 100644 --- a/packages/payment-processor/test/payment/any-to-erc20-proxy.test.ts +++ b/packages/payment-processor/test/payment/any-to-erc20-proxy.test.ts @@ -1,14 +1,11 @@ import { Wallet, providers, BigNumber } from 'ethers'; - import { ClientTypes, ExtensionTypes, IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; - -import Utils from '@requestnetwork/utils'; - +import { deepCopy } from '@requestnetwork/utils'; import { approveErc20ForProxyConversionIfNeeded } from '../../src/payment/conversion-erc20'; import { payAnyToErc20ProxyRequest } from '../../src/payment/any-to-erc20-proxy'; import { ERC20__factory } from '@requestnetwork/smart-contracts/types'; @@ -116,7 +113,7 @@ describe('conversion-erc20-fee-proxy', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validEuroRequest); + const request = deepCopy(validEuroRequest); request.extensions = [] as any; await expect( diff --git a/packages/payment-processor/test/payment/any-to-eth-proxy.test.ts b/packages/payment-processor/test/payment/any-to-eth-proxy.test.ts index c48df462a..9ce12f0b2 100644 --- a/packages/payment-processor/test/payment/any-to-eth-proxy.test.ts +++ b/packages/payment-processor/test/payment/any-to-eth-proxy.test.ts @@ -1,17 +1,15 @@ import { Wallet, providers } from 'ethers'; - import { ClientTypes, ExtensionTypes, IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; - -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { payAnyToEthProxyRequest } from '../../src/payment/any-to-eth-proxy'; import { currencyManager } from './shared'; - import { IConversionPaymentSettings } from '../../src/index'; + const paymentSettings: IConversionPaymentSettings = { maxToSpend: '2500000000000000', currencyManager, @@ -70,7 +68,7 @@ const validEuroRequest: ClientTypes.IRequestData = { describe('any-to-eth-proxy', () => { describe('error checking', () => { it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validEuroRequest); + const request = deepCopy(validEuroRequest); request.extensions = [] as any; await expect(payAnyToEthProxyRequest(request, wallet, paymentSettings)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/erc20-batch-proxy.test.ts b/packages/payment-processor/test/payment/erc20-batch-proxy.test.ts index 6a7e977ea..800685317 100644 --- a/packages/payment-processor/test/payment/erc20-batch-proxy.test.ts +++ b/packages/payment-processor/test/payment/erc20-batch-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { batchPaymentsArtifact } from '@requestnetwork/smart-contracts'; import { getErc20Balance } from '../../src/payment/erc20'; @@ -74,7 +74,7 @@ const validRequest: ClientTypes.IRequestData = { version: '1.0', }; -const fauValidRequest = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; +const fauValidRequest = deepCopy(validRequest) as ClientTypes.IRequestData; fauValidRequest.currencyInfo = { network: 'private', type: RequestLogicTypes.CURRENCY.ERC20 as any, @@ -115,8 +115,8 @@ const testSuite = ( beforeEach(() => { jest.restoreAllMocks(); - request1 = Utils.deepCopy(requestTemplate1) as ClientTypes.IRequestData; - request2 = Utils.deepCopy(requestTemplate2) as ClientTypes.IRequestData; + request1 = deepCopy(requestTemplate1) as ClientTypes.IRequestData; + request2 = deepCopy(requestTemplate2) as ClientTypes.IRequestData; }); it('should throw an error if the request is not erc20', async () => { @@ -206,7 +206,7 @@ const testSuite = ( it('should pay an ERC20 request with fees', async () => { // first approve the contract - const tmpRequest = Utils.deepCopy(request1); + const tmpRequest = deepCopy(request1); let amount = 1000; const isMultiToken = !sameCurrencyValue(request1, request2); diff --git a/packages/payment-processor/test/payment/erc20-escrow-payment.test.ts b/packages/payment-processor/test/payment/erc20-escrow-payment.test.ts index 3b9bef071..1391f5008 100644 --- a/packages/payment-processor/test/payment/erc20-escrow-payment.test.ts +++ b/packages/payment-processor/test/payment/erc20-escrow-payment.test.ts @@ -5,7 +5,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { Escrow } from '../../src/'; import { getRequestPaymentValues, getSigner } from '../../src/payment/utils'; @@ -86,7 +86,7 @@ describe('erc20-escrow-payment tests:', () => { expect(values.paymentReference).toBe(paymentReference); }); it('Should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect(Escrow.payEscrow(request, wallet)).rejects.toThrowError( @@ -94,21 +94,21 @@ describe('erc20-escrow-payment tests:', () => { ); }); it('Should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect(Escrow.payEscrow(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-fee-proxy-contract request', ); }); it('Should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(Escrow.payEscrow(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-fee-proxy-contract request', ); }); it('Should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(Escrow.payEscrow(request, wallet)).rejects.toThrowError( @@ -203,7 +203,7 @@ describe('erc20-escrow-payment tests:', () => { describe('Normal Flow:', () => { it('Should pay the amount and fee from payers account', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; const payerBeforeBalance = await getErc20Balance(request, payerAddress); const escrowBeforeBalance = await getErc20Balance(request, escrowAddress); @@ -228,7 +228,7 @@ describe('erc20-escrow-payment tests:', () => { }); it('Should withdraw funds and pay funds from escrow to payee', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aabb'; // Execute payEscrow @@ -258,7 +258,7 @@ describe('erc20-escrow-payment tests:', () => { describe('Emergency Flow:', () => { it('Should initiate emergency claim', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aacc'; // Assign the paymentAddress as the payee. @@ -277,7 +277,7 @@ describe('erc20-escrow-payment tests:', () => { }); it('Should revert emergency claim', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aadd'; // Assign the paymentAddress as the payee. @@ -304,7 +304,7 @@ describe('erc20-escrow-payment tests:', () => { describe('Freeze Request Flow:', () => { it('Should freeze funds:', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aaee'; // Execute payEscrow function on smart contract. @@ -320,7 +320,7 @@ describe('erc20-escrow-payment tests:', () => { }); it('Should revert if tried to withdraw to early:', async () => { // Set a new requestID to test independent unit-tests. - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.requestId = 'aaff'; // Execute payEscrow. diff --git a/packages/payment-processor/test/payment/erc20-fee-proxy.test.ts b/packages/payment-processor/test/payment/erc20-fee-proxy.test.ts index 2c2003feb..592b5a527 100644 --- a/packages/payment-processor/test/payment/erc20-fee-proxy.test.ts +++ b/packages/payment-processor/test/payment/erc20-fee-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { erc20FeeProxyArtifact } from '@requestnetwork/smart-contracts'; import { approveErc20, getErc20Balance } from '../../src/payment/erc20'; @@ -88,7 +88,7 @@ describe('erc20-fee-proxy', () => { describe('encodePayErc20FeeRequest (used to pay and swap to pay)', () => { it('should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect(payErc20FeeProxyRequest(request, wallet)).rejects.toThrowError( @@ -97,7 +97,7 @@ describe('erc20-fee-proxy', () => { }); it('should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect(payErc20FeeProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-fee-proxy-contract request', @@ -105,7 +105,7 @@ describe('erc20-fee-proxy', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payErc20FeeProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-fee-proxy-contract request', @@ -113,7 +113,7 @@ describe('erc20-fee-proxy', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payErc20FeeProxyRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/erc20-proxy.test.ts b/packages/payment-processor/test/payment/erc20-proxy.test.ts index 9356a02d0..5139c18ef 100644 --- a/packages/payment-processor/test/payment/erc20-proxy.test.ts +++ b/packages/payment-processor/test/payment/erc20-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { approveErc20, getErc20Balance } from '../../src/payment/erc20'; import { _getErc20ProxyPaymentUrl, payErc20ProxyRequest } from '../../src/payment/erc20-proxy'; import { getRequestPaymentValues } from '../../src/payment/utils'; @@ -73,7 +73,7 @@ describe('getRequestPaymentValues', () => { describe('payErc20ProxyRequest', () => { it('should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect(payErc20ProxyRequest(request, wallet)).rejects.toThrowError( @@ -82,7 +82,7 @@ describe('payErc20ProxyRequest', () => { }); it('should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect(payErc20ProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-proxy-contract request', @@ -90,7 +90,7 @@ describe('payErc20ProxyRequest', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payErc20ProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc20-proxy-contract request', @@ -98,7 +98,7 @@ describe('payErc20ProxyRequest', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payErc20ProxyRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/erc777-stream.test.ts b/packages/payment-processor/test/payment/erc777-stream.test.ts index 468ed981f..2b01b425d 100644 --- a/packages/payment-processor/test/payment/erc777-stream.test.ts +++ b/packages/payment-processor/test/payment/erc777-stream.test.ts @@ -7,7 +7,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { closeErc777StreamRequest, @@ -91,7 +91,7 @@ describe('erc777-stream', () => { describe('encodePayErc20FeeRequest (used to pay and swap to pay)', () => { it('should throw an error if the request is not erc777', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect(payErc777StreamRequest(request, wallet)).rejects.toThrowError( @@ -100,7 +100,7 @@ describe('erc777-stream', () => { }); it('should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect(payErc777StreamRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc777-stream request', @@ -108,7 +108,7 @@ describe('erc777-stream', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payErc777StreamRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-erc777-stream request', @@ -116,7 +116,7 @@ describe('erc777-stream', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payErc777StreamRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/eth-batch-proxy.test.ts b/packages/payment-processor/test/payment/eth-batch-proxy.test.ts index 86327cbc8..f44ae6fbe 100644 --- a/packages/payment-processor/test/payment/eth-batch-proxy.test.ts +++ b/packages/payment-processor/test/payment/eth-batch-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { payBatchProxyRequest, encodePayBatchRequest } from '../../src/payment/batch-proxy'; import { getRequestPaymentValues } from '../../src/payment/utils'; @@ -67,7 +67,7 @@ const validRequest: ClientTypes.IRequestData = { version: '2.0.3', }; -const validRequest2 = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; +const validRequest2 = deepCopy(validRequest) as ClientTypes.IRequestData; validRequest2.extensions = { [ExtensionTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], @@ -93,7 +93,7 @@ describe('getRequestPaymentValues', () => { describe('payBatchProxyRequest', () => { it('should throw an error if one request is not eth', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ERC20; await expect( @@ -104,7 +104,7 @@ describe('payBatchProxyRequest', () => { }); it('should throw an error if in one request, currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect( payBatchProxyRequest([validRequest, request], batchVersion, wallet, batchFee), @@ -114,7 +114,7 @@ describe('payBatchProxyRequest', () => { }); it('should throw an error if one request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect( diff --git a/packages/payment-processor/test/payment/eth-fee-proxy.test.ts b/packages/payment-processor/test/payment/eth-fee-proxy.test.ts index b46174a3e..5f39d8d0c 100644 --- a/packages/payment-processor/test/payment/eth-fee-proxy.test.ts +++ b/packages/payment-processor/test/payment/eth-fee-proxy.test.ts @@ -1,13 +1,11 @@ import { Wallet, providers } from 'ethers'; - import { ClientTypes, ExtensionTypes, IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; - +import { deepCopy } from '@requestnetwork/utils'; import { encodePayEthFeeProxyRequest, payEthFeeProxyRequest, @@ -77,7 +75,7 @@ describe('getRequestPaymentValues', () => { describe('payEthFeeProxyRequest', () => { it('should throw an error if the request is not eth', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ERC20; await expect(payEthFeeProxyRequest(request, wallet)).rejects.toThrowError( @@ -86,7 +84,7 @@ describe('payEthFeeProxyRequest', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payEthFeeProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-eth-fee-proxy-contract request', @@ -94,7 +92,7 @@ describe('payEthFeeProxyRequest', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payEthFeeProxyRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/eth-input-data.test.ts b/packages/payment-processor/test/payment/eth-input-data.test.ts index 5a52eeaca..f4eaefd64 100644 --- a/packages/payment-processor/test/payment/eth-input-data.test.ts +++ b/packages/payment-processor/test/payment/eth-input-data.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { _getEthPaymentUrl, payEthInputDataRequest } from '../../src/payment/eth-input-data'; import { getRequestPaymentValues } from '../../src/payment/utils'; @@ -72,7 +72,7 @@ describe('getRequestPaymentValues', () => { describe('payEthInputDataRequest', () => { it('should throw an error if the request is not eth', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ERC20; await expect(payEthInputDataRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-eth-input-data request', @@ -80,7 +80,7 @@ describe('payEthInputDataRequest', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payEthInputDataRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-eth-input-data request', @@ -88,7 +88,7 @@ describe('payEthInputDataRequest', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payEthInputDataRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/eth-proxy.test.ts b/packages/payment-processor/test/payment/eth-proxy.test.ts index 534b59231..979090db5 100644 --- a/packages/payment-processor/test/payment/eth-proxy.test.ts +++ b/packages/payment-processor/test/payment/eth-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { encodePayEthProxyRequest, @@ -76,7 +76,7 @@ describe('getRequestPaymentValues', () => { describe('payEthProxyRequest', () => { it('should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ERC20; await expect(payEthProxyRequest(request, wallet)).rejects.toThrowError( @@ -85,7 +85,7 @@ describe('payEthProxyRequest', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect(payEthProxyRequest(request, wallet)).rejects.toThrowError( 'request cannot be processed, or is not an pn-eth-input-data request', @@ -93,7 +93,7 @@ describe('payEthProxyRequest', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect(payEthProxyRequest(request, wallet)).rejects.toThrowError( diff --git a/packages/payment-processor/test/payment/swap-any-to-erc20.test.ts b/packages/payment-processor/test/payment/swap-any-to-erc20.test.ts index 886341368..a95aec8c2 100644 --- a/packages/payment-processor/test/payment/swap-any-to-erc20.test.ts +++ b/packages/payment-processor/test/payment/swap-any-to-erc20.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { approveErc20ForSwapWithConversionIfNeeded } from '../../src/payment/swap-conversion-erc20'; import { ERC20, ERC20__factory } from '@requestnetwork/smart-contracts/types'; @@ -111,7 +111,7 @@ describe('swap-any-to-erc20', () => { }); it('should throw an error if the payment network is wrong', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); delete request.extensions[ExtensionTypes.PAYMENT_NETWORK_ID.ANY_TO_ERC20_PROXY]; await expect( @@ -123,7 +123,7 @@ describe('swap-any-to-erc20', () => { }); it('should throw an error if the conversion path is impossible', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); (request.currencyInfo = { type: RequestLogicTypes.CURRENCY.ISO4217, value: 'XXX', diff --git a/packages/payment-processor/test/payment/swap-erc20-fee-proxy.test.ts b/packages/payment-processor/test/payment/swap-erc20-fee-proxy.test.ts index d39591704..dd5e5a74a 100644 --- a/packages/payment-processor/test/payment/swap-erc20-fee-proxy.test.ts +++ b/packages/payment-processor/test/payment/swap-erc20-fee-proxy.test.ts @@ -6,7 +6,7 @@ import { IdentityTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { getErc20Balance } from '../../src/payment/erc20'; import { approveErc20ForSwapToPayIfNeeded } from '../../src/payment/swap-erc20'; @@ -96,7 +96,7 @@ describe('swap-erc20-fee-proxy', () => { ); }); it('should throw an error if the request is not erc20', async () => { - const request = Utils.deepCopy(validRequest) as ClientTypes.IRequestData; + const request = deepCopy(validRequest) as ClientTypes.IRequestData; request.currencyInfo.type = RequestLogicTypes.CURRENCY.ETH; await expect( @@ -107,7 +107,7 @@ describe('swap-erc20-fee-proxy', () => { }); it('should throw an error if the currencyInfo has no value', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.value = ''; await expect( swapErc20FeeProxyRequest(request, wallet, validSwapSettings), @@ -117,7 +117,7 @@ describe('swap-erc20-fee-proxy', () => { }); it('should throw an error if currencyInfo has no network', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.currencyInfo.network = ''; await expect( swapErc20FeeProxyRequest(request, wallet, validSwapSettings), @@ -127,7 +127,7 @@ describe('swap-erc20-fee-proxy', () => { }); it('should throw an error if request has no extension', async () => { - const request = Utils.deepCopy(validRequest); + const request = deepCopy(validRequest); request.extensions = [] as any; await expect( diff --git a/packages/prototype-estimator/src/mock-storage.ts b/packages/prototype-estimator/src/mock-storage.ts index 54dfd9103..db4166116 100644 --- a/packages/prototype-estimator/src/mock-storage.ts +++ b/packages/prototype-estimator/src/mock-storage.ts @@ -1,7 +1,7 @@ import MultiFormat from '@requestnetwork/multi-format'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { EventEmitter } from 'events'; +import { getCurrentTimestampInSecond, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Storage layer implemented with in-memory hashmap, to be used for testing. @@ -23,9 +23,9 @@ export default class MockStorage implements StorageTypes.IStorage { if (!content) { throw Error('Error: no content provided'); } - const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(content)); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(content)); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); this.data[hash] = { content, @@ -84,7 +84,7 @@ export default class MockStorage implements StorageTypes.IStorage { }, })); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); return { entries, diff --git a/packages/request-client.js/src/api/request-network.ts b/packages/request-client.js/src/api/request-network.ts index 8e9a9fe78..a74c16faa 100644 --- a/packages/request-client.js/src/api/request-network.ts +++ b/packages/request-client.js/src/api/request-network.ts @@ -13,7 +13,7 @@ import { SignatureProviderTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy, supportedIdentities } from '@requestnetwork/utils'; import { CurrencyManager, ICurrencyManager, @@ -29,7 +29,7 @@ import localUtils from './utils'; */ export default class RequestNetwork { public paymentNetworkFactory: PaymentNetworkFactory; - public supportedIdentities: IdentityTypes.TYPE[] = Utils.identity.supportedIdentities; + public supportedIdentities: IdentityTypes.TYPE[] = supportedIdentities; private requestLogic: RequestLogicTypes.IRequestLogic; private transaction: TransactionTypes.ITransactionManager; @@ -388,7 +388,7 @@ export default class RequestNetwork { } // avoid mutation of the parameters - const copiedRequestParameters = Utils.deepCopy(requestParameters); + const copiedRequestParameters = deepCopy(requestParameters); copiedRequestParameters.extensionsData = []; const detectionChain = diff --git a/packages/request-client.js/src/api/request.ts b/packages/request-client.js/src/api/request.ts index e403fa0f4..9d236811b 100644 --- a/packages/request-client.js/src/api/request.ts +++ b/packages/request-client.js/src/api/request.ts @@ -1,16 +1,15 @@ import { EventEmitter } from 'events'; - import { DeclarativePaymentDetector, EscrowERC20InfoRetriever, } from '@requestnetwork/payment-detection'; import { IdentityTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types'; import { ICurrencyManager } from '@requestnetwork/currency'; -import Utils from '@requestnetwork/utils'; import * as Types from '../types'; import ContentDataExtension from './content-data-extension'; import localUtils from './utils'; import { erc20EscrowToPayArtifact } from '@requestnetwork/smart-contracts'; +import { deepCopy } from '@requestnetwork/utils'; /** * Class representing a request. @@ -631,9 +630,9 @@ export default class Request { throw Error('request confirmation failed'); } - let requestData = Utils.deepCopy(this.requestData); + let requestData = deepCopy(this.requestData); - let pending = Utils.deepCopy(this.pendingData); + let pending = deepCopy(this.pendingData); if (!requestData) { requestData = pending as RequestLogicTypes.IRequest; requestData.state = RequestLogicTypes.STATE.PENDING; diff --git a/packages/request-client.js/src/api/utils.ts b/packages/request-client.js/src/api/utils.ts index 7712094bf..4eee0e979 100644 --- a/packages/request-client.js/src/api/utils.ts +++ b/packages/request-client.js/src/api/utils.ts @@ -1,5 +1,5 @@ import { RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { getCurrentTimestampInSecond } from '@requestnetwork/utils'; /** * Collection of utils functions related to the library, meant to simplify its use. */ @@ -11,7 +11,7 @@ export default { * * @returns current timestamp in second */ - getCurrentTimestampInSecond: Utils.getCurrentTimestampInSecond, + getCurrentTimestampInSecond, }; /** diff --git a/packages/request-client.js/src/http-data-access.ts b/packages/request-client.js/src/http-data-access.ts index bb4f64613..cf4397669 100644 --- a/packages/request-client.js/src/http-data-access.ts +++ b/packages/request-client.js/src/http-data-access.ts @@ -1,9 +1,9 @@ import { ClientTypes, DataAccessTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import axios, { AxiosRequestConfig } from 'axios'; import { EventEmitter } from 'events'; import httpConfigDefaults from './http-config-defaults'; +import { normalizeKeccak256Hash, retry } from '@requestnetwork/utils'; // eslint-disable-next-line @typescript-eslint/no-var-requires const packageJson = require('../package.json'); @@ -100,7 +100,7 @@ export default class HttpDataAccess implements DataAccessTypes.IDataAccess { this.axiosConfig, ); - const transactionHash: string = Utils.crypto.normalizeKeccak256Hash(transactionData).value; + const transactionHash: string = normalizeKeccak256Hash(transactionData).value; // Create the return result with EventEmitter const result: DataAccessTypes.IReturnPersistTransaction = Object.assign( @@ -203,7 +203,7 @@ export default class HttpDataAccess implements DataAccessTypes.IDataAccess { ): Promise { retryConfig.maxRetries = retryConfig.maxRetries ?? this.httpConfig.httpRequestMaxRetry; retryConfig.retryDelay = retryConfig.retryDelay ?? this.httpConfig.httpRequestRetryDelay; - const { data } = await Utils.retry( + const { data } = await retry( async () => axios.get(url, { ...this.axiosConfig, params }), retryConfig, )(); diff --git a/packages/request-client.js/src/http-metamask-data-access.ts b/packages/request-client.js/src/http-metamask-data-access.ts index dd13b9fc0..ca27f67cf 100644 --- a/packages/request-client.js/src/http-metamask-data-access.ts +++ b/packages/request-client.js/src/http-metamask-data-access.ts @@ -1,11 +1,11 @@ import { Block } from '@requestnetwork/data-access'; import { requestHashSubmitterArtifact } from '@requestnetwork/smart-contracts'; import { ClientTypes, DataAccessTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import axios, { AxiosRequestConfig } from 'axios'; import { ethers } from 'ethers'; import { EventEmitter } from 'events'; import HttpDataAccess from './http-data-access'; +import { retry } from '@requestnetwork/utils'; /** * Exposes a Data-Access module over HTTP @@ -187,7 +187,7 @@ export default class HttpMetaMaskDataAccess extends HttpDataAccess { channelId: string, timestampBoundaries?: DataAccessTypes.ITimestampBoundaries, ): Promise { - const { data } = await Utils.retry( + const { data } = await retry( async () => axios.get( '/getTransactionsByChannelId', diff --git a/packages/request-client.js/src/mock-storage.ts b/packages/request-client.js/src/mock-storage.ts index 3599ce963..6cfb0394d 100644 --- a/packages/request-client.js/src/mock-storage.ts +++ b/packages/request-client.js/src/mock-storage.ts @@ -1,7 +1,7 @@ import MultiFormat from '@requestnetwork/multi-format'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { EventEmitter } from 'events'; +import { getCurrentTimestampInSecond, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Storage layer implemented with in-memory hashmap, to be used for testing. @@ -23,9 +23,9 @@ export default class MockStorage implements StorageTypes.IStorage { if (!content) { throw Error('Error: no content provided'); } - const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(content)); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(content)); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); this.data.set(hash, { content, @@ -43,9 +43,9 @@ export default class MockStorage implements StorageTypes.IStorage { if (!content) { throw Error('Error: no content provided'); } - const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(content)); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(content)); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); const dataToStore = { content, @@ -117,7 +117,7 @@ export default class MockStorage implements StorageTypes.IStorage { }, })); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); return { entries, diff --git a/packages/request-client.js/test/api/request-network.test.ts b/packages/request-client.js/test/api/request-network.test.ts index d0b2aa281..fed1c9dd8 100644 --- a/packages/request-client.js/test/api/request-network.test.ts +++ b/packages/request-client.js/test/api/request-network.test.ts @@ -1,12 +1,12 @@ import MultiFormat from '@requestnetwork/multi-format'; import { DataAccessTypes, SignatureTypes, TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import RequestNetwork from '../../src/api/request-network'; import Request from '../../src/api/request'; import * as TestData from '../data-test'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; const mockDataAccess: DataAccessTypes.IDataAccess = { _getStatus: jest.fn(), @@ -59,7 +59,7 @@ describe('api/request-network', () => { timestamp: 1549953337, transaction: { data: 'broken transaction' }, }; - const actionWrongSigner = Utils.signature.sign(TestData.data, { + const actionWrongSigner = sign(TestData.data, { method: SignatureTypes.METHOD.ECDSA, privateKey: '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', }); @@ -71,9 +71,7 @@ describe('api/request-network', () => { data: JSON.stringify(actionWrongSigner), }, }; - const requestId = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(actionWrongSigner), - ); + const requestId = MultiFormat.serialize(normalizeKeccak256Hash(actionWrongSigner)); const mockDataAccessWithTxs: DataAccessTypes.IDataAccess = { ...mockDataAccess, diff --git a/packages/request-client.js/test/data-test-real-btc.ts b/packages/request-client.js/test/data-test-real-btc.ts index 8f22d3306..6ed341a2c 100644 --- a/packages/request-client.js/test/data-test-real-btc.ts +++ b/packages/request-client.js/test/data-test-real-btc.ts @@ -4,7 +4,7 @@ import { SignatureTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; const payee = { identity: { @@ -50,7 +50,7 @@ export const data = { version: '2.0.3', }; -export const action: RequestLogicTypes.IAction = Utils.signature.sign(data, payee.signatureParams); +export const action: RequestLogicTypes.IAction = sign(data, payee.signatureParams); export const timestampedTransaction: TransactionTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, diff --git a/packages/request-client.js/test/data-test.ts b/packages/request-client.js/test/data-test.ts index 42c8a3339..74b625611 100644 --- a/packages/request-client.js/test/data-test.ts +++ b/packages/request-client.js/test/data-test.ts @@ -8,7 +8,7 @@ import { SignatureTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; import AxiosMockAdapter from 'axios-mock-adapter'; import axios from 'axios'; import { Types } from '../src'; @@ -155,15 +155,12 @@ const dataWithDeclarativeNoPaymentInfo = { version: '2.0.3', }; -export const action: RequestLogicTypes.IAction = Utils.signature.sign( - dataWithDeclarative, - payee.signatureParams, -); -const actionWithoutExtensionsData: RequestLogicTypes.IAction = Utils.signature.sign( +export const action: RequestLogicTypes.IAction = sign(dataWithDeclarative, payee.signatureParams); +const actionWithoutExtensionsData: RequestLogicTypes.IAction = sign( dataWithoutExtensionsData, payee.signatureParams, ); -const actionWithoutPaymentInfo: RequestLogicTypes.IAction = Utils.signature.sign( +const actionWithoutPaymentInfo: RequestLogicTypes.IAction = sign( dataWithDeclarativeNoPaymentInfo, payee.signatureParams, ); @@ -191,12 +188,9 @@ export const timestampedTransactionWithoutPaymentInfo: TransactionTypes.ITimesta transaction: { data: JSON.stringify(actionWithoutPaymentInfo) }, }; -export const actionRequestId = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action)); +export const actionRequestId = MultiFormat.serialize(normalizeKeccak256Hash(action)); -export const anotherCreationAction: RequestLogicTypes.IAction = Utils.signature.sign( - data, - payer.signatureParams, -); +export const anotherCreationAction: RequestLogicTypes.IAction = sign(data, payer.signatureParams); export const anotherCreationTransactionConfirmed: TransactionTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, @@ -220,7 +214,7 @@ const dataSecondRequest = { version: '2.0.3', }; -export const actionCreationSecondRequest: RequestLogicTypes.IAction = Utils.signature.sign( +export const actionCreationSecondRequest: RequestLogicTypes.IAction = sign( dataSecondRequest, payee.signatureParams, ); @@ -232,7 +226,7 @@ export const timestampedTransactionSecondRequest: TransactionTypes.ITimestampedT }; export const actionRequestIdSecondRequest = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(actionCreationSecondRequest), + normalizeKeccak256Hash(actionCreationSecondRequest), ); export const declarativePaymentNetwork: PaymentTypes.PaymentNetworkCreateParameters = { @@ -265,11 +259,11 @@ export const signatureParametersDelegate: SignatureTypes.ISignatureParameters = export const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, signer: IdentityTypes.IIdentity): any => { if (signer.value === payee.identity.value) { - return Utils.signature.sign(data, signatureParametersPayee); + return sign(data, signatureParametersPayee); } else if (signer.value === payer.identity.value) { - return Utils.signature.sign(data, signatureParametersPayer); + return sign(data, signatureParametersPayer); } else { - return Utils.signature.sign(data, signatureParametersDelegate); + return sign(data, signatureParametersDelegate); } }, supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], diff --git a/packages/request-client.js/test/declarative-payments.test.ts b/packages/request-client.js/test/declarative-payments.test.ts index 6e105fc24..54a1fd9de 100644 --- a/packages/request-client.js/test/declarative-payments.test.ts +++ b/packages/request-client.js/test/declarative-payments.test.ts @@ -20,7 +20,7 @@ import { } from '@requestnetwork/payment-detection'; import { IRequestDataWithEvents } from '../src/types'; import { CurrencyManager } from '@requestnetwork/currency'; -import Utils from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; const httpConfig: Partial = { getConfirmationDeferDelay: 0, @@ -417,7 +417,7 @@ describe('request-client.js: declarative payments', () => { timestamp: TestData.arbitraryTimestamp, transaction: { data: JSON.stringify( - Utils.signature.sign( + sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { diff --git a/packages/request-client.js/test/index.test.ts b/packages/request-client.js/test/index.test.ts index c4ee9e2a7..6433e9731 100644 --- a/packages/request-client.js/test/index.test.ts +++ b/packages/request-client.js/test/index.test.ts @@ -9,7 +9,7 @@ import { PaymentTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { CryptoWrapper, decrypt } from '@requestnetwork/utils'; import { ethers } from 'ethers'; import AxiosMockAdapter from 'axios-mock-adapter'; @@ -54,7 +54,7 @@ const fakeDecryptionProvider: DecryptionProviderTypes.IDecryptionProvider = { ): Promise => { switch (identity.value.toLowerCase()) { case encryptionData.identity.value: - return Utils.encryption.decrypt(data, encryptionData.decryptionParams); + return decrypt(data, encryptionData.decryptionParams); default: throw new Error('Identity not registered'); @@ -1439,10 +1439,8 @@ describe('request-client.js', () => { useMockStorage: true, }); // generate address randomly to avoid collisions - const paymentAddress = - '0x' + (await Utils.crypto.CryptoWrapper.random32Bytes()).slice(12).toString('hex'); - const refundAddress = - '0x' + (await Utils.crypto.CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const paymentAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const refundAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); const paymentNetwork: PaymentTypes.PaymentNetworkCreateParameters = { id: ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_ADDRESS_BASED, @@ -1585,10 +1583,8 @@ describe('request-client.js', () => { }); // generate address randomly to avoid collisions - const paymentAddress = - '0x' + (await Utils.crypto.CryptoWrapper.random32Bytes()).slice(12).toString('hex'); - const refundAddress = - '0x' + (await Utils.crypto.CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const paymentAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const refundAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); const paymentNetwork: PaymentTypes.PaymentNetworkCreateParameters = { id: ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_ADDRESS_BASED, diff --git a/packages/request-logic/specs/example/example.ts b/packages/request-logic/specs/example/example.ts index a3d9af920..69f4915b2 100644 --- a/packages/request-logic/specs/example/example.ts +++ b/packages/request-logic/specs/example/example.ts @@ -6,9 +6,9 @@ import { SignatureProviderTypes, SignatureTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import RequestLogic from '../../src/requestLogicCore'; +import { sign } from '@requestnetwork/utils'; async function foo(): Promise { // Bob (the payee) @@ -38,8 +38,8 @@ async function foo(): Promise { const signatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, identity: IdentityTypes.IIdentity): any => ({ - [aliceRaw.identity.value as string]: Utils.signature.sign(data, aliceRaw.signatureParams), - [bobRaw.identity.value as string]: Utils.signature.sign(data, bobRaw.signatureParams), + [aliceRaw.identity.value as string]: sign(data, aliceRaw.signatureParams), + [bobRaw.identity.value as string]: sign(data, bobRaw.signatureParams), }[identity.value]), supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], supportedMethods: [SignatureTypes.METHOD.ECDSA], diff --git a/packages/request-logic/src/action.ts b/packages/request-logic/src/action.ts index 1a15ca1dd..5118c9587 100644 --- a/packages/request-logic/src/action.ts +++ b/packages/request-logic/src/action.ts @@ -1,9 +1,9 @@ import MultiFormat from '@requestnetwork/multi-format'; import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Semver from 'semver'; import Role from './role'; import Version from './version'; +import { normalizeKeccak256Hash, recover } from '@requestnetwork/utils'; /** * Function to manage Request logic action (object that will be interpreted to create or modify a request) @@ -45,7 +45,7 @@ function createAction( * @returns RequestEnum.ROLE the role of the signer (payee, payer or third party) */ function getSignerIdentityFromAction(action: RequestLogicTypes.IAction): IdentityTypes.IIdentity { - return Utils.signature.recover(action); + return recover(action); } /** @@ -125,7 +125,7 @@ function getVersionFromAction(action: RequestLogicTypes.IAction): string { function getActionHash(action: RequestLogicTypes.IAction): string { // Before the version 2.0.0, the hash was computed without the signature if (Semver.lte(action.data.version, '2.0.0')) { - return MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action.data)); + return MultiFormat.serialize(normalizeKeccak256Hash(action.data)); } - return MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action)); + return MultiFormat.serialize(normalizeKeccak256Hash(action)); } diff --git a/packages/request-logic/src/actions/accept.ts b/packages/request-logic/src/actions/accept.ts index a8538323c..712ad7320 100644 --- a/packages/request-logic/src/actions/accept.ts +++ b/packages/request-logic/src/actions/accept.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { deepCopy } from '@requestnetwork/utils'; /** * Implementation of the action accept from request logic specification @@ -69,7 +69,7 @@ function applyActionToRequest( throw new Error('Signer must be the payer'); } // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); diff --git a/packages/request-logic/src/actions/addExtensionsData.ts b/packages/request-logic/src/actions/addExtensionsData.ts index 66c711dac..9fd3034ad 100644 --- a/packages/request-logic/src/actions/addExtensionsData.ts +++ b/packages/request-logic/src/actions/addExtensionsData.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { deepCopy } from '@requestnetwork/utils'; /** * Implementation of the action add extensions data from request logic specification @@ -68,7 +68,7 @@ function applyActionToRequest( const signer: IdentityTypes.IIdentity = Action.getSignerIdentityFromAction(action); // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); diff --git a/packages/request-logic/src/actions/cancel.ts b/packages/request-logic/src/actions/cancel.ts index 48d432b21..b09816a3b 100644 --- a/packages/request-logic/src/actions/cancel.ts +++ b/packages/request-logic/src/actions/cancel.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { deepCopy } from '@requestnetwork/utils'; /** * Implementation of the action cancel from request logic specification @@ -56,7 +56,7 @@ function applyActionToRequest( const signerRole = Request.getRoleInRequest(signer, request); // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); diff --git a/packages/request-logic/src/actions/create.ts b/packages/request-logic/src/actions/create.ts index bd0b60c80..8afda7b6c 100644 --- a/packages/request-logic/src/actions/create.ts +++ b/packages/request-logic/src/actions/create.ts @@ -1,8 +1,14 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import * as Semver from 'semver'; import Action from '../action'; import Version from '../version'; +import { + deepCopy, + getCurrentTimestampInSecond, + hasError, + isString, + isValid, +} from '@requestnetwork/utils'; /** * Implementation of the request logic specification @@ -32,20 +38,20 @@ function format( throw new Error('payee or PayerId must be given'); } - if (!Utils.amount.isValid(requestParameters.expectedAmount)) { + if (!isValid(requestParameters.expectedAmount)) { throw new Error('expectedAmount must be a positive integer'); } - if (requestParameters.payee && Utils.identity.hasError(requestParameters.payee)) { - throw new Error(`payee: ${Utils.identity.hasError(requestParameters.payee)}̀`); + if (requestParameters.payee && hasError(requestParameters.payee)) { + throw new Error(`payee: ${hasError(requestParameters.payee)}̀`); } - if (requestParameters.payer && Utils.identity.hasError(requestParameters.payer)) { - throw new Error(`payer: ${Utils.identity.hasError(requestParameters.payer)}̀`); + if (requestParameters.payer && hasError(requestParameters.payer)) { + throw new Error(`payer: ${hasError(requestParameters.payer)}̀`); } if (!requestParameters.timestamp) { - requestParameters.timestamp = Utils.getCurrentTimestampInSecond(); + requestParameters.timestamp = getCurrentTimestampInSecond(); } // convert expectedAmount to string to have a consistent numbering @@ -85,17 +91,17 @@ function createRequest( throw new Error('action.parameters.payee or action.parameters.payer must be given'); } - if (action.data.parameters.payee && Utils.identity.hasError(action.data.parameters.payee)) { - throw new Error(`payee: ${Utils.identity.hasError(action.data.parameters.payee)}̀`); + if (action.data.parameters.payee && hasError(action.data.parameters.payee)) { + throw new Error(`payee: ${hasError(action.data.parameters.payee)}̀`); } - if (action.data.parameters.payer && Utils.identity.hasError(action.data.parameters.payer)) { - throw new Error(`payer: ${Utils.identity.hasError(action.data.parameters.payer)}̀`); + if (action.data.parameters.payer && hasError(action.data.parameters.payer)) { + throw new Error(`payer: ${hasError(action.data.parameters.payer)}̀`); } if ( - !Utils.isString(action.data.parameters.expectedAmount) || - !Utils.amount.isValid(action.data.parameters.expectedAmount) + !isString(action.data.parameters.expectedAmount) || + !isValid(action.data.parameters.expectedAmount) ) { throw new Error( 'action.parameters.expectedAmount must be a string representing a positive integer', @@ -105,7 +111,7 @@ function createRequest( const signer: IdentityTypes.IIdentity = Action.getSignerIdentityFromAction(action); // Copy to not modify the action itself - const request: RequestLogicTypes.IRequest = Utils.deepCopy(action.data.parameters); + const request: RequestLogicTypes.IRequest = deepCopy(action.data.parameters); request.extensions = {}; request.requestId = Action.getRequestId(action); request.version = Action.getVersionFromAction(action); diff --git a/packages/request-logic/src/actions/increaseExpectedAmount.ts b/packages/request-logic/src/actions/increaseExpectedAmount.ts index 0a47e6858..efe65cc25 100644 --- a/packages/request-logic/src/actions/increaseExpectedAmount.ts +++ b/packages/request-logic/src/actions/increaseExpectedAmount.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { add, deepCopy, isValid } from '@requestnetwork/utils'; /** * Implementation of the action increaseExpectedAmount from request logic specification @@ -27,7 +27,7 @@ function format( signerIdentity: IdentityTypes.IIdentity, signatureProvider: SignatureProviderTypes.ISignatureProvider, ): Promise { - if (!Utils.amount.isValid(increaseAmountParameters.deltaAmount)) { + if (!isValid(increaseAmountParameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -61,7 +61,7 @@ function applyActionToRequest( if (!action.data.parameters.deltaAmount) { throw new Error('deltaAmount must be given'); } - if (!Utils.amount.isValid(action.data.parameters.deltaAmount)) { + if (!isValid(action.data.parameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -69,7 +69,7 @@ function applyActionToRequest( const signerRole = Request.getRoleInRequest(signer, request); // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); @@ -78,10 +78,7 @@ function applyActionToRequest( throw new Error('the request must not be canceled'); } // increase the expected amount and store it as string - requestCopied.expectedAmount = Utils.amount.add( - request.expectedAmount, - action.data.parameters.deltaAmount, - ); + requestCopied.expectedAmount = add(request.expectedAmount, action.data.parameters.deltaAmount); return requestCopied; } diff --git a/packages/request-logic/src/actions/reduceExpectedAmount.ts b/packages/request-logic/src/actions/reduceExpectedAmount.ts index dda8868df..b418d5f70 100644 --- a/packages/request-logic/src/actions/reduceExpectedAmount.ts +++ b/packages/request-logic/src/actions/reduceExpectedAmount.ts @@ -1,9 +1,9 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from '../action'; import Request from '../request'; import Version from '../version'; +import { deepCopy, isValid, reduce } from '@requestnetwork/utils'; /** * Implementation of the action reduceExpectedAmount from request logic specification @@ -27,7 +27,7 @@ function format( signerIdentity: IdentityTypes.IIdentity, signatureProvider: SignatureProviderTypes.ISignatureProvider, ): Promise { - if (!Utils.amount.isValid(reduceAmountParameters.deltaAmount)) { + if (!isValid(reduceAmountParameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -61,7 +61,7 @@ function applyActionToRequest( if (!action.data.parameters.deltaAmount) { throw new Error('deltaAmount must be given'); } - if (!Utils.amount.isValid(action.data.parameters.deltaAmount)) { + if (!isValid(action.data.parameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -69,7 +69,7 @@ function applyActionToRequest( const signerRole = Request.getRoleInRequest(signer, request); // avoid to mutate the request - let requestCopied: RequestLogicTypes.IRequest = Utils.deepCopy(request); + let requestCopied: RequestLogicTypes.IRequest = deepCopy(request); requestCopied = Request.pushExtensionsData(requestCopied, action.data.parameters.extensionsData); requestCopied.events.push(generateEvent(action, timestamp, signer)); @@ -78,7 +78,7 @@ function applyActionToRequest( throw new Error('the request must not be canceled'); } // reduce the expected amount and store it as string or throw if the result is not valid - requestCopied.expectedAmount = Utils.amount.reduce( + requestCopied.expectedAmount = reduce( request.expectedAmount, action.data.parameters.deltaAmount, ); diff --git a/packages/request-logic/src/request-logic.ts b/packages/request-logic/src/request-logic.ts index 6ad87a831..63b5c323c 100644 --- a/packages/request-logic/src/request-logic.ts +++ b/packages/request-logic/src/request-logic.ts @@ -9,8 +9,8 @@ import { SignatureProviderTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import RequestLogicCore from './requestLogicCore'; +import { normalizeKeccak256Hash, notNull, uniqueByProperty } from '@requestnetwork/utils'; /** * Implementation of Request Logic @@ -457,7 +457,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { updatedBetween?: RequestLogicTypes.ITimestampBoundaries, ): Promise { // hash all the topics - const hashedTopic = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic)); + const hashedTopic = MultiFormat.serialize(normalizeKeccak256Hash(topic)); const getChannelsResult = await this.transactionManager.getChannelsByTopic( hashedTopic, @@ -477,7 +477,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { ): Promise { // hash all the topics const hashedTopics = topics.map((topic) => - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic)), + MultiFormat.serialize(normalizeKeccak256Hash(topic)), ); const getChannelsResult = await this.transactionManager.getChannelsByMultipleTopics( @@ -517,7 +517,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { // hash all the topics const hashedTopics = topics.map((topic) => - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(topic)), + MultiFormat.serialize(normalizeKeccak256Hash(topic)), ); return { @@ -542,16 +542,16 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { const resultGetTx = await this.transactionManager.getTransactionsByChannelId(requestId); const actions = resultGetTx.result.transactions // filter the actions ignored by the previous layers - .filter(Utils.notNull) + .filter(notNull) .sort((a, b) => a.timestamp - b.timestamp); // eslint-disable-next-line prefer-const let { ignoredTransactions, keptTransactions } = this.removeOldPendingTransactions(actions); // array of transaction without duplicates to avoid replay attack - const timestampedActionsWithoutDuplicates = Utils.uniqueByProperty( + const timestampedActionsWithoutDuplicates = uniqueByProperty( keptTransactions - .filter(Utils.notNull) + .filter(notNull) .map((t) => { try { return { @@ -568,7 +568,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { return; } }) - .filter(Utils.notNull), + .filter(notNull), 'action', ); @@ -678,10 +678,10 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { transactionsByChannel[channelId], ); - const timestampedActionsWithoutDuplicates = Utils.uniqueByProperty( + const timestampedActionsWithoutDuplicates = uniqueByProperty( keptTransactions // filter the actions ignored by the previous layers - .filter(Utils.notNull) + .filter(notNull) .map((t) => { try { return { @@ -698,7 +698,7 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { return; } }) - .filter(Utils.notNull), + .filter(notNull), 'action', ); @@ -820,8 +820,8 @@ export default class RequestLogic implements RequestLogicTypes.IRequestLogic { if (key in pendingRequestState) { // TODO: Should find a better way to do that if ( - Utils.crypto.normalizeKeccak256Hash(pendingRequestState[key]).value !== - Utils.crypto.normalizeKeccak256Hash(confirmedRequestState[key]).value + normalizeKeccak256Hash(pendingRequestState[key]).value !== + normalizeKeccak256Hash(confirmedRequestState[key]).value ) { if (!pending) { pending = {}; diff --git a/packages/request-logic/src/request.ts b/packages/request-logic/src/request.ts index 25eb798a7..4e40289ae 100644 --- a/packages/request-logic/src/request.ts +++ b/packages/request-logic/src/request.ts @@ -1,7 +1,7 @@ import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Role from './role'; +import { isValid } from '@requestnetwork/utils'; /** * Module to manage a request @@ -63,7 +63,7 @@ function checkRequest(request: RequestLogicTypes.IRequest): boolean { if (request.payer && request.payer.type !== IdentityTypes.TYPE.ETHEREUM_ADDRESS) { throw Error('request.payer.type not supported'); } - if (!Utils.amount.isValid(request.expectedAmount)) { + if (!isValid(request.expectedAmount)) { throw Error('expectedAmount must be a positive integer'); } return true; diff --git a/packages/request-logic/src/requestLogicCore.ts b/packages/request-logic/src/requestLogicCore.ts index 2d3c497c9..f4da831dd 100644 --- a/packages/request-logic/src/requestLogicCore.ts +++ b/packages/request-logic/src/requestLogicCore.ts @@ -1,5 +1,4 @@ import { AdvancedLogicTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import Action from './action'; import Request from './request'; @@ -9,6 +8,7 @@ import CancelAction from './actions/cancel'; import CreateAction from './actions/create'; import IncreaseExpectedAmountAction from './actions/increaseExpectedAmount'; import ReduceExpectedAmountAction from './actions/reduceExpectedAmount'; +import { deepCopy } from '@requestnetwork/utils'; /** * Implementation of Request Logic Core @@ -45,7 +45,7 @@ function applyActionToRequest( } // we don't want to modify the original request state - const requestCopied: RequestLogicTypes.IRequest | null = request ? Utils.deepCopy(request) : null; + const requestCopied: RequestLogicTypes.IRequest | null = request ? deepCopy(request) : null; let requestAfterApply: RequestLogicTypes.IRequest | null = null; diff --git a/packages/request-logic/src/role.ts b/packages/request-logic/src/role.ts index 098cb99f1..16933a660 100644 --- a/packages/request-logic/src/role.ts +++ b/packages/request-logic/src/role.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { areEqual } from '@requestnetwork/utils'; /** * Function to manage Request Logic Role @@ -17,10 +17,10 @@ export default { * @returns Types.ROLE the role of identity in parameters */ function getRole(identity: IdentityTypes.IIdentity, parameters: any): RequestLogicTypes.ROLE { - if (parameters.payee && Utils.identity.areEqual(parameters.payee, identity)) { + if (parameters.payee && areEqual(parameters.payee, identity)) { return RequestLogicTypes.ROLE.PAYEE; } - if (parameters.payer && Utils.identity.areEqual(parameters.payer, identity)) { + if (parameters.payer && areEqual(parameters.payer, identity)) { return RequestLogicTypes.ROLE.PAYER; } diff --git a/packages/request-logic/test/index.test.ts b/packages/request-logic/test/index.test.ts index e8650a8df..d0b3cbd0d 100644 --- a/packages/request-logic/test/index.test.ts +++ b/packages/request-logic/test/index.test.ts @@ -2,12 +2,12 @@ import { EventEmitter } from 'events'; import MultiFormat from '@requestnetwork/multi-format'; import { AdvancedLogicTypes, RequestLogicTypes, TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { RequestLogic } from '../src/index'; import * as TestData from './unit/utils/test-data-generator'; import Version from '../src/version'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; const CURRENT_VERSION = Version.currentVersion; @@ -26,8 +26,8 @@ const unsignedAction: RequestLogicTypes.IUnsignedAction = { parameters: createParams, version: CURRENT_VERSION, }; -const action = Utils.signature.sign(unsignedAction, TestData.payeeRaw.signatureParams); -const requestId = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action)); +const action = sign(unsignedAction, TestData.payeeRaw.signatureParams); +const requestId = MultiFormat.serialize(normalizeKeccak256Hash(action)); const fakeTxHash = '01aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; @@ -167,8 +167,8 @@ describe('index', () => { JSON.stringify(action), requestId, [ - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payeeRaw.identity)), - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payerRaw.identity)), + MultiFormat.serialize(normalizeKeccak256Hash(TestData.payeeRaw.identity)), + MultiFormat.serialize(normalizeKeccak256Hash(TestData.payerRaw.identity)), ], ); }); @@ -324,8 +324,8 @@ describe('index', () => { JSON.stringify(action), requestId, [ - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payeeRaw.identity)), - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payerRaw.identity)), + MultiFormat.serialize(normalizeKeccak256Hash(TestData.payeeRaw.identity)), + MultiFormat.serialize(normalizeKeccak256Hash(TestData.payerRaw.identity)), ], [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], ); @@ -496,7 +496,7 @@ describe('index', () => { }); it('cannot accept as payee', async () => { - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -592,7 +592,7 @@ describe('index', () => { }); it('cannot cancel if not payee or payer', async () => { - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -693,7 +693,7 @@ describe('index', () => { ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot increaseExpectedAmountRequest as payee', async () => { - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -799,7 +799,7 @@ describe('index', () => { ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot reduceExpectedAmountRequest as payer', async () => { - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -908,7 +908,7 @@ describe('index', () => { }, }; - const actionCreate = Utils.signature.sign( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -962,7 +962,7 @@ describe('index', () => { describe('getRequestFromId', () => { it('can getRequestFromId', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -980,7 +980,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -991,7 +991,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1098,7 +1098,7 @@ describe('index', () => { }); it('can getRequestFromId ignore old pending transaction', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1116,7 +1116,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1127,7 +1127,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1237,7 +1237,7 @@ describe('index', () => { }); it('can getRequestFromId with pending transaction', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1255,7 +1255,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1266,7 +1266,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1376,7 +1376,7 @@ describe('index', () => { }); it('can getRequestFromId ignore the same transactions even with different case', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1394,7 +1394,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1405,7 +1405,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const actionReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const actionReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1417,7 +1417,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionReduce2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionReduce2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1538,7 +1538,7 @@ describe('index', () => { }); it('can getRequestFromId do not ignore the same transactions if different nonces', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1556,7 +1556,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1567,7 +1567,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const actionReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const actionReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1579,7 +1579,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionReduce2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionReduce2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1736,7 +1736,7 @@ describe('index', () => { }); it('should ignored the corrupted data (e.g: wrong properties)', async () => { - const actionCorrupted: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCorrupted: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1811,15 +1811,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); - const newRequestId = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), - ); + const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1830,7 +1828,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1856,15 +1854,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); - const newRequestId2 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), - ); + const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -1889,13 +1885,11 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); - const newRequestId3 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), - ); + const newRequestId3 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation3)); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, @@ -1980,15 +1974,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); - const newRequestId = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), - ); + const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1999,7 +1991,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -2025,15 +2017,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); - const newRequestId2 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), - ); + const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -2058,13 +2048,11 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); - const newRequestId3 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), - ); + const newRequestId3 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation3)); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, @@ -2155,7 +2143,7 @@ describe('index', () => { }); it('should ignore the transaction none parsable and the rejected action', async () => { - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -2173,7 +2161,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const acceptNotValid: RequestLogicTypes.IAction = Utils.signature.sign( + const acceptNotValid: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -2250,15 +2238,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); - const newRequestId = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), - ); + const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -2269,7 +2255,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -2295,15 +2281,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); - const newRequestId2 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), - ); + const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -2328,13 +2312,11 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); - const newRequestId3 = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), - ); + const newRequestId3 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation3)); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, diff --git a/packages/request-logic/test/unit/action.test.ts b/packages/request-logic/test/unit/action.test.ts index 4a53d3a0a..a308739db 100644 --- a/packages/request-logic/test/unit/action.test.ts +++ b/packages/request-logic/test/unit/action.test.ts @@ -5,7 +5,7 @@ import { SignatureProviderTypes, SignatureTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy, normalizeKeccak256Hash } from '@requestnetwork/utils'; import Action from '../../src/action'; import CreateAction from '../../src/actions/create'; @@ -46,7 +46,7 @@ const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { describe('Action', () => { it('can getRequestId() of current version', () => { const reqId = Action.getRequestId(signedAction); - expect(reqId).toBe(MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(signedAction))); + expect(reqId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(signedAction))); }); it('can getRequestId() of version before or equal 2.0.0', () => { const randomUnsignedAction200 = { @@ -72,9 +72,7 @@ describe('Action', () => { }; const reqId = Action.getRequestId(signedAction200); - expect(reqId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(randomUnsignedAction200)), - ); + expect(reqId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(randomUnsignedAction200))); }); it('can getRoleInAction()', () => { @@ -110,7 +108,7 @@ describe('Action', () => { it('can isActionVersionSupported()', () => { expect(Action.isActionVersionSupported(signedAction)).toBeTruthy(); - const wrongVersionAction = Utils.deepCopy(signedAction); + const wrongVersionAction = deepCopy(signedAction); wrongVersionAction.data.version = '10.0.0'; expect(Action.isActionVersionSupported(wrongVersionAction)).toBeFalsy(); diff --git a/packages/request-logic/test/unit/actions/accept.test.ts b/packages/request-logic/test/unit/actions/accept.test.ts index b006bdbdc..2f7b3d172 100644 --- a/packages/request-logic/test/unit/actions/accept.test.ts +++ b/packages/request-logic/test/unit/actions/accept.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import AcceptAction from '../../../src/actions/accept'; import Version from '../../../src/version'; @@ -57,7 +57,7 @@ describe('actions/accept', () => { const request = AcceptAction.applyActionToRequest( actionAccept, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -118,7 +118,7 @@ describe('actions/accept', () => { AcceptAction.applyActionToRequest( actionAccept, 1, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('Signer must be the payer'); }); @@ -133,7 +133,7 @@ describe('actions/accept', () => { AcceptAction.applyActionToRequest( actionAccept, 1, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('Signer must be the payer'); }); @@ -152,11 +152,7 @@ describe('actions/accept', () => { }, }; expect(() => - AcceptAction.applyActionToRequest( - action, - 1, - Utils.deepCopy(TestData.requestCreatedNoExtension), - ), + AcceptAction.applyActionToRequest(action, 1, deepCopy(TestData.requestCreatedNoExtension)), ).toThrowError('requestId must be given'); }); @@ -234,11 +230,7 @@ describe('actions/accept', () => { }; expect(() => - AcceptAction.applyActionToRequest( - action, - 1, - Utils.deepCopy(TestData.requestCanceledNoExtension), - ), + AcceptAction.applyActionToRequest(action, 1, deepCopy(TestData.requestCanceledNoExtension)), ).toThrowError('the request state must be created'); }); @@ -259,11 +251,7 @@ describe('actions/accept', () => { }; expect(() => - AcceptAction.applyActionToRequest( - action, - 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), - ), + AcceptAction.applyActionToRequest(action, 2, deepCopy(TestData.requestCanceledNoExtension)), ).toThrowError('the request state must be created'); }); @@ -281,7 +269,7 @@ describe('actions/accept', () => { const request = AcceptAction.applyActionToRequest( actionAccept, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -344,7 +332,7 @@ describe('actions/accept', () => { const request = AcceptAction.applyActionToRequest( actionAccept, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -411,7 +399,7 @@ describe('actions/accept', () => { const request = AcceptAction.applyActionToRequest( actionAccept, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' diff --git a/packages/request-logic/test/unit/actions/addExtensionsData.test.ts b/packages/request-logic/test/unit/actions/addExtensionsData.test.ts index 840fc793d..95b769f83 100644 --- a/packages/request-logic/test/unit/actions/addExtensionsData.test.ts +++ b/packages/request-logic/test/unit/actions/addExtensionsData.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import AddExtensionsDataAction from '../../../src/actions/addExtensionsData'; import Version from '../../../src/version'; @@ -75,7 +75,7 @@ describe('actions/addExtensionsData', () => { const request = AddExtensionsDataAction.applyActionToRequest( actionAddExtensionsData, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -141,7 +141,7 @@ describe('actions/addExtensionsData', () => { AddExtensionsDataAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('requestId must be given'); }); @@ -163,7 +163,7 @@ describe('actions/addExtensionsData', () => { AddExtensionsDataAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('extensionsData must be given'); }); @@ -185,7 +185,7 @@ describe('actions/addExtensionsData', () => { AddExtensionsDataAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('extensionsData must be given'); }); @@ -204,7 +204,7 @@ describe('actions/addExtensionsData', () => { const request = AddExtensionsDataAction.applyActionToRequest( actionAddExtensionsData, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -267,7 +267,7 @@ describe('actions/addExtensionsData', () => { const request = AddExtensionsDataAction.applyActionToRequest( actionAddExtensionsData, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' diff --git a/packages/request-logic/test/unit/actions/cancel.test.ts b/packages/request-logic/test/unit/actions/cancel.test.ts index 3608378fa..580be2f78 100644 --- a/packages/request-logic/test/unit/actions/cancel.test.ts +++ b/packages/request-logic/test/unit/actions/cancel.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import CancelAction from '../../../src/actions/cancel'; import Version from '../../../src/version'; @@ -60,7 +60,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -122,7 +122,7 @@ describe('actions/cancel', () => { CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestAcceptedNoExtension), + deepCopy(TestData.requestAcceptedNoExtension), ), ).toThrowError('A payer cancel need to be done on a request with the state created'); }); @@ -139,7 +139,7 @@ describe('actions/cancel', () => { CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), + deepCopy(TestData.requestCanceledNoExtension), ), ).toThrowError('A payer cancel need to be done on a request with the state created'); }); @@ -155,7 +155,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -215,7 +215,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestAcceptedNoExtension), + deepCopy(TestData.requestAcceptedNoExtension), ); // 'requestId is wrong' @@ -276,7 +276,7 @@ describe('actions/cancel', () => { CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), + deepCopy(TestData.requestCanceledNoExtension), ), ).toThrowError('Cannot cancel an already canceled request'); }); @@ -294,7 +294,7 @@ describe('actions/cancel', () => { CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('Signer must be the payer or the payee'); }); @@ -314,11 +314,7 @@ describe('actions/cancel', () => { }; expect(() => - CancelAction.applyActionToRequest( - action, - 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), - ), + CancelAction.applyActionToRequest(action, 2, deepCopy(TestData.requestCreatedNoExtension)), ).toThrowError('requestId must be given'); }); it('cannot cancel by payer if no payer in state', () => { @@ -447,7 +443,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -510,7 +506,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -570,7 +566,7 @@ describe('actions/cancel', () => { const request = CancelAction.applyActionToRequest( actionCancel, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' diff --git a/packages/request-logic/test/unit/actions/create.test.ts b/packages/request-logic/test/unit/actions/create.test.ts index 781a9b43a..bfcd3fcdf 100644 --- a/packages/request-logic/test/unit/actions/create.test.ts +++ b/packages/request-logic/test/unit/actions/create.test.ts @@ -1,7 +1,7 @@ import MultiFormat from '@requestnetwork/multi-format'; import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; import CreateAction from '../../../src/actions/create'; @@ -647,9 +647,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -719,9 +717,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -791,9 +787,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -862,9 +856,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -1027,9 +1019,7 @@ describe('CreateAction', () => { const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, diff --git a/packages/request-logic/test/unit/actions/increaseExpectedAmount.test.ts b/packages/request-logic/test/unit/actions/increaseExpectedAmount.test.ts index 6cee4bfd6..f9166d9ab 100644 --- a/packages/request-logic/test/unit/actions/increaseExpectedAmount.test.ts +++ b/packages/request-logic/test/unit/actions/increaseExpectedAmount.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import IncreaseExpectedAmountAction from '../../../src/actions/increaseExpectedAmount'; import Version from '../../../src/version'; @@ -118,7 +118,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -181,7 +181,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('signer must be the payer'); }); @@ -199,7 +199,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('signer must be the payer'); }); @@ -224,7 +224,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('requestId must be given'); }); @@ -249,7 +249,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('deltaAmount must be given'); }); @@ -325,7 +325,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), + deepCopy(TestData.requestCanceledNoExtension), ), ).toThrowError('the request must not be canceled'); }); @@ -343,7 +343,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestAcceptedNoExtension), + deepCopy(TestData.requestAcceptedNoExtension), ); // 'requestId is wrong' @@ -407,7 +407,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -471,7 +471,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -532,7 +532,7 @@ describe('actions/increaseExpectedAmount', () => { const request = IncreaseExpectedAmountAction.applyActionToRequest( actionIncreaseAmount, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -602,7 +602,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -629,7 +629,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -655,7 +655,7 @@ describe('actions/increaseExpectedAmount', () => { IncreaseExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ), ).toThrowError('deltaAmount must be a string representing a positive integer'); }); diff --git a/packages/request-logic/test/unit/actions/reduceExpectedAmount.test.ts b/packages/request-logic/test/unit/actions/reduceExpectedAmount.test.ts index c03c4c345..190e3aeb5 100644 --- a/packages/request-logic/test/unit/actions/reduceExpectedAmount.test.ts +++ b/packages/request-logic/test/unit/actions/reduceExpectedAmount.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import ReduceExpectedAmountAction from '../../../src/actions/reduceExpectedAmount'; import Version from '../../../src/version'; @@ -119,7 +119,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -182,7 +182,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('signer must be the payee'); }); @@ -200,7 +200,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('signer must be the payee'); }); @@ -224,7 +224,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('requestId must be given'); }); @@ -248,7 +248,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('deltaAmount must be given'); }); @@ -324,7 +324,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCanceledNoExtension), + deepCopy(TestData.requestCanceledNoExtension), ); }).toThrowError('the request must not be canceled'); }); @@ -342,7 +342,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestAcceptedNoExtension), + deepCopy(TestData.requestAcceptedNoExtension), ); // 'requestId is wrong' @@ -406,7 +406,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -470,7 +470,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -531,7 +531,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedWithExtensions), + deepCopy(TestData.requestCreatedWithExtensions), ); // 'requestId is wrong' @@ -601,7 +601,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -627,7 +627,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -652,7 +652,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( action, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('deltaAmount must be a string representing a positive integer'); }); @@ -670,7 +670,7 @@ describe('actions/reduceExpectedAmount', () => { const request = ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); // 'requestId is wrong' @@ -732,7 +732,7 @@ describe('actions/reduceExpectedAmount', () => { ReduceExpectedAmountAction.applyActionToRequest( actionReduceAmount, 2, - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), ); }).toThrowError('result of reduce is not valid'); }); diff --git a/packages/request-logic/test/unit/requestLogicCore.test.ts b/packages/request-logic/test/unit/requestLogicCore.test.ts index 4c7b61021..bb85cfcf6 100644 --- a/packages/request-logic/test/unit/requestLogicCore.test.ts +++ b/packages/request-logic/test/unit/requestLogicCore.test.ts @@ -6,7 +6,7 @@ import { RequestLogicTypes, SignatureTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { deepCopy, normalizeKeccak256Hash } from '@requestnetwork/utils'; import Version from '../../src/version'; const CURRENT_VERSION = Version.currentVersion; @@ -51,7 +51,7 @@ describe('requestLogicCore', () => { expect(() => RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), action, 2, fakeAdvancedLogic, @@ -392,9 +392,7 @@ describe('requestLogicCore', () => { ); // 'requestId is wrong' - expect(request.requestId).toBe( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), - ); + expect(request.requestId).toBe(MultiFormat.serialize(normalizeKeccak256Hash(actionCreation))); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, @@ -431,7 +429,7 @@ describe('requestLogicCore', () => { ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionAccept, 2, fakeAdvancedLogic, @@ -485,7 +483,7 @@ describe('requestLogicCore', () => { TestData.fakeSignatureProvider, ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionCancel, 2, fakeAdvancedLogic, @@ -543,7 +541,7 @@ describe('requestLogicCore', () => { ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionIncreaseAmount, 2, fakeAdvancedLogic, @@ -601,7 +599,7 @@ describe('requestLogicCore', () => { ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionReduceAmount, 2, fakeAdvancedLogic, @@ -654,7 +652,7 @@ describe('requestLogicCore', () => { ); const request = RequestLogicCore.applyActionToRequest( - Utils.deepCopy(TestData.requestCreatedNoExtension), + deepCopy(TestData.requestCreatedNoExtension), actionAddExtensionsData, 2, fakeAdvancedLogic, diff --git a/packages/request-logic/test/unit/utils/test-data-generator.ts b/packages/request-logic/test/unit/utils/test-data-generator.ts index 3e8f190e0..25a107eb2 100644 --- a/packages/request-logic/test/unit/utils/test-data-generator.ts +++ b/packages/request-logic/test/unit/utils/test-data-generator.ts @@ -6,7 +6,7 @@ import { SignatureTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; import Version from '../../../src/version'; const CURRENT_VERSION = Version.currentVersion; @@ -280,9 +280,9 @@ export const fakeIdentity = { export const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, identity: IdentityTypes.IIdentity): any => ({ - [payeeRaw.address as string]: Utils.signature.sign(data, payeeRaw.signatureParams), - [payerRaw.address as string]: Utils.signature.sign(data, payerRaw.signatureParams), - [otherIdRaw.address as string]: Utils.signature.sign(data, otherIdRaw.signatureParams), + [payeeRaw.address as string]: sign(data, payeeRaw.signatureParams), + [payerRaw.address as string]: sign(data, payerRaw.signatureParams), + [otherIdRaw.address as string]: sign(data, otherIdRaw.signatureParams), }[identity.value]), supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], supportedMethods: [SignatureTypes.METHOD.ECDSA], diff --git a/packages/request-node/src/logger.ts b/packages/request-node/src/logger.ts index f9e565074..fb2980810 100644 --- a/packages/request-node/src/logger.ts +++ b/packages/request-node/src/logger.ts @@ -1,5 +1,5 @@ import { LogTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { SimpleLogger } from '@requestnetwork/utils'; import chalk from 'chalk'; /** The different logging modes supported by this logger */ @@ -20,7 +20,7 @@ const levelColor = { /** * A logger for the Request Node that extends the `SimpleLogger` */ -export class Logger extends Utils.SimpleLogger { +export class Logger extends SimpleLogger { // The class modeType private mode: modeType; diff --git a/packages/request-node/src/request/persistTransaction.ts b/packages/request-node/src/request/persistTransaction.ts index 9b190c369..768e72244 100644 --- a/packages/request-node/src/request/persistTransaction.ts +++ b/packages/request-node/src/request/persistTransaction.ts @@ -1,10 +1,10 @@ import { LogTypes, MultiFormatTypes, DataAccessTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { Request, Response } from 'express'; import { StatusCodes } from 'http-status-codes'; import { getPersistTransactionTimeout } from '../config'; import ConfirmedTransactionStore from './confirmedTransactionStore'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Class to persist transactions though the data-access layer @@ -52,7 +52,7 @@ export default class PersistTransactionHandler { return; } try { - const transactionHash: MultiFormatTypes.HashTypes.IHash = Utils.crypto.normalizeKeccak256Hash( + const transactionHash: MultiFormatTypes.HashTypes.IHash = normalizeKeccak256Hash( clientRequest.body.transactionData, ); diff --git a/packages/request-node/src/requestNode.ts b/packages/request-node/src/requestNode.ts index 3ca028e00..5fcd45184 100644 --- a/packages/request-node/src/requestNode.ts +++ b/packages/request-node/src/requestNode.ts @@ -7,12 +7,12 @@ import { getInitializationStorageFilePath, getMnemonic } from './config'; import { getEthereumStorage, getIpfsStorage } from './storageUtils'; import { RequestNodeBase } from './requestNodeBase'; -import Utils from '@requestnetwork/utils'; +import { SimpleLogger } from '@requestnetwork/utils'; export class RequestNode extends RequestNodeBase { constructor(logger?: LogTypes.ILogger) { const initializationStoragePath = getInitializationStorageFilePath(); - logger = logger || new Utils.SimpleLogger(); + logger = logger || new SimpleLogger(); const store = initializationStoragePath ? new KeyvFile({ diff --git a/packages/request-node/src/requestNodeBase.ts b/packages/request-node/src/requestNodeBase.ts index 12666e35f..81c05c5be 100644 --- a/packages/request-node/src/requestNodeBase.ts +++ b/packages/request-node/src/requestNodeBase.ts @@ -1,5 +1,5 @@ import { DataAccessTypes, LogTypes, StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { SimpleLogger } from '@requestnetwork/utils'; import cors from 'cors'; import { Server } from 'http'; import express, { NextFunction, Request, Response } from 'express'; @@ -61,7 +61,7 @@ export class RequestNodeBase { ) { this.initialized = false; - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.dataAccess = dataAccess; this.confirmedTransactionStore = new ConfirmedTransactionStore(store); diff --git a/packages/request-node/src/thegraph-node.ts b/packages/request-node/src/thegraph-node.ts index 81bbddcf5..757a60332 100644 --- a/packages/request-node/src/thegraph-node.ts +++ b/packages/request-node/src/thegraph-node.ts @@ -6,9 +6,9 @@ import { LogTypes } from '@requestnetwork/types'; import { RequestNodeBase } from './requestNodeBase'; import * as config from './config'; import { getIpfsStorage } from './storageUtils'; -import Utils from '@requestnetwork/utils'; import { TheGraphDataAccess } from '@requestnetwork/thegraph-data-access'; import { EthereumStorageEthers } from '@requestnetwork/ethereum-storage'; +import { SimpleLogger } from '@requestnetwork/utils'; const getNetworkFromId = (networkId: number) => { const customNames: Record = { @@ -20,7 +20,7 @@ const getNetworkFromId = (networkId: number) => { export class TheGraphRequestNode extends RequestNodeBase { constructor(url: string, logger?: LogTypes.ILogger) { const initializationStoragePath = config.getInitializationStorageFilePath(); - logger = logger || new Utils.SimpleLogger(); + logger = logger || new SimpleLogger(); const store = initializationStoragePath ? new KeyvFile({ diff --git a/packages/request-node/test/getConfirmedTransaction.test.ts b/packages/request-node/test/getConfirmedTransaction.test.ts index d5a7db037..4cd49ecd5 100644 --- a/packages/request-node/test/getConfirmedTransaction.test.ts +++ b/packages/request-node/test/getConfirmedTransaction.test.ts @@ -1,4 +1,4 @@ -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; import { StatusCodes } from 'http-status-codes'; import request from 'supertest'; import { RequestNode } from '../src/requestNode'; @@ -7,7 +7,7 @@ import { RequestNodeBase } from '../src/requestNodeBase'; const channelId = '010aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; const transactionData = { data: 'this is sample data for a transaction' }; -const transactionHash = Utils.crypto.normalizeKeccak256Hash(transactionData).value; +const transactionHash = normalizeKeccak256Hash(transactionData).value; let requestNodeInstance: RequestNodeBase; let server: any; diff --git a/packages/smart-contracts/hardhat.config.ts b/packages/smart-contracts/hardhat.config.ts index e02716a45..6d304a713 100644 --- a/packages/smart-contracts/hardhat.config.ts +++ b/packages/smart-contracts/hardhat.config.ts @@ -13,8 +13,8 @@ import { HardhatRuntimeEnvironmentExtended } from './scripts-create2/types'; import { computeCreate2DeploymentAddressesFromList } from './scripts-create2/compute-one-address'; import { VerifyCreate2FromList } from './scripts-create2/verify'; import { deployWithCreate2FromList } from './scripts-create2/deploy'; -import utils from '@requestnetwork/utils'; import { NUMBER_ERRORS } from './scripts/utils'; +import { networkRpcs } from '@requestnetwork/utils'; config(); @@ -45,8 +45,7 @@ const requestDeployer = process.env.REQUEST_DEPLOYER_LIVE ? LIVE_DEPLOYER_ADDRESS : LOCAL_DEPLOYER_ADDRESS; -const url = (network: string): string => - process.env.WEB3_PROVIDER_URL || utils.networkRpcs[network]; +const url = (network: string): string => process.env.WEB3_PROVIDER_URL || networkRpcs[network]; export default { solidity: '0.8.9', diff --git a/packages/smart-contracts/scripts-create2/check-deployer.ts b/packages/smart-contracts/scripts-create2/check-deployer.ts index 637c4ce36..e1c3c689a 100644 --- a/packages/smart-contracts/scripts-create2/check-deployer.ts +++ b/packages/smart-contracts/scripts-create2/check-deployer.ts @@ -1,5 +1,5 @@ -import utils from '@requestnetwork/utils'; import { HardhatRuntimeEnvironmentExtended } from './types'; +import { getCeloProvider, getDefaultProvider } from '@requestnetwork/utils'; export const checkCreate2Deployer = async ( hre: HardhatRuntimeEnvironmentExtended, @@ -14,9 +14,9 @@ export const checkCreate2Deployer = async ( hre.config.xdeploy.networks.map(async (network: string) => { let provider; if (network === 'celo') { - provider = utils.getCeloProvider(); + provider = getCeloProvider(); } else { - provider = utils.getDefaultProvider(network); + provider = getDefaultProvider(network); } const code = await provider.getCode(hre.config.xdeploy.deployerAddress); diff --git a/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts b/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts index f6445261e..344126d20 100644 --- a/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts +++ b/packages/smart-contracts/scripts-create2/contract-setup/adminTasks.ts @@ -2,9 +2,9 @@ import { chainlinkConversionPath } from '../../src/lib'; import { uniswapV2RouterAddresses } from '../../scripts/utils'; import * as artifacts from '../../src/lib'; import { BigNumber, Overrides, Wallet } from 'ethers'; -import utils from '@requestnetwork/utils'; import { HardhatRuntimeEnvironmentExtended } from '../types'; import { parseUnits } from 'ethers/lib/utils'; +import { estimateGasFees, getCeloProvider, getDefaultProvider } from '@requestnetwork/utils'; // Fees: 0.5% export const REQUEST_SWAP_FEES = 5; @@ -243,15 +243,15 @@ export const getSignerAndGasFees = async ( }> => { let provider; if (network === 'celo') { - provider = utils.getCeloProvider(); + provider = getCeloProvider(); } else { - provider = utils.getDefaultProvider(network); + provider = getDefaultProvider(network); } const signer = new hre.ethers.Wallet(hre.config.xdeploy.signer).connect(provider); let txOverrides; try { - txOverrides = await utils.estimateGasFees({ provider }); + txOverrides = await estimateGasFees({ provider }); } catch (err) { txOverrides = {}; } diff --git a/packages/smart-contracts/scripts-create2/xdeployer.ts b/packages/smart-contracts/scripts-create2/xdeployer.ts index c8e8e0088..c9026faf4 100644 --- a/packages/smart-contracts/scripts-create2/xdeployer.ts +++ b/packages/smart-contracts/scripts-create2/xdeployer.ts @@ -1,7 +1,7 @@ import { HardhatRuntimeEnvironmentExtended, IDeploymentParams, IDeploymentResult } from './types'; -import utils from '@requestnetwork/utils'; import { requestDeployer } from '../src/lib'; import { Overrides } from 'ethers'; +import { estimateGasFees, getCeloProvider, getDefaultProvider } from '@requestnetwork/utils'; const ZERO_ETH_INPUT = 0; @@ -44,9 +44,9 @@ export const xdeploy = async ( console.log(`... on ${network}`); let provider; if (network === 'celo') { - provider = utils.getCeloProvider(); + provider = getCeloProvider(); } else { - provider = utils.getDefaultProvider(network); + provider = getDefaultProvider(network); } const wallet = new hre.ethers.Wallet(hre.config.xdeploy.signer, provider); const signer = wallet.connect(provider); @@ -74,7 +74,7 @@ export const xdeploy = async ( let txOverrides: Overrides; try { - txOverrides = await utils.estimateGasFees({ provider }); + txOverrides = await estimateGasFees({ provider }); const gasLimit = hre.config.xdeploy.gasLimit; txOverrides.gasLimit = gasLimit; } catch (e) { diff --git a/packages/smart-contracts/test/contracts/BatchConversionPayments.test.ts b/packages/smart-contracts/test/contracts/BatchConversionPayments.test.ts index 5f12cc131..6506ae36a 100644 --- a/packages/smart-contracts/test/contracts/BatchConversionPayments.test.ts +++ b/packages/smart-contracts/test/contracts/BatchConversionPayments.test.ts @@ -17,7 +17,7 @@ import { CurrencyManager } from '@requestnetwork/currency'; import { chainlinkConversionPath } from '../../src/lib'; import { FAU_USD_RATE } from '../../scripts/test-deploy-batch-conversion-deployment'; import { localERC20AlphaArtifact, secondLocalERC20AlphaArtifact } from './localArtifacts'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { HttpNetworkConfig } from 'hardhat/types'; import { DAI_USD_RATE, @@ -754,28 +754,28 @@ describe('contract: BatchConversionPayments', async () => { describe('batchMultiERC20ConversionPayments errors', async () => { it('cannot transfer with invalid path', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); convRequest.path = [EUR_hash, ETH_hash, DAI_address]; await expect( batchConversionProxy.batchMultiERC20ConversionPayments([convRequest], [], feeAddress), ).to.be.revertedWith('revert No aggregator found'); }); it('cannot transfer if max to spend too low', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); convRequest.maxToSpend = '1000000'; // not enough await expect( batchConversionProxy.batchMultiERC20ConversionPayments([convRequest], [], feeAddress), ).to.be.revertedWith('Amount to pay is over the user limit'); }); it('cannot transfer if rate is too old', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); convRequest.maxRateTimespan = '10'; await expect( batchConversionProxy.batchMultiERC20ConversionPayments([convRequest], [], feeAddress), ).to.be.revertedWith('aggregator rate is outdated'); }); it('Not enough allowance', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); // reduce fromSigner± allowance await fauERC20.approve( batchConversionProxy.address, @@ -789,7 +789,7 @@ describe('contract: BatchConversionPayments', async () => { ).to.be.revertedWith('Insufficient allowance for batch to pay'); }); it('Not enough funds even if partially enough funds', async () => { - const convRequest = Utils.deepCopy(fauConvRequest); + const convRequest = deepCopy(fauConvRequest); // fromSigner transfer enough token to pay just 1 invoice to signer4 await fauERC20 .connect(fromSigner) @@ -846,7 +846,7 @@ describe('contract: BatchConversionPayments', async () => { const initialToETHBalance = await provider.getBalance(to); const initialFeeETHBalance = await provider.getBalance(feeAddress); const initialFromETHBalance = await provider.getBalance(await fromSigner.getAddress()); - const EurEthConvRequest = Utils.deepCopy(ethConvRequest); + const EurEthConvRequest = deepCopy(ethConvRequest); EurEthConvRequest.path = [EUR_hash, USD_hash, ETH_hash]; tx = await batchConversionProxy.batchNativeConversionPayments( @@ -875,7 +875,7 @@ describe('contract: BatchConversionPayments', async () => { describe('batchNativeConversionPayments errors', () => { it('cannot transfer with invalid path', async () => { - const wrongConvRequest = Utils.deepCopy(ethConvRequest); + const wrongConvRequest = deepCopy(ethConvRequest); wrongConvRequest.path = [USD_hash, EUR_hash, ETH_hash]; await expect( batchConversionProxy.batchNativeConversionPayments([wrongConvRequest], false, feeAddress, { @@ -896,7 +896,7 @@ describe('contract: BatchConversionPayments', async () => { ).to.be.revertedWith('paymentProxy transferExactEthWithReferenceAndFee failed'); }); it('cannot transfer if rate is too old', async () => { - const wrongConvRequest = Utils.deepCopy(ethConvRequest); + const wrongConvRequest = deepCopy(ethConvRequest); wrongConvRequest.maxRateTimespan = '1'; await expect( batchConversionProxy.batchNativeConversionPayments([wrongConvRequest], false, feeAddress, { diff --git a/packages/smart-contracts/test/contracts/BatchNoConversionEthPayments.test.ts b/packages/smart-contracts/test/contracts/BatchNoConversionEthPayments.test.ts index d08067258..93288dcaa 100644 --- a/packages/smart-contracts/test/contracts/BatchNoConversionEthPayments.test.ts +++ b/packages/smart-contracts/test/contracts/BatchNoConversionEthPayments.test.ts @@ -1,7 +1,7 @@ import { ethers, network } from 'hardhat'; import { BigNumber, Signer } from 'ethers'; import { expect } from 'chai'; -import Utils from '@requestnetwork/utils'; +import { deepCopy } from '@requestnetwork/utils'; import { EthereumFeeProxy__factory, BatchNoConversionPayments__factory, @@ -89,11 +89,11 @@ describe('contract: batchNoConversionPayments: Ethereum', () => { beforeEthBalance1 = await provider.getBalance(payee1); beforeEthBalance2 = await provider.getBalance(payee2); - const copyEthRequestDetail1 = Utils.deepCopy(ethRequestDetail1); + const copyEthRequestDetail1 = deepCopy(ethRequestDetail1); copyEthRequestDetail1.requestAmount = '2000'; copyEthRequestDetail1.feeAmount = '100'; - const copyEthRequestDetail2 = Utils.deepCopy(ethRequestDetail2); + const copyEthRequestDetail2 = deepCopy(ethRequestDetail2); copyEthRequestDetail2.requestAmount = '3000'; copyEthRequestDetail2.feeAmount = '200'; await expect( @@ -149,7 +149,7 @@ describe('contract: batchNoConversionPayments: Ethereum', () => { const feeAmount = 1; const nbTxs = 10; // to compare gas optim, go to 100. - const copyEthRequestDetail = Utils.deepCopy(ethRequestDetail2); + const copyEthRequestDetail = deepCopy(ethRequestDetail2); copyEthRequestDetail.requestAmount = amount.toString(); copyEthRequestDetail.feeAmount = feeAmount.toString(); const totalAmount = BigNumber.from(((amount + feeAmount) * nbTxs).toString()); diff --git a/packages/smart-contracts/test/contracts/ChainlinkConversionPath.test.ts b/packages/smart-contracts/test/contracts/ChainlinkConversionPath.test.ts index f30fbb763..11d118173 100644 --- a/packages/smart-contracts/test/contracts/ChainlinkConversionPath.test.ts +++ b/packages/smart-contracts/test/contracts/ChainlinkConversionPath.test.ts @@ -32,7 +32,7 @@ describe('contract: ChainlinkConversionPath', () => { describe('admin tasks', async () => { it('can updateAggregator and updateAggregatorsList', async () => { let addressAggregator = await conversionPathInstance.allAggregators(address1, address2); - expect(addressAggregator).equal('0x0000000000000000000000000000000000000000'); + expect(addressAggregator).equal('0x3333333333333333333333333333333333333333'); await conversionPathInstance.updateAggregator(address1, address2, address3); @@ -41,7 +41,7 @@ describe('contract: ChainlinkConversionPath', () => { addressAggregator = await conversionPathInstance.allAggregators(address4, address5); expect(addressAggregator, 'addressAggregator must be 0x').equal( - '0x0000000000000000000000000000000000000000', + '0x6666666666666666666666666666666666666666', ); await conversionPathInstance.updateAggregatorsList( diff --git a/packages/thegraph-data-access/src/data-access.ts b/packages/thegraph-data-access/src/data-access.ts index 273b1ad9d..9078137d8 100644 --- a/packages/thegraph-data-access/src/data-access.ts +++ b/packages/thegraph-data-access/src/data-access.ts @@ -3,7 +3,7 @@ import TypedEmitter from 'typed-emitter'; import { BigNumber } from 'ethers'; -import Utils from '@requestnetwork/utils'; +import { getCurrentTimestampInSecond, retry, SimpleLogger } from '@requestnetwork/utils'; import { Block } from '@requestnetwork/data-access'; import { DataAccessTypes, LogTypes, StorageTypes } from '@requestnetwork/types'; @@ -179,7 +179,7 @@ export class TheGraphDataRead implements DataAccessTypes.IDataRead { transactions: [ { state: DataAccessTypes.TransactionState.PENDING, - timestamp: Utils.getCurrentTimestampInSecond(), + timestamp: getCurrentTimestampInSecond(), transaction, }, ], @@ -219,7 +219,7 @@ export class TheGraphDataWrite implements DataAccessTypes.IDataWrite { private readonly graphql: SubgraphClient, { network, logger, pendingStore }: TheGraphDataAccessBaseOptions, ) { - this.logger = logger || new Utils.SimpleLogger(); + this.logger = logger || new SimpleLogger(); this.network = network; this.pendingStore = pendingStore; } @@ -269,7 +269,7 @@ export class TheGraphDataWrite implements DataAccessTypes.IDataWrite { }; storageResult.on('confirmed', () => { - Utils.retry( + retry( async () => { const response = await this.graphql.getTransactionsByHash(storageResult.id); if (response.transactions.length === 0) { diff --git a/packages/toolbox/src/chainlinkConversionPathTools.ts b/packages/toolbox/src/chainlinkConversionPathTools.ts index 585f9a0f6..b92a3ea41 100644 --- a/packages/toolbox/src/chainlinkConversionPathTools.ts +++ b/packages/toolbox/src/chainlinkConversionPathTools.ts @@ -8,7 +8,7 @@ import { import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import Bluebird from 'bluebird'; import chunk from 'lodash/chunk'; -import Utils from '@requestnetwork/utils'; +import { retry } from '@requestnetwork/utils'; export interface IOptions { network?: string; @@ -75,13 +75,10 @@ class ChainlinkConversionPathTools { chunks, (blocks) => { console.error(`Fetching logs from ${blocks[0]} to ${blocks[blocks.length - 1]}`); - return Utils.retry( - this.chainLinkConversionPath.queryFilter.bind(this.chainLinkConversionPath), - { - maxRetries: 3, - retryDelay: 2000, - }, - )( + return retry(this.chainLinkConversionPath.queryFilter.bind(this.chainLinkConversionPath), { + maxRetries: 3, + retryDelay: 2000, + })( this.chainLinkConversionPath.filters.AggregatorUpdated(), blocks[0], blocks[blocks.length - 1], diff --git a/packages/transaction-manager/src/clear-transaction.ts b/packages/transaction-manager/src/clear-transaction.ts index 52404a364..2a903bb07 100644 --- a/packages/transaction-manager/src/clear-transaction.ts +++ b/packages/transaction-manager/src/clear-transaction.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; import { TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Class representing a clear transaction @@ -27,7 +27,7 @@ export default class ClearTransaction implements TransactionTypes.ITransaction { * @returns a promise resolving the transaction data hash */ public async getHash(): Promise { - return MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(JSON.parse(this.data))); + return MultiFormat.serialize(normalizeKeccak256Hash(JSON.parse(this.data))); } /** diff --git a/packages/transaction-manager/src/encrypted-transaction.ts b/packages/transaction-manager/src/encrypted-transaction.ts index fcfc86eab..3733127ab 100644 --- a/packages/transaction-manager/src/encrypted-transaction.ts +++ b/packages/transaction-manager/src/encrypted-transaction.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; import { EncryptionTypes, TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { decrypt, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Class representing an encrypted transaction @@ -40,7 +40,7 @@ export default class EncryptedTransaction implements TransactionTypes.ITransacti if (this.data === '') { try { const encryptedData = MultiFormat.deserialize(this.persistedData); - this.data = await Utils.encryption.decrypt(encryptedData, this.channelKey); + this.data = await decrypt(encryptedData, this.channelKey); } catch { throw new Error('Impossible to decrypt the transaction'); } @@ -57,7 +57,7 @@ export default class EncryptedTransaction implements TransactionTypes.ITransacti if (this.dataHashSerialized === '') { const data = await this.getData(); try { - const dataHash = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data)); + const dataHash = normalizeKeccak256Hash(JSON.parse(data)); this.dataHashSerialized = MultiFormat.serialize(dataHash); } catch (e) { throw new Error('Impossible to JSON parse the decrypted transaction data'); diff --git a/packages/transaction-manager/src/transaction-manager.ts b/packages/transaction-manager/src/transaction-manager.ts index 427c818c8..d28511105 100644 --- a/packages/transaction-manager/src/transaction-manager.ts +++ b/packages/transaction-manager/src/transaction-manager.ts @@ -5,7 +5,7 @@ import { EncryptionTypes, TransactionTypes, } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; import { EventEmitter } from 'events'; @@ -47,9 +47,7 @@ export default class TransactionManager implements TransactionTypes.ITransaction let channelEncryptionMethod: string | undefined; // compute hash to add it to the topics - const hash = MultiFormat.serialize( - Utils.crypto.normalizeKeccak256Hash(JSON.parse(transactionData)), - ); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(JSON.parse(transactionData))); // Need to create a new channel (only the first transaction can have the hash equals to the channel id) if (channelId === hash) { diff --git a/packages/transaction-manager/src/transactions-factory.ts b/packages/transaction-manager/src/transactions-factory.ts index 658ac3b35..9a639d078 100644 --- a/packages/transaction-manager/src/transactions-factory.ts +++ b/packages/transaction-manager/src/transactions-factory.ts @@ -1,6 +1,10 @@ import MultiFormat from '@requestnetwork/multi-format'; import { EncryptionTypes, TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { + encrypt, + generate32BufferKey, + getIdentityFromEncryptionParams, +} from '@requestnetwork/utils'; /** * Class to create transactions (clear and encrypted) @@ -39,10 +43,10 @@ export default class TransactionsFactory { const encryptionMethod = `${EncryptionTypes.METHOD.ECIES}-${EncryptionTypes.METHOD.AES256_GCM}`; // Generate a key for the AES encryption - const symmetricKey: string = await Utils.crypto.generate32BufferKey(); + const symmetricKey: string = await generate32BufferKey(); // Encrypt the data with the key and the AES256-GCM algorithm - const encryptedData: EncryptionTypes.IEncryptedData = await Utils.encryption.encrypt(data, { + const encryptedData: EncryptionTypes.IEncryptedData = await encrypt(data, { key: symmetricKey, method: EncryptionTypes.METHOD.AES256_GCM, }); @@ -71,12 +75,11 @@ export default class TransactionsFactory { encryptedKey: EncryptionTypes.IEncryptedData; multiFormattedIdentity: string; }> => { - const encryptedKey: EncryptionTypes.IEncryptedData = await Utils.encryption.encrypt( + const encryptedKey: EncryptionTypes.IEncryptedData = await encrypt( symmetricKey, encryptionParam, ); - const identityEncryption = - Utils.encryption.getIdentityFromEncryptionParams(encryptionParam); + const identityEncryption = getIdentityFromEncryptionParams(encryptionParam); const multiFormattedIdentity: string = MultiFormat.serialize(identityEncryption); return { encryptedKey, multiFormattedIdentity }; @@ -123,10 +126,7 @@ export default class TransactionsFactory { } // Encrypt the data with the key and the AES256-GCM algorithm - const encryptedData: EncryptionTypes.IEncryptedData = await Utils.encryption.encrypt( - data, - channelKey, - ); + const encryptedData: EncryptionTypes.IEncryptedData = await encrypt(data, channelKey); try { JSON.parse(data); diff --git a/packages/transaction-manager/test/index.test.ts b/packages/transaction-manager/test/index.test.ts index 0aae90e5d..979aa9ddb 100644 --- a/packages/transaction-manager/test/index.test.ts +++ b/packages/transaction-manager/test/index.test.ts @@ -1,5 +1,5 @@ import MultiFormat from '@requestnetwork/multi-format'; -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; import { EventEmitter } from 'events'; @@ -27,9 +27,9 @@ const tx2: DataAccessTypes.ITimestampedTransaction = { transaction: { data: data2 }, }; -const dataHash = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data)); +const dataHash = normalizeKeccak256Hash(JSON.parse(data)); const channelId = MultiFormat.serialize(dataHash); -const dataHash2 = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data2)); +const dataHash2 = normalizeKeccak256Hash(JSON.parse(data2)); const channelId2 = MultiFormat.serialize(dataHash2); const fakeMetaDataAccessPersistReturn: DataAccessTypes.IReturnPersistTransaction = Object.assign( diff --git a/packages/transaction-manager/test/unit/channel-parser.test.ts b/packages/transaction-manager/test/unit/channel-parser.test.ts index 4441cc7ce..6ad4b4cfa 100644 --- a/packages/transaction-manager/test/unit/channel-parser.test.ts +++ b/packages/transaction-manager/test/unit/channel-parser.test.ts @@ -1,9 +1,9 @@ import MultiFormat from '@requestnetwork/multi-format'; import { TransactionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import ChannelParser from '../../src/channel-parser'; import TransactionsFactory from '../../src/transactions-factory'; import * as TestData from './utils/test-data'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; let channelParser: ChannelParser; @@ -21,9 +21,9 @@ const tx2: TransactionTypes.ITimestampedTransaction = { transaction: { data: data2 }, }; -const dataHash = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data)); +const dataHash = normalizeKeccak256Hash(JSON.parse(data)); const channelId = MultiFormat.serialize(dataHash); -const dataHash2 = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data2)); +const dataHash2 = normalizeKeccak256Hash(JSON.parse(data2)); const channelId2 = MultiFormat.serialize(dataHash2); /* eslint-disable @typescript-eslint/no-unused-expressions */ diff --git a/packages/transaction-manager/test/unit/clear-transaction.test.ts b/packages/transaction-manager/test/unit/clear-transaction.test.ts index e34c119d1..52b1aaf7e 100644 --- a/packages/transaction-manager/test/unit/clear-transaction.test.ts +++ b/packages/transaction-manager/test/unit/clear-transaction.test.ts @@ -1,6 +1,6 @@ import MultiFormat from '@requestnetwork/multi-format'; -import Utils from '@requestnetwork/utils'; import ClearTransaction from '../../src/clear-transaction'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; const data = '{ "what": "ever", "it": "is,", "this": "must", "work": true }'; @@ -21,7 +21,7 @@ describe('clear-transaction', () => { // 'hash not right' expect(await tx.getHash()).toEqual( - MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(JSON.parse(data))), + MultiFormat.serialize(normalizeKeccak256Hash(JSON.parse(data))), ); }); }); diff --git a/packages/transaction-manager/test/unit/encryption-transaction.test.ts b/packages/transaction-manager/test/unit/encryption-transaction.test.ts index 156119639..c42d65ded 100644 --- a/packages/transaction-manager/test/unit/encryption-transaction.test.ts +++ b/packages/transaction-manager/test/unit/encryption-transaction.test.ts @@ -1,11 +1,11 @@ import MultiFormat from '@requestnetwork/multi-format'; import { EncryptionTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import EncryptedTransaction from '../../src/encrypted-transaction'; +import { encrypt, normalizeKeccak256Hash } from '@requestnetwork/utils'; const data = '{ "what": "ever", "it": "is,", "this": "must", "work": true }'; -const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(JSON.parse(data))); +const hash = MultiFormat.serialize(normalizeKeccak256Hash(JSON.parse(data))); const channelKey = { key: 'XYVH7kMWMAy/if+IZ0e7EXMbPVptHd22Xmpr9ktmjRo=', method: EncryptionTypes.METHOD.AES256_CBC, @@ -35,7 +35,7 @@ describe('encryption-transaction', () => { describe('getError', () => { it('can get error of a transaction not parsable', async () => { const encryptedDataNotParsable = MultiFormat.serialize( - await Utils.encryption.encrypt('Not parsable', channelKey), + await encrypt('Not parsable', channelKey), ); const tx = new EncryptedTransaction(encryptedDataNotParsable, channelKey); diff --git a/packages/transaction-manager/test/unit/utils/test-data.ts b/packages/transaction-manager/test/unit/utils/test-data.ts index 821e7de43..8f80914b4 100644 --- a/packages/transaction-manager/test/unit/utils/test-data.ts +++ b/packages/transaction-manager/test/unit/utils/test-data.ts @@ -1,5 +1,5 @@ import { DecryptionProviderTypes, EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { decrypt } from '@requestnetwork/utils'; export const idRaw1 = { address: '0xaf083f77f1ffd54218d91491afd06c9296eac3ce', @@ -65,11 +65,11 @@ export const fakeDecryptionProvider: DecryptionProviderTypes.IDecryptionProvider ): Promise => { switch (identity.value.toLowerCase()) { case idRaw1.address: - return Utils.encryption.decrypt(data, idRaw1.decryptionParams); + return decrypt(data, idRaw1.decryptionParams); case idRaw2.address: - return Utils.encryption.decrypt(data, idRaw2.decryptionParams); + return decrypt(data, idRaw2.decryptionParams); case idRaw3.address: - return Utils.encryption.decrypt(data, idRaw3.decryptionParams); + return decrypt(data, idRaw3.decryptionParams); default: throw new Error('Identity not registered'); } diff --git a/packages/usage-examples/src/mock/mock-storage.ts b/packages/usage-examples/src/mock/mock-storage.ts index 54dfd9103..db4166116 100644 --- a/packages/usage-examples/src/mock/mock-storage.ts +++ b/packages/usage-examples/src/mock/mock-storage.ts @@ -1,7 +1,7 @@ import MultiFormat from '@requestnetwork/multi-format'; import { StorageTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; import { EventEmitter } from 'events'; +import { getCurrentTimestampInSecond, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** * Storage layer implemented with in-memory hashmap, to be used for testing. @@ -23,9 +23,9 @@ export default class MockStorage implements StorageTypes.IStorage { if (!content) { throw Error('Error: no content provided'); } - const hash = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(content)); + const hash = MultiFormat.serialize(normalizeKeccak256Hash(content)); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); this.data[hash] = { content, @@ -84,7 +84,7 @@ export default class MockStorage implements StorageTypes.IStorage { }, })); - const nowTimestampInSec = Utils.getCurrentTimestampInSecond(); + const nowTimestampInSec = getCurrentTimestampInSecond(); return { entries, diff --git a/packages/utils/README.md b/packages/utils/README.md index 0198b2855..c5e07b8bd 100644 --- a/packages/utils/README.md +++ b/packages/utils/README.md @@ -4,16 +4,16 @@ It is a collection of tools shared between the @requestnetwork packages. - Elliptic curve crypto and signature - - crypto.normalizeKeccak256Hash() - - crypto.ecUtils.getAddressFromPrivateKey() - - crypto.ecUtils.recover() - - crypto.ecUtils.sign() - - signature.getIdentityFromSignatureParams() - - signature.recover() - - signature.sign() + - normalizeKeccak256Hash() + - EcUtils.getAddressFromPrivateKey() + - EcUtils.recover() + - EcUtils.sign() + - getIdentityFromSignatureParams() + - recover() + - sign() - Identity - - identity.areEqual() - - identity.normalizeIdentityValue() + - areEqual() + - normalizeIdentityValue() - isString - Miscellaneous - deepCopy() @@ -30,9 +30,9 @@ npm install @requestnetwork/utils ## Usage ```javascript -import Utils from '@requestnetwork/utils'; +import { normalizeKeccak256Hash } from '@requestnetwork/utils'; -const hash = Utils.crypto.normalizeKeccak256Hash({ exampleData: true }); +const hash = normalizeKeccak256Hash({ exampleData: true }); ``` ## Contributing diff --git a/packages/utils/test/crypto.test.ts b/packages/utils/test/crypto.test.ts index add011527..4647b33e2 100644 --- a/packages/utils/test/crypto.test.ts +++ b/packages/utils/test/crypto.test.ts @@ -8,7 +8,7 @@ import { } from '../src'; /* eslint-disable @typescript-eslint/no-unused-expressions */ -describe('Utils.crypto', () => { +describe('Utils/crypto', () => { it('can normalizeKeccak256Hash', () => { const arbitraryObject = { param1: 'valC', diff --git a/packages/utils/test/crypto/crypto-wrapper.test.ts b/packages/utils/test/crypto/crypto-wrapper.test.ts index 4b1cb647a..05ea73cfa 100644 --- a/packages/utils/test/crypto/crypto-wrapper.test.ts +++ b/packages/utils/test/crypto/crypto-wrapper.test.ts @@ -4,7 +4,7 @@ const anyData = 'this is any data!'; const arbitraryKey = '12345678901234567890123456789012'; /* eslint-disable @typescript-eslint/no-unused-expressions */ -describe('Utils.cryptoWrapper', () => { +describe('Utils/cryptoWrapper', () => { describe('random32Bytes', () => { it('can create a 32 bytes buffer', async () => { const randomBytes = await CryptoWrapper.random32Bytes(); diff --git a/packages/web3-signature/src/web3-signature-provider.ts b/packages/web3-signature/src/web3-signature-provider.ts index 64949eddc..00d3d5495 100644 --- a/packages/web3-signature/src/web3-signature-provider.ts +++ b/packages/web3-signature/src/web3-signature-provider.ts @@ -1,6 +1,6 @@ import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import Utils from '@requestnetwork/utils'; +import { areEqual, normalize, recover } from '@requestnetwork/utils'; import { providers } from 'ethers'; @@ -41,7 +41,7 @@ export default class Web3SignatureProvider implements SignatureProviderTypes.ISi throw Error(`Identity type not supported ${signer.type}`); } - const normalizedData = Utils.crypto.normalize(data); + const normalizedData = normalize(data); const signerEthers = this.web3Provider.getSigner(signer.value); let signatureValue; @@ -82,7 +82,7 @@ export default class Web3SignatureProvider implements SignatureProviderTypes.ISi value, }, }; - if (Utils.identity.areEqual(Utils.signature.recover(signedData), signer)) { + if (areEqual(recover(signedData), signer)) { return signedData; } return null; diff --git a/packages/web3-signature/test/web3-signature-provider.test.ts b/packages/web3-signature/test/web3-signature-provider.test.ts index e34f38f83..eae6173f2 100644 --- a/packages/web3-signature/test/web3-signature-provider.test.ts +++ b/packages/web3-signature/test/web3-signature-provider.test.ts @@ -2,7 +2,7 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import Web3SignatureProvider from '../src/web3-signature-provider'; -import Utils from '@requestnetwork/utils'; +import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; const id1Raw = { identity: { @@ -16,11 +16,8 @@ const id1Raw = { }; const data = { What: 'ever', the: 'data', are: true }; -const hashData = Utils.crypto.normalizeKeccak256Hash(data).value; -const signatureValueExpected = Utils.crypto.EcUtils.sign( - id1Raw.signatureParams.privateKey, - hashData, -); +const hashData = normalizeKeccak256Hash(data).value; +const signatureValueExpected = EcUtils.sign(id1Raw.signatureParams.privateKey, hashData); const mockWeb3: any = { getSigner: jest.fn().mockImplementation(() => ({ From 3513f0e864326931ec678143aa9c6a52ae1a086f Mon Sep 17 00:00:00 2001 From: marcohefti Date: Sun, 25 Dec 2022 14:54:42 +0700 Subject: [PATCH 09/13] Apply changes to utils package to payment-processor/test/payment/any-to-near.test.ts --- .../payment-processor/test/payment/any-to-near.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/payment-processor/test/payment/any-to-near.test.ts b/packages/payment-processor/test/payment/any-to-near.test.ts index 8d43edb0d..323bce6a0 100644 --- a/packages/payment-processor/test/payment/any-to-near.test.ts +++ b/packages/payment-processor/test/payment/any-to-near.test.ts @@ -1,10 +1,10 @@ import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; import { PaymentReferenceCalculator } from '@requestnetwork/payment-detection'; -import * as Utils from '@requestnetwork/utils'; import { IConversionPaymentSettings, _getPaymentUrl } from '../../src/payment'; import * as nearUtils from '../../src/payment/utils-near'; import { payNearConversionRequest } from '../../src/payment/near-conversion'; +import { deepCopy } from '@requestnetwork/utils'; /* eslint-disable @typescript-eslint/no-unused-expressions */ /* eslint-disable @typescript-eslint/await-thenable */ @@ -101,7 +101,7 @@ describe('payNearWithConversionRequest', () => { state: () => Promise.resolve({ amount: 100 }), }), } as any; - let invalidRequest = Utils.default.deepCopy(request); + let invalidRequest = deepCopy(request); invalidRequest = { ...invalidRequest, extensions: { @@ -129,7 +129,7 @@ describe('payNearWithConversionRequest', () => { state: () => Promise.resolve({ amount: 100 }), }), } as any; - let invalidRequest = Utils.default.deepCopy(request); + let invalidRequest = deepCopy(request); invalidRequest = { ...invalidRequest, currencyInfo: { @@ -154,7 +154,7 @@ describe('payNearWithConversionRequest', () => { state: () => Promise.resolve({ amount: 100 }), }), } as any; - let invalidRequest = Utils.default.deepCopy(request); + let invalidRequest = deepCopy(request); invalidRequest = { ...invalidRequest, extensions: { From e734d6b5f6a6d5bb12e8b61c315df59cc7476524 Mon Sep 17 00:00:00 2001 From: marcohefti Date: Wed, 4 Jan 2023 16:54:32 +0700 Subject: [PATCH 10/13] fix circular dependency by importing from the corresponding package rather from the same package barrel file --- .../payment-detection/src/any/retrievers/any-to-any-proxy.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts b/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts index adba109f1..3963d2949 100644 --- a/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts +++ b/packages/payment-detection/src/any/retrievers/any-to-any-proxy.ts @@ -3,7 +3,7 @@ import { PaymentTypes } from '@requestnetwork/types'; import { BigNumber, ethers } from 'ethers'; import { parseLogArgs, unpadAmountFromChainlink } from '../../utils'; import type { JsonFragment } from '@ethersproject/abi'; -import { getDefaultProvider } from '../../index'; +import { getDefaultProvider } from '@requestnetwork/utils'; /** TransferWithConversionAndReference event */ type TransferWithConversionAndReferenceArgs = { From c2d550493dad57b2051e0f7741e55aae54709aa7 Mon Sep 17 00:00:00 2001 From: marcohefti Date: Tue, 10 Jan 2023 15:31:13 +0700 Subject: [PATCH 11/13] Resolves #1023: Rename ambiguous functions for clarity As discussed with @alexandre-abrioux and @benjlevesque, many of the functions in the utils module have been refactored and need to be renamed for improved code readability. Signed-off-by: marcohefti --- .../payment-network/address-based.ts | 6 +- .../extensions/payment-network/declarative.ts | 27 +++--- .../payment-network/erc777/stream.ts | 6 +- .../payment-network/fee-reference-based.ts | 18 ++-- .../test/api/request-network.test.ts | 4 +- .../test/data-test-real-btc.ts | 4 +- packages/request-client.js/test/data-test.ts | 24 +++-- .../test/declarative-payments.test.ts | 4 +- .../request-logic/specs/example/example.ts | 6 +- packages/request-logic/src/action.ts | 4 +- packages/request-logic/src/actions/create.ts | 24 ++--- .../src/actions/increaseExpectedAmount.ts | 11 ++- .../src/actions/reduceExpectedAmount.ts | 8 +- packages/request-logic/src/request.ts | 4 +- packages/request-logic/src/role.ts | 6 +- packages/request-logic/test/index.test.ts | 90 +++++++++---------- .../test/unit/utils/test-data-generator.ts | 8 +- packages/utils/src/amount.ts | 18 ++-- packages/utils/src/bignumber.ts | 6 +- packages/utils/src/crypto.ts | 8 +- packages/utils/src/estimate-gas-fees.ts | 6 +- packages/utils/src/identity.ts | 6 +- packages/utils/src/index.ts | 15 ++-- packages/utils/src/signature.ts | 12 +-- packages/utils/test/amount.test.ts | 42 ++++----- packages/utils/test/bignumber.test.ts | 18 ++-- packages/utils/test/crypto.test.ts | 10 +-- packages/utils/test/identity.test.ts | 20 ++--- packages/utils/test/signature.test.ts | 49 +++++----- .../src/web3-signature-provider.ts | 6 +- 30 files changed, 249 insertions(+), 221 deletions(-) diff --git a/packages/advanced-logic/src/extensions/payment-network/address-based.ts b/packages/advanced-logic/src/extensions/payment-network/address-based.ts index 2588f8a57..a21350b02 100644 --- a/packages/advanced-logic/src/extensions/payment-network/address-based.ts +++ b/packages/advanced-logic/src/extensions/payment-network/address-based.ts @@ -1,6 +1,6 @@ import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import { areEqual, deepCopy } from '@requestnetwork/utils'; +import { areEqualIdentities, deepCopy } from '@requestnetwork/utils'; import DeclarativePaymentNetwork from './declarative'; /** @@ -194,7 +194,7 @@ export default abstract class AddressBasedPaymentNetwork< if (!requestState.payee) { throw Error(`The request must have a payee`); } - if (!areEqual(actionSigner, requestState.payee)) { + if (!areEqualIdentities(actionSigner, requestState.payee)) { throw Error(`The signer must be the payee`); } @@ -241,7 +241,7 @@ export default abstract class AddressBasedPaymentNetwork< if (!requestState.payer) { throw Error(`The request must have a payer`); } - if (!areEqual(actionSigner, requestState.payer)) { + if (!areEqualIdentities(actionSigner, requestState.payer)) { throw Error(`The signer must be the payer`); } diff --git a/packages/advanced-logic/src/extensions/payment-network/declarative.ts b/packages/advanced-logic/src/extensions/payment-network/declarative.ts index 114e79453..634f21cc7 100644 --- a/packages/advanced-logic/src/extensions/payment-network/declarative.ts +++ b/packages/advanced-logic/src/extensions/payment-network/declarative.ts @@ -1,5 +1,5 @@ import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import { add, areEqual, deepCopy, isValid } from '@requestnetwork/utils'; +import { addAmount, areEqualIdentities, deepCopy, isValidAmount } from '@requestnetwork/utils'; import { AbstractExtension } from '../abstract-extension'; const CURRENT_VERSION = '0.1.0'; @@ -239,14 +239,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER); - if (!isValid(extensionAction.parameters.amount)) { + if (!isValidAmount(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment sentPaymentAmount - copiedExtensionState.values.sentPaymentAmount = add( + copiedExtensionState.values.sentPaymentAmount = addAmount( copiedExtensionState.values.sentPaymentAmount, extensionAction.parameters.amount, ); @@ -285,14 +285,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE); - if (!isValid(extensionAction.parameters.amount)) { + if (!isValidAmount(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment sentRefundAmount - copiedExtensionState.values.sentRefundAmount = add( + copiedExtensionState.values.sentRefundAmount = addAmount( copiedExtensionState.values.sentRefundAmount, extensionAction.parameters.amount, ); @@ -331,14 +331,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYEE); - if (!isValid(extensionAction.parameters.amount)) { + if (!isValidAmount(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment receivedPaymentAmount - copiedExtensionState.values.receivedPaymentAmount = add( + copiedExtensionState.values.receivedPaymentAmount = addAmount( copiedExtensionState.values.receivedPaymentAmount, extensionAction.parameters.amount, ); @@ -377,14 +377,14 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { this.checkIdentities(extensionState, requestState, actionSigner, RequestLogicTypes.ROLE.PAYER); - if (!isValid(extensionAction.parameters.amount)) { + if (!isValidAmount(extensionAction.parameters.amount)) { throw Error(`The amount is not a valid amount`); } const copiedExtensionState: ExtensionTypes.IState = deepCopy(extensionState); // increment receivedRefundAmount - copiedExtensionState.values.receivedRefundAmount = add( + copiedExtensionState.values.receivedRefundAmount = addAmount( copiedExtensionState.values.receivedRefundAmount, extensionAction.parameters.amount, ); @@ -463,9 +463,9 @@ export default class DeclarativePaymentNetwork< timestamp: number, ): ExtensionTypes.IState { let delegateStr: string; - if (areEqual(actionSigner, requestState.payee)) { + if (areEqualIdentities(actionSigner, requestState.payee)) { delegateStr = 'payeeDelegate'; - } else if (areEqual(actionSigner, requestState.payer)) { + } else if (areEqualIdentities(actionSigner, requestState.payer)) { delegateStr = 'payerDelegate'; } else { throw Error(`The signer must be the payee or the payer`); @@ -566,7 +566,10 @@ export default class DeclarativePaymentNetwork< if (!requestRole) { throw Error(`The request must have a ${requestRoleStr}`); } - if (!areEqual(actionSigner, requestRole) && !areEqual(actionSigner, requestRoleDelegate)) { + if ( + !areEqualIdentities(actionSigner, requestRole) && + !areEqualIdentities(actionSigner, requestRoleDelegate) + ) { throw Error(`The signer must be the ${requestRoleStr} or the ${requestRoleStr}Delegate`); } } diff --git a/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts b/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts index 2ceda2206..1b8e2da50 100644 --- a/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts +++ b/packages/advanced-logic/src/extensions/payment-network/erc777/stream.ts @@ -1,6 +1,6 @@ import { ExtensionTypes, RequestLogicTypes, TypesUtils } from '@requestnetwork/types'; import ReferenceBasedPaymentNetwork from '../reference-based'; -import { isValid } from '@requestnetwork/utils'; +import { isValidAmount } from '@requestnetwork/utils'; const CURRENT_VERSION = '0.1.0'; /** @@ -92,7 +92,7 @@ export default class Erc777StreamPaymentNetwork< if ( !extensionAction.parameters.expectedStartDate || (extensionAction.parameters.expectedStartDate && - !isValid(extensionAction.parameters.expectedStartDate)) + !isValidAmount(extensionAction.parameters.expectedStartDate)) ) { throw Error('expectedStartDate is empty or invalid'); } @@ -100,7 +100,7 @@ export default class Erc777StreamPaymentNetwork< if ( !extensionAction.parameters.expectedFlowRate || (extensionAction.parameters.expectedFlowRate && - !isValid(extensionAction.parameters.expectedFlowRate)) + !isValidAmount(extensionAction.parameters.expectedFlowRate)) ) { throw Error('expectedFlowRate is empty or invalid'); } diff --git a/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts b/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts index e4defca02..132f264ff 100644 --- a/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts +++ b/packages/advanced-logic/src/extensions/payment-network/fee-reference-based.ts @@ -1,6 +1,6 @@ import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; import ReferenceBasedPaymentNetwork from './reference-based'; -import { areEqual, deepCopy, isValid } from '@requestnetwork/utils'; +import { areEqualIdentities, deepCopy, isValidAmount } from '@requestnetwork/utils'; /** * Core of the reference based with fee payment networks @@ -35,7 +35,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< throw Error('feeAddress is not a valid address'); } - if (creationParameters.feeAmount && !isValid(creationParameters.feeAmount)) { + if (creationParameters.feeAmount && !isValidAmount(creationParameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -65,7 +65,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< throw Error('feeAddress is not a valid address'); } - if (addFeeParameters.feeAmount && !isValid(addFeeParameters.feeAmount)) { + if (addFeeParameters.feeAmount && !isValidAmount(addFeeParameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -101,7 +101,10 @@ export abstract class FeeReferenceBasedPaymentNetwork< ) { throw Error('feeAddress is not a valid address'); } - if (extensionAction.parameters.feeAmount && !isValid(extensionAction.parameters.feeAmount)) { + if ( + extensionAction.parameters.feeAmount && + !isValidAmount(extensionAction.parameters.feeAmount) + ) { throw Error('feeAmount is not a valid amount'); } @@ -157,7 +160,10 @@ export abstract class FeeReferenceBasedPaymentNetwork< if (extensionState.values.feeAddress) { throw Error(`Fee address already given`); } - if (extensionAction.parameters.feeAmount && !isValid(extensionAction.parameters.feeAmount)) { + if ( + extensionAction.parameters.feeAmount && + !isValidAmount(extensionAction.parameters.feeAmount) + ) { throw Error('feeAmount is not a valid amount'); } if (extensionState.values.feeAmount) { @@ -166,7 +172,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< if (!requestState.payee) { throw Error(`The request must have a payee`); } - if (!areEqual(actionSigner, requestState.payee)) { + if (!areEqualIdentities(actionSigner, requestState.payee)) { throw Error(`The signer must be the payee`); } diff --git a/packages/request-client.js/test/api/request-network.test.ts b/packages/request-client.js/test/api/request-network.test.ts index fed1c9dd8..1b3c0249b 100644 --- a/packages/request-client.js/test/api/request-network.test.ts +++ b/packages/request-client.js/test/api/request-network.test.ts @@ -6,7 +6,7 @@ import RequestNetwork from '../../src/api/request-network'; import Request from '../../src/api/request'; import * as TestData from '../data-test'; -import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, signSignature } from '@requestnetwork/utils'; const mockDataAccess: DataAccessTypes.IDataAccess = { _getStatus: jest.fn(), @@ -59,7 +59,7 @@ describe('api/request-network', () => { timestamp: 1549953337, transaction: { data: 'broken transaction' }, }; - const actionWrongSigner = sign(TestData.data, { + const actionWrongSigner = signSignature(TestData.data, { method: SignatureTypes.METHOD.ECDSA, privateKey: '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', }); diff --git a/packages/request-client.js/test/data-test-real-btc.ts b/packages/request-client.js/test/data-test-real-btc.ts index 6ed341a2c..3fb9c3853 100644 --- a/packages/request-client.js/test/data-test-real-btc.ts +++ b/packages/request-client.js/test/data-test-real-btc.ts @@ -4,7 +4,7 @@ import { SignatureTypes, TransactionTypes, } from '@requestnetwork/types'; -import { sign } from '@requestnetwork/utils'; +import { signSignature } from '@requestnetwork/utils'; const payee = { identity: { @@ -50,7 +50,7 @@ export const data = { version: '2.0.3', }; -export const action: RequestLogicTypes.IAction = sign(data, payee.signatureParams); +export const action: RequestLogicTypes.IAction = signSignature(data, payee.signatureParams); export const timestampedTransaction: TransactionTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, diff --git a/packages/request-client.js/test/data-test.ts b/packages/request-client.js/test/data-test.ts index 74b625611..6f56eeaf0 100644 --- a/packages/request-client.js/test/data-test.ts +++ b/packages/request-client.js/test/data-test.ts @@ -8,7 +8,7 @@ import { SignatureTypes, TransactionTypes, } from '@requestnetwork/types'; -import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, signSignature } from '@requestnetwork/utils'; import AxiosMockAdapter from 'axios-mock-adapter'; import axios from 'axios'; import { Types } from '../src'; @@ -155,12 +155,15 @@ const dataWithDeclarativeNoPaymentInfo = { version: '2.0.3', }; -export const action: RequestLogicTypes.IAction = sign(dataWithDeclarative, payee.signatureParams); -const actionWithoutExtensionsData: RequestLogicTypes.IAction = sign( +export const action: RequestLogicTypes.IAction = signSignature( + dataWithDeclarative, + payee.signatureParams, +); +const actionWithoutExtensionsData: RequestLogicTypes.IAction = signSignature( dataWithoutExtensionsData, payee.signatureParams, ); -const actionWithoutPaymentInfo: RequestLogicTypes.IAction = sign( +const actionWithoutPaymentInfo: RequestLogicTypes.IAction = signSignature( dataWithDeclarativeNoPaymentInfo, payee.signatureParams, ); @@ -190,7 +193,10 @@ export const timestampedTransactionWithoutPaymentInfo: TransactionTypes.ITimesta export const actionRequestId = MultiFormat.serialize(normalizeKeccak256Hash(action)); -export const anotherCreationAction: RequestLogicTypes.IAction = sign(data, payer.signatureParams); +export const anotherCreationAction: RequestLogicTypes.IAction = signSignature( + data, + payer.signatureParams, +); export const anotherCreationTransactionConfirmed: TransactionTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, @@ -214,7 +220,7 @@ const dataSecondRequest = { version: '2.0.3', }; -export const actionCreationSecondRequest: RequestLogicTypes.IAction = sign( +export const actionCreationSecondRequest: RequestLogicTypes.IAction = signSignature( dataSecondRequest, payee.signatureParams, ); @@ -259,11 +265,11 @@ export const signatureParametersDelegate: SignatureTypes.ISignatureParameters = export const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, signer: IdentityTypes.IIdentity): any => { if (signer.value === payee.identity.value) { - return sign(data, signatureParametersPayee); + return signSignature(data, signatureParametersPayee); } else if (signer.value === payer.identity.value) { - return sign(data, signatureParametersPayer); + return signSignature(data, signatureParametersPayer); } else { - return sign(data, signatureParametersDelegate); + return signSignature(data, signatureParametersDelegate); } }, supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], diff --git a/packages/request-client.js/test/declarative-payments.test.ts b/packages/request-client.js/test/declarative-payments.test.ts index 54a1fd9de..1b3096694 100644 --- a/packages/request-client.js/test/declarative-payments.test.ts +++ b/packages/request-client.js/test/declarative-payments.test.ts @@ -20,7 +20,7 @@ import { } from '@requestnetwork/payment-detection'; import { IRequestDataWithEvents } from '../src/types'; import { CurrencyManager } from '@requestnetwork/currency'; -import { sign } from '@requestnetwork/utils'; +import { signSignature } from '@requestnetwork/utils'; const httpConfig: Partial = { getConfirmationDeferDelay: 0, @@ -417,7 +417,7 @@ describe('request-client.js: declarative payments', () => { timestamp: TestData.arbitraryTimestamp, transaction: { data: JSON.stringify( - sign( + signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { diff --git a/packages/request-logic/specs/example/example.ts b/packages/request-logic/specs/example/example.ts index 69f4915b2..847608f62 100644 --- a/packages/request-logic/specs/example/example.ts +++ b/packages/request-logic/specs/example/example.ts @@ -8,7 +8,7 @@ import { } from '@requestnetwork/types'; import RequestLogic from '../../src/requestLogicCore'; -import { sign } from '@requestnetwork/utils'; +import { signSignature } from '@requestnetwork/utils'; async function foo(): Promise { // Bob (the payee) @@ -38,8 +38,8 @@ async function foo(): Promise { const signatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, identity: IdentityTypes.IIdentity): any => ({ - [aliceRaw.identity.value as string]: sign(data, aliceRaw.signatureParams), - [bobRaw.identity.value as string]: sign(data, bobRaw.signatureParams), + [aliceRaw.identity.value as string]: signSignature(data, aliceRaw.signatureParams), + [bobRaw.identity.value as string]: signSignature(data, bobRaw.signatureParams), }[identity.value]), supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], supportedMethods: [SignatureTypes.METHOD.ECDSA], diff --git a/packages/request-logic/src/action.ts b/packages/request-logic/src/action.ts index 5118c9587..1da075bfb 100644 --- a/packages/request-logic/src/action.ts +++ b/packages/request-logic/src/action.ts @@ -3,7 +3,7 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@reque import * as Semver from 'semver'; import Role from './role'; import Version from './version'; -import { normalizeKeccak256Hash, recover } from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, recoverSignature } from '@requestnetwork/utils'; /** * Function to manage Request logic action (object that will be interpreted to create or modify a request) @@ -45,7 +45,7 @@ function createAction( * @returns RequestEnum.ROLE the role of the signer (payee, payer or third party) */ function getSignerIdentityFromAction(action: RequestLogicTypes.IAction): IdentityTypes.IIdentity { - return recover(action); + return recoverSignature(action); } /** diff --git a/packages/request-logic/src/actions/create.ts b/packages/request-logic/src/actions/create.ts index 8afda7b6c..ff2f745ad 100644 --- a/packages/request-logic/src/actions/create.ts +++ b/packages/request-logic/src/actions/create.ts @@ -5,9 +5,9 @@ import Version from '../version'; import { deepCopy, getCurrentTimestampInSecond, - hasError, + hasErrorIdentities, isString, - isValid, + isValidAmount, } from '@requestnetwork/utils'; /** @@ -38,16 +38,16 @@ function format( throw new Error('payee or PayerId must be given'); } - if (!isValid(requestParameters.expectedAmount)) { + if (!isValidAmount(requestParameters.expectedAmount)) { throw new Error('expectedAmount must be a positive integer'); } - if (requestParameters.payee && hasError(requestParameters.payee)) { - throw new Error(`payee: ${hasError(requestParameters.payee)}̀`); + if (requestParameters.payee && hasErrorIdentities(requestParameters.payee)) { + throw new Error(`payee: ${hasErrorIdentities(requestParameters.payee)}̀`); } - if (requestParameters.payer && hasError(requestParameters.payer)) { - throw new Error(`payer: ${hasError(requestParameters.payer)}̀`); + if (requestParameters.payer && hasErrorIdentities(requestParameters.payer)) { + throw new Error(`payer: ${hasErrorIdentities(requestParameters.payer)}̀`); } if (!requestParameters.timestamp) { @@ -91,17 +91,17 @@ function createRequest( throw new Error('action.parameters.payee or action.parameters.payer must be given'); } - if (action.data.parameters.payee && hasError(action.data.parameters.payee)) { - throw new Error(`payee: ${hasError(action.data.parameters.payee)}̀`); + if (action.data.parameters.payee && hasErrorIdentities(action.data.parameters.payee)) { + throw new Error(`payee: ${hasErrorIdentities(action.data.parameters.payee)}̀`); } - if (action.data.parameters.payer && hasError(action.data.parameters.payer)) { - throw new Error(`payer: ${hasError(action.data.parameters.payer)}̀`); + if (action.data.parameters.payer && hasErrorIdentities(action.data.parameters.payer)) { + throw new Error(`payer: ${hasErrorIdentities(action.data.parameters.payer)}̀`); } if ( !isString(action.data.parameters.expectedAmount) || - !isValid(action.data.parameters.expectedAmount) + !isValidAmount(action.data.parameters.expectedAmount) ) { throw new Error( 'action.parameters.expectedAmount must be a string representing a positive integer', diff --git a/packages/request-logic/src/actions/increaseExpectedAmount.ts b/packages/request-logic/src/actions/increaseExpectedAmount.ts index efe65cc25..f273b092d 100644 --- a/packages/request-logic/src/actions/increaseExpectedAmount.ts +++ b/packages/request-logic/src/actions/increaseExpectedAmount.ts @@ -3,7 +3,7 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@reque import Action from '../action'; import Request from '../request'; import Version from '../version'; -import { add, deepCopy, isValid } from '@requestnetwork/utils'; +import { addAmount, deepCopy, isValidAmount } from '@requestnetwork/utils'; /** * Implementation of the action increaseExpectedAmount from request logic specification @@ -27,7 +27,7 @@ function format( signerIdentity: IdentityTypes.IIdentity, signatureProvider: SignatureProviderTypes.ISignatureProvider, ): Promise { - if (!isValid(increaseAmountParameters.deltaAmount)) { + if (!isValidAmount(increaseAmountParameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -61,7 +61,7 @@ function applyActionToRequest( if (!action.data.parameters.deltaAmount) { throw new Error('deltaAmount must be given'); } - if (!isValid(action.data.parameters.deltaAmount)) { + if (!isValidAmount(action.data.parameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -78,7 +78,10 @@ function applyActionToRequest( throw new Error('the request must not be canceled'); } // increase the expected amount and store it as string - requestCopied.expectedAmount = add(request.expectedAmount, action.data.parameters.deltaAmount); + requestCopied.expectedAmount = addAmount( + request.expectedAmount, + action.data.parameters.deltaAmount, + ); return requestCopied; } diff --git a/packages/request-logic/src/actions/reduceExpectedAmount.ts b/packages/request-logic/src/actions/reduceExpectedAmount.ts index b418d5f70..dfc0485a6 100644 --- a/packages/request-logic/src/actions/reduceExpectedAmount.ts +++ b/packages/request-logic/src/actions/reduceExpectedAmount.ts @@ -3,7 +3,7 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@reque import Action from '../action'; import Request from '../request'; import Version from '../version'; -import { deepCopy, isValid, reduce } from '@requestnetwork/utils'; +import { deepCopy, isValidAmount, reduceAmount } from '@requestnetwork/utils'; /** * Implementation of the action reduceExpectedAmount from request logic specification @@ -27,7 +27,7 @@ function format( signerIdentity: IdentityTypes.IIdentity, signatureProvider: SignatureProviderTypes.ISignatureProvider, ): Promise { - if (!isValid(reduceAmountParameters.deltaAmount)) { + if (!isValidAmount(reduceAmountParameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -61,7 +61,7 @@ function applyActionToRequest( if (!action.data.parameters.deltaAmount) { throw new Error('deltaAmount must be given'); } - if (!isValid(action.data.parameters.deltaAmount)) { + if (!isValidAmount(action.data.parameters.deltaAmount)) { throw new Error('deltaAmount must be a string representing a positive integer'); } @@ -78,7 +78,7 @@ function applyActionToRequest( throw new Error('the request must not be canceled'); } // reduce the expected amount and store it as string or throw if the result is not valid - requestCopied.expectedAmount = reduce( + requestCopied.expectedAmount = reduceAmount( request.expectedAmount, action.data.parameters.deltaAmount, ); diff --git a/packages/request-logic/src/request.ts b/packages/request-logic/src/request.ts index 4e40289ae..04b8720e6 100644 --- a/packages/request-logic/src/request.ts +++ b/packages/request-logic/src/request.ts @@ -1,7 +1,7 @@ import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; import Role from './role'; -import { isValid } from '@requestnetwork/utils'; +import { isValidAmount } from '@requestnetwork/utils'; /** * Module to manage a request @@ -63,7 +63,7 @@ function checkRequest(request: RequestLogicTypes.IRequest): boolean { if (request.payer && request.payer.type !== IdentityTypes.TYPE.ETHEREUM_ADDRESS) { throw Error('request.payer.type not supported'); } - if (!isValid(request.expectedAmount)) { + if (!isValidAmount(request.expectedAmount)) { throw Error('expectedAmount must be a positive integer'); } return true; diff --git a/packages/request-logic/src/role.ts b/packages/request-logic/src/role.ts index 16933a660..b91839216 100644 --- a/packages/request-logic/src/role.ts +++ b/packages/request-logic/src/role.ts @@ -1,5 +1,5 @@ import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; -import { areEqual } from '@requestnetwork/utils'; +import { areEqualIdentities } from '@requestnetwork/utils'; /** * Function to manage Request Logic Role @@ -17,10 +17,10 @@ export default { * @returns Types.ROLE the role of identity in parameters */ function getRole(identity: IdentityTypes.IIdentity, parameters: any): RequestLogicTypes.ROLE { - if (parameters.payee && areEqual(parameters.payee, identity)) { + if (parameters.payee && areEqualIdentities(parameters.payee, identity)) { return RequestLogicTypes.ROLE.PAYEE; } - if (parameters.payer && areEqual(parameters.payer, identity)) { + if (parameters.payer && areEqualIdentities(parameters.payer, identity)) { return RequestLogicTypes.ROLE.PAYER; } diff --git a/packages/request-logic/test/index.test.ts b/packages/request-logic/test/index.test.ts index d0b3cbd0d..67ff7e613 100644 --- a/packages/request-logic/test/index.test.ts +++ b/packages/request-logic/test/index.test.ts @@ -7,7 +7,7 @@ import { RequestLogic } from '../src/index'; import * as TestData from './unit/utils/test-data-generator'; import Version from '../src/version'; -import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, signSignature } from '@requestnetwork/utils'; const CURRENT_VERSION = Version.currentVersion; @@ -26,7 +26,7 @@ const unsignedAction: RequestLogicTypes.IUnsignedAction = { parameters: createParams, version: CURRENT_VERSION, }; -const action = sign(unsignedAction, TestData.payeeRaw.signatureParams); +const action = signSignature(unsignedAction, TestData.payeeRaw.signatureParams); const requestId = MultiFormat.serialize(normalizeKeccak256Hash(action)); const fakeTxHash = '01aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; @@ -496,7 +496,7 @@ describe('index', () => { }); it('cannot accept as payee', async () => { - const actionCreate = sign( + const actionCreate = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -592,7 +592,7 @@ describe('index', () => { }); it('cannot cancel if not payee or payer', async () => { - const actionCreate = sign( + const actionCreate = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -693,7 +693,7 @@ describe('index', () => { ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot increaseExpectedAmountRequest as payee', async () => { - const actionCreate = sign( + const actionCreate = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -799,7 +799,7 @@ describe('index', () => { ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot reduceExpectedAmountRequest as payer', async () => { - const actionCreate = sign( + const actionCreate = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -908,7 +908,7 @@ describe('index', () => { }, }; - const actionCreate = sign( + const actionCreate = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -962,7 +962,7 @@ describe('index', () => { describe('getRequestFromId', () => { it('can getRequestFromId', async () => { - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -980,7 +980,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = sign( + const actionAccept: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -991,7 +991,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = sign( + const rxReduce: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1098,7 +1098,7 @@ describe('index', () => { }); it('can getRequestFromId ignore old pending transaction', async () => { - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1116,7 +1116,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = sign( + const actionAccept: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1127,7 +1127,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = sign( + const rxReduce: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1237,7 +1237,7 @@ describe('index', () => { }); it('can getRequestFromId with pending transaction', async () => { - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1255,7 +1255,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = sign( + const actionAccept: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1266,7 +1266,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = sign( + const rxReduce: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1376,7 +1376,7 @@ describe('index', () => { }); it('can getRequestFromId ignore the same transactions even with different case', async () => { - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1394,7 +1394,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = sign( + const actionAccept: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1405,7 +1405,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const actionReduce: RequestLogicTypes.IAction = sign( + const actionReduce: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1417,7 +1417,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionReduce2: RequestLogicTypes.IAction = sign( + const actionReduce2: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1538,7 +1538,7 @@ describe('index', () => { }); it('can getRequestFromId do not ignore the same transactions if different nonces', async () => { - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1556,7 +1556,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = sign( + const actionAccept: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1567,7 +1567,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const actionReduce: RequestLogicTypes.IAction = sign( + const actionReduce: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1579,7 +1579,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionReduce2: RequestLogicTypes.IAction = sign( + const actionReduce2: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1736,7 +1736,7 @@ describe('index', () => { }); it('should ignored the corrupted data (e.g: wrong properties)', async () => { - const actionCorrupted: RequestLogicTypes.IAction = sign( + const actionCorrupted: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1811,13 +1811,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = sign( + const actionAccept: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1828,7 +1828,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = sign( + const rxReduce: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1854,13 +1854,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = sign( + const actionCreate2: RequestLogicTypes.IAction = signSignature( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = sign( + const actionCancel2: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -1885,7 +1885,7 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = sign( + const actionCreate3: RequestLogicTypes.IAction = signSignature( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); @@ -1974,13 +1974,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = sign( + const actionAccept: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1991,7 +1991,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = sign( + const rxReduce: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -2017,13 +2017,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = sign( + const actionCreate2: RequestLogicTypes.IAction = signSignature( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = sign( + const actionCancel2: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -2048,7 +2048,7 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = sign( + const actionCreate3: RequestLogicTypes.IAction = signSignature( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); @@ -2143,7 +2143,7 @@ describe('index', () => { }); it('should ignore the transaction none parsable and the rejected action', async () => { - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -2161,7 +2161,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const acceptNotValid: RequestLogicTypes.IAction = sign( + const acceptNotValid: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -2238,13 +2238,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = sign( + const actionCreate: RequestLogicTypes.IAction = signSignature( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = sign( + const actionAccept: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -2255,7 +2255,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = sign( + const rxReduce: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -2281,13 +2281,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = sign( + const actionCreate2: RequestLogicTypes.IAction = signSignature( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = sign( + const actionCancel2: RequestLogicTypes.IAction = signSignature( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -2312,7 +2312,7 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = sign( + const actionCreate3: RequestLogicTypes.IAction = signSignature( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); diff --git a/packages/request-logic/test/unit/utils/test-data-generator.ts b/packages/request-logic/test/unit/utils/test-data-generator.ts index 25a107eb2..b974f80be 100644 --- a/packages/request-logic/test/unit/utils/test-data-generator.ts +++ b/packages/request-logic/test/unit/utils/test-data-generator.ts @@ -6,7 +6,7 @@ import { SignatureTypes, } from '@requestnetwork/types'; -import { sign } from '@requestnetwork/utils'; +import { signSignature } from '@requestnetwork/utils'; import Version from '../../../src/version'; const CURRENT_VERSION = Version.currentVersion; @@ -280,9 +280,9 @@ export const fakeIdentity = { export const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, identity: IdentityTypes.IIdentity): any => ({ - [payeeRaw.address as string]: sign(data, payeeRaw.signatureParams), - [payerRaw.address as string]: sign(data, payerRaw.signatureParams), - [otherIdRaw.address as string]: sign(data, otherIdRaw.signatureParams), + [payeeRaw.address as string]: signSignature(data, payeeRaw.signatureParams), + [payerRaw.address as string]: signSignature(data, payerRaw.signatureParams), + [otherIdRaw.address as string]: signSignature(data, otherIdRaw.signatureParams), }[identity.value]), supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], supportedMethods: [SignatureTypes.METHOD.ECDSA], diff --git a/packages/utils/src/amount.ts b/packages/utils/src/amount.ts index d54410e1b..b78f36bb4 100644 --- a/packages/utils/src/amount.ts +++ b/packages/utils/src/amount.ts @@ -6,7 +6,7 @@ import { BigNumber } from 'ethers'; /** * Function to manage amounts */ -export { add, isValid, reduce }; +export { addAmount, isValidAmount, reduceAmount }; const regexInteger = RegExp(/^[\d]+$/); @@ -17,7 +17,7 @@ const regexInteger = RegExp(/^[\d]+$/); * * @returns boolean true if amount is a valid amount */ -function isValid(amount: RequestLogicTypes.Amount | BigNumber): boolean { +function isValidAmount(amount: RequestLogicTypes.Amount | BigNumber): boolean { return ( (isString(amount) && regexInteger.test(amount as string)) || (typeof amount === 'number' && Number.isSafeInteger(Number(amount)) && Number(amount) >= 0) @@ -32,11 +32,11 @@ function isValid(amount: RequestLogicTypes.Amount | BigNumber): boolean { * * @returns string the new amount in a string format */ -function add(amount: RequestLogicTypes.Amount, delta: RequestLogicTypes.Amount): string { - if (!isValid(amount)) { +function addAmount(amount: RequestLogicTypes.Amount, delta: RequestLogicTypes.Amount): string { + if (!isValidAmount(amount)) { throw Error('amount must represent a positive integer'); } - if (!isValid(delta)) { + if (!isValidAmount(delta)) { throw Error('delta must represent a positive integer'); } @@ -55,11 +55,11 @@ function add(amount: RequestLogicTypes.Amount, delta: RequestLogicTypes.Amount): * * @returns string the new amount in a string format */ -function reduce(amount: RequestLogicTypes.Amount, delta: RequestLogicTypes.Amount): string { - if (!isValid(amount)) { +function reduceAmount(amount: RequestLogicTypes.Amount, delta: RequestLogicTypes.Amount): string { + if (!isValidAmount(amount)) { throw Error('amount must represent a positive integer'); } - if (!isValid(delta)) { + if (!isValidAmount(delta)) { throw Error('delta must represent a positive integer'); } @@ -68,7 +68,7 @@ function reduce(amount: RequestLogicTypes.Amount, delta: RequestLogicTypes.Amoun const newAmount = amountBN.sub(deltaBN).toString(); // Check if the new amount is valid (basically it is not negative) - if (!isValid(newAmount)) { + if (!isValidAmount(newAmount)) { throw Error('result of reduce is not valid'); } return newAmount; diff --git a/packages/utils/src/bignumber.ts b/packages/utils/src/bignumber.ts index 68e7053b9..1f94abbbe 100644 --- a/packages/utils/src/bignumber.ts +++ b/packages/utils/src/bignumber.ts @@ -1,11 +1,11 @@ import { BigNumber, BigNumberish } from 'ethers'; /** Returns the minimum of two big numbers */ -const min = (a: BigNumberish, b: BigNumberish): BigNumber => +const minBigNumber = (a: BigNumberish, b: BigNumberish): BigNumber => BigNumber.from(a).lt(b) ? BigNumber.from(a) : BigNumber.from(b); /** Returns the maximum of two big numbers */ -const max = (a: BigNumberish, b: BigNumberish): BigNumber => +const maxBigNumber = (a: BigNumberish, b: BigNumberish): BigNumber => BigNumber.from(a).gt(b) ? BigNumber.from(a) : BigNumber.from(b); -export { min, max }; +export { minBigNumber, maxBigNumber }; diff --git a/packages/utils/src/crypto.ts b/packages/utils/src/crypto.ts index 8f74190ab..8051a0112 100644 --- a/packages/utils/src/crypto.ts +++ b/packages/utils/src/crypto.ts @@ -14,7 +14,7 @@ export { generate8randomBytes, keccak256Hash, last20bytesOfNormalizedKeccak256Hash, - normalize, + normalizeData, normalizeKeccak256Hash, }; @@ -29,7 +29,7 @@ export { function normalizeKeccak256Hash(data: unknown): MultiFormatTypes.HashTypes.IHash { return { type: MultiFormatTypes.HashTypes.TYPE.KECCAK256, - value: keccak256Hash(normalize(data)), + value: keccak256Hash(normalizeData(data)), }; } @@ -39,7 +39,7 @@ function normalizeKeccak256Hash(data: unknown): MultiFormatTypes.HashTypes.IHash * @param data The data to normalize * @returns The normalized data */ -function normalize(data: unknown): string { +function normalizeData(data: unknown): string { if (data === undefined) { return 'undefined'; } @@ -70,7 +70,7 @@ function keccak256Hash(data: string): string { * @returns The hashed data multi-formatted */ function last20bytesOfNormalizedKeccak256Hash(data: unknown): string { - const hash = keccak256Hash(normalize(data)); + const hash = keccak256Hash(normalizeData(data)); // eslint-disable-next-line no-magic-numbers return `0x${hash.slice(-40)}`; } diff --git a/packages/utils/src/estimate-gas-fees.ts b/packages/utils/src/estimate-gas-fees.ts index 068a6b367..ec21ef3b6 100644 --- a/packages/utils/src/estimate-gas-fees.ts +++ b/packages/utils/src/estimate-gas-fees.ts @@ -1,6 +1,6 @@ import { BigNumber, constants, providers } from 'ethers'; import { suggestFees } from 'eip1559-fee-suggestions-ethers'; -import { max } from './index'; +import { maxBigNumber } from './index'; /** * The function estimates gas fee with EIP-1559. @@ -25,9 +25,9 @@ async function estimateGasFees({ }> { const suggestedFee = await suggestFees(provider as providers.JsonRpcProvider); - const baseFee = max(suggestedFee.baseFeeSuggestion, gasPriceMin || constants.Zero); + const baseFee = maxBigNumber(suggestedFee.baseFeeSuggestion, gasPriceMin || constants.Zero); - const maxPriorityFeePerGas = max( + const maxPriorityFeePerGas = maxBigNumber( suggestedFee.maxPriorityFeeSuggestions.urgent, gasPriceMin || constants.Zero, ); diff --git a/packages/utils/src/identity.ts b/packages/utils/src/identity.ts index 02b8cea97..96b4b078a 100644 --- a/packages/utils/src/identity.ts +++ b/packages/utils/src/identity.ts @@ -8,7 +8,7 @@ const supportedIdentities: IdentityTypes.TYPE[] = [ /** * Module to manage Request Logic Identity */ -export { areEqual, hasError, normalizeIdentityValue, supportedIdentities }; +export { areEqualIdentities, hasErrorIdentities, normalizeIdentityValue, supportedIdentities }; /** * Checks if two identities are equals @@ -17,7 +17,7 @@ export { areEqual, hasError, normalizeIdentityValue, supportedIdentities }; * @param IIdentity id2 second identity * @returns boolean */ -function areEqual(id1?: IdentityTypes.IIdentity, id2?: IdentityTypes.IIdentity): boolean { +function areEqualIdentities(id1?: IdentityTypes.IIdentity, id2?: IdentityTypes.IIdentity): boolean { return ( !!id1 && !!id2 && @@ -42,7 +42,7 @@ function normalizeIdentityValue(value: string): string { * @param id identity to check * @returns the error or null if valid */ -function hasError(id: IdentityTypes.IIdentity): string | null { +function hasErrorIdentities(id: IdentityTypes.IIdentity): string | null { if (!supportedIdentities.includes(id.type)) { return 'identity type not supported'; } diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index d534ade67..868546adb 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -2,9 +2,9 @@ * Collection of general purpose utility function */ -export { add, isValid, reduce } from './amount'; +export { addAmount, isValidAmount, reduceAmount } from './amount'; -export { min, max } from './bignumber'; +export { minBigNumber, maxBigNumber } from './bignumber'; export { cachedThrottle } from './cached-throttle'; @@ -15,7 +15,7 @@ export { generate8randomBytes, keccak256Hash, last20bytesOfNormalizedKeccak256Hash, - normalize, + normalizeData, normalizeKeccak256Hash, } from './crypto'; @@ -23,7 +23,12 @@ export { decrypt, encrypt, getIdentityFromEncryptionParams } from './encryption' export { estimateGasFees } from './estimate-gas-fees'; -export { areEqual, hasError, normalizeIdentityValue, supportedIdentities } from './identity'; +export { + areEqualIdentities, + hasErrorIdentities, + normalizeIdentityValue, + supportedIdentities, +} from './identity'; export { setProviderFactory, @@ -35,7 +40,7 @@ export { export { retry } from './retry'; -export { getIdentityFromSignatureParams, recover, sign } from './signature'; +export { getIdentityFromSignatureParams, recoverSignature, signSignature } from './signature'; export { SimpleLogger } from './simple-logger'; diff --git a/packages/utils/src/signature.ts b/packages/utils/src/signature.ts index d1c807308..4de3837bc 100644 --- a/packages/utils/src/signature.ts +++ b/packages/utils/src/signature.ts @@ -1,11 +1,11 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import { ethers } from 'ethers'; -import { EcUtils, normalize, normalizeKeccak256Hash } from './crypto'; +import { EcUtils, normalizeData, normalizeKeccak256Hash } from './crypto'; /** * Function to manage Request Logic Signature */ -export { getIdentityFromSignatureParams, recover, sign }; +export { getIdentityFromSignatureParams, recoverSignature, signSignature }; // Use to localize the parameter V in an ECDSA signature in hex format const V_POSITION_FROM_END_IN_ECDSA_HEX = -2; @@ -39,7 +39,7 @@ function getIdentityFromSignatureParams( * @param signatureParams Signature parameters * @returns ISignature the signature */ -function sign( +function signSignature( data: unknown, signatureParams: SignatureTypes.ISignatureParameters, ): SignatureTypes.ISignedData { @@ -50,7 +50,7 @@ function sign( } if (signatureParams.method === SignatureTypes.METHOD.ECDSA_ETHEREUM) { - const normalizedData = normalize(data); + const normalizedData = normalizeData(data); value = EcUtils.sign(signatureParams.privateKey, ethers.utils.hashMessage(normalizedData)); return { data, signature: { method: signatureParams.method, value } }; @@ -67,7 +67,7 @@ function sign( * @param signedData the data signed * @returns identity of the signer */ -function recover(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentity { +function recoverSignature(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentity { let value: string; if (signedData.signature.method === SignatureTypes.METHOD.ECDSA) { value = EcUtils.recover( @@ -91,7 +91,7 @@ function recover(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentit } else if (v.toLowerCase() === '01') { signature = `${signedData.signature.value.slice(0, V_POSITION_FROM_END_IN_ECDSA_HEX)}1b`; } - const normalizedData = ethers.utils.hashMessage(normalize(signedData.data)); + const normalizedData = ethers.utils.hashMessage(normalizeData(signedData.data)); value = EcUtils.recover(signature, normalizedData).toLowerCase(); return { diff --git a/packages/utils/test/amount.test.ts b/packages/utils/test/amount.test.ts index e43c6823c..d13cd746a 100644 --- a/packages/utils/test/amount.test.ts +++ b/packages/utils/test/amount.test.ts @@ -1,6 +1,6 @@ import { BigNumber } from 'ethers'; -import { add, isValid, reduce } from '../src'; +import { addAmount, isValidAmount, reduceAmount } from '../src'; const magicIntegerSmall = 10000; const magicIntegerBig = 1000000000000000000000000000000; @@ -16,70 +16,70 @@ const arbitraryExpectedAmountPlusDelta = '223400000000000000'; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('Amount', () => { - describe('isValid', () => { + describe('isValidAmount', () => { it('can valid amount as small integer', () => { // 'integer should be valid' - expect(isValid(magicIntegerSmall)).toBe(true); + expect(isValidAmount(magicIntegerSmall)).toBe(true); }); it('cannot valid amount as big integer', () => { // 'Big integer should not be valid' - expect(isValid(magicIntegerBig)).toBe(false); + expect(isValidAmount(magicIntegerBig)).toBe(false); }); it('cannot valid amount as bn', () => { // 'BN should not be valid' - expect(isValid(BigNumber.from('1000000000000000000000000'))).toBe(false); + expect(isValidAmount(BigNumber.from('1000000000000000000000000'))).toBe(false); }); it('can valid amount as string representing integer', () => { // 'integer as string should be valid' - expect(isValid('10000')).toBe(true); + expect(isValidAmount('10000')).toBe(true); }); it('cannot valid amount as a small decimal', () => { // 'decimal should not be valid' - expect(isValid(magicFloatSmall)).toBe(false); + expect(isValidAmount(magicFloatSmall)).toBe(false); }); it('cannot valid amount as a big decimal', () => { // 'decimal should not be valid' - expect(isValid(magicFloatBig)).toBe(false); + expect(isValidAmount(magicFloatBig)).toBe(false); }); it('cannot valid amount as string representing small decimal', () => { // 'decimal as string should not be valid' - expect(isValid('10000.01')).toBe(false); + expect(isValidAmount('10000.01')).toBe(false); }); it('cannot valid amount as string representing big decimal', () => { // 'decimal as string should not be valid' - expect(isValid('1000000000000000000000000000000000.01')).toBe(false); + expect(isValidAmount('1000000000000000000000000000000000.01')).toBe(false); }); it('cannot valid amount as not number', () => { // 'Not number should not be valid' - expect(isValid('Not a number')).toBe(false); + expect(isValidAmount('Not a number')).toBe(false); }); it('cannot valid amount as small integer', () => { // 'integer should not be valid' - expect(isValid(-magicIntegerSmall)).toBe(false); + expect(isValidAmount(-magicIntegerSmall)).toBe(false); }); it('cannot valid amount as big integer negative', () => { // 'Big integer should not be valid' - expect(isValid(-magicIntegerBig)).toBe(false); + expect(isValidAmount(-magicIntegerBig)).toBe(false); }); it('cannot valid an empty string', () => { // 'Empty string should not be valid' - expect(isValid('')).toBe(false); + expect(isValidAmount('')).toBe(false); }); }); describe('add', () => { it('cannot add amounts not number', () => { - expect(() => add('Not a number', '1000000000000000000')).toThrowError( + expect(() => addAmount('Not a number', '1000000000000000000')).toThrowError( 'amount must represent a positive integer', ); - expect(() => add('1000000000000000000', 'Not a number')).toThrowError( + expect(() => addAmount('1000000000000000000', 'Not a number')).toThrowError( 'delta must represent a positive integer', ); }); it('can add two amounts', () => { // 'add() result is wrong' - expect(add(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( + expect(addAmount(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( arbitraryExpectedAmountPlusDelta, ); }); @@ -87,22 +87,22 @@ describe('Amount', () => { describe('reduce', () => { it('cannot reduce amounts not number', () => { - expect(() => reduce('Not a number', '1000000000000000000')).toThrowError( + expect(() => reduceAmount('Not a number', '1000000000000000000')).toThrowError( 'amount must represent a positive integer', ); - expect(() => reduce('1000000000000000000', 'Not a number')).toThrowError( + expect(() => reduceAmount('1000000000000000000', 'Not a number')).toThrowError( 'delta must represent a positive integer', ); }); it('can reduce two amounts', () => { // 'reduce() result is wrong' - expect(reduce(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( + expect(reduceAmount(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( arbitraryExpectedAmountMinusDelta, ); }); it('cannot reduce lower zero', () => { - expect(() => reduce(arbitraryDeltaAmount, arbitraryExpectedAmount)).toThrowError( + expect(() => reduceAmount(arbitraryDeltaAmount, arbitraryExpectedAmount)).toThrowError( 'result of reduce is not valid', ); }); diff --git a/packages/utils/test/bignumber.test.ts b/packages/utils/test/bignumber.test.ts index 62a640591..1b2a9c907 100644 --- a/packages/utils/test/bignumber.test.ts +++ b/packages/utils/test/bignumber.test.ts @@ -1,26 +1,26 @@ import { BigNumber } from '@ethersproject/bignumber'; -import { max, min } from '../src'; +import { maxBigNumber, minBigNumber } from '../src'; describe('min', () => { it('returns the min of 2 big numbers', () => { - expect(min(1, 2)).toMatchObject(BigNumber.from(1)); - expect(min(2, 1)).toMatchObject(BigNumber.from(1)); + expect(minBigNumber(1, 2)).toMatchObject(BigNumber.from(1)); + expect(minBigNumber(2, 1)).toMatchObject(BigNumber.from(1)); }); it('supports 0', () => { - expect(min(1, 0)).toMatchObject(BigNumber.from(0)); - expect(min(0, 1)).toMatchObject(BigNumber.from(0)); + expect(minBigNumber(1, 0)).toMatchObject(BigNumber.from(0)); + expect(minBigNumber(0, 1)).toMatchObject(BigNumber.from(0)); }); }); describe('max', () => { it('returns the max of 2 big numbers', () => { - expect(max(1, 2)).toMatchObject(BigNumber.from(2)); - expect(max(2, 1)).toMatchObject(BigNumber.from(2)); + expect(maxBigNumber(1, 2)).toMatchObject(BigNumber.from(2)); + expect(maxBigNumber(2, 1)).toMatchObject(BigNumber.from(2)); }); it('supports 0', () => { - expect(max(1, 0)).toMatchObject(BigNumber.from(1)); - expect(max(0, 1)).toMatchObject(BigNumber.from(1)); + expect(maxBigNumber(1, 0)).toMatchObject(BigNumber.from(1)); + expect(maxBigNumber(0, 1)).toMatchObject(BigNumber.from(1)); }); }); diff --git a/packages/utils/test/crypto.test.ts b/packages/utils/test/crypto.test.ts index 4647b33e2..944957303 100644 --- a/packages/utils/test/crypto.test.ts +++ b/packages/utils/test/crypto.test.ts @@ -3,7 +3,7 @@ import { generate32BufferKey, generate8randomBytes, last20bytesOfNormalizedKeccak256Hash, - normalize, + normalizeData, normalizeKeccak256Hash, } from '../src'; @@ -89,11 +89,11 @@ describe('Utils/crypto', () => { }); it('can normalize integer, null, string, undefined', () => { - expect(normalize('TesT')).toBe('"test"'); + expect(normalizeData('TesT')).toBe('"test"'); // eslint-disable-next-line no-magic-numbers - expect(normalize(12345)).toBe('12345'); - expect(normalize(null)).toBe('null'); - expect(normalize(undefined)).toBe('undefined'); + expect(normalizeData(12345)).toBe('12345'); + expect(normalizeData(null)).toBe('null'); + expect(normalizeData(undefined)).toBe('undefined'); }); it('can generate32BufferKey()', async () => { diff --git a/packages/utils/test/identity.test.ts b/packages/utils/test/identity.test.ts index ca77dda8f..17462f1ea 100644 --- a/packages/utils/test/identity.test.ts +++ b/packages/utils/test/identity.test.ts @@ -1,5 +1,5 @@ import { IdentityTypes } from '@requestnetwork/types'; -import { areEqual, normalizeIdentityValue } from '../src'; +import { areEqualIdentities, normalizeIdentityValue } from '../src'; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('Identity', () => { @@ -10,7 +10,7 @@ describe('Identity', () => { ); }); - it('can areEqual() two identities', () => { + it('can areEqualIdentities() two identities', () => { const id1 = { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0xe241d3757DAd0Ef86D0FCc5fE90e20f955743eD5', @@ -19,11 +19,11 @@ describe('Identity', () => { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0xe241d3757DAd0Ef86D0FCc5fE90e20f955743eD5', }; - // 'areEqual() error' - expect(areEqual(id1, id2)).toBe(true); + // 'areEqualIdentities() error' + expect(areEqualIdentities(id1, id2)).toBe(true); }); - it('can areEqual() two identities with different cases', () => { + it('can areEqualIdentities() two identities with different cases', () => { const id1 = { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0xe241d3757DAd0Ef86D0FCc5fE90e20f955743eD5', @@ -32,11 +32,11 @@ describe('Identity', () => { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0xe241d3757dad0ef86d0fcc5fe90e20f955743ed5', }; - // 'areEqual() error' - expect(areEqual(id1, id2)).toBe(true); + // 'areEqualIdentities() error' + expect(areEqualIdentities(id1, id2)).toBe(true); }); - it('cannot areEqual() two identities with differents values', () => { + it('cannot areEqualIdentities() two identities with differents values', () => { const id1 = { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0xe241d3757DAd0Ef86D0FCc5fE90e20f955743eD5', @@ -45,7 +45,7 @@ describe('Identity', () => { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: '0xFFFFFFFFFFFFFFf86D0FCc5fE90e20f955743eD5', }; - // 'areEqual() error' - expect(areEqual(id1, id2)).toBe(false); + // 'areEqualIdentities() error' + expect(areEqualIdentities(id1, id2)).toBe(false); }); }); diff --git a/packages/utils/test/signature.test.ts b/packages/utils/test/signature.test.ts index f94b14f53..83d6b8c9a 100644 --- a/packages/utils/test/signature.test.ts +++ b/packages/utils/test/signature.test.ts @@ -1,5 +1,10 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; -import { getIdentityFromSignatureParams, normalizeKeccak256Hash, recover, sign } from '../src'; +import { + getIdentityFromSignatureParams, + normalizeKeccak256Hash, + recoverSignature, + signSignature, +} from '../src'; const otherIdRaw = { address: '0x818B6337657A23F58581715Fc610577292e521D0', @@ -50,12 +55,12 @@ describe('Signature', () => { }); describe('sign', () => { - it('can sign() with ECDSA', () => { - const signature = sign(data, { + it('can signSignature() with ECDSA', () => { + const signature = signSignature(data, { method: SignatureTypes.METHOD.ECDSA, privateKey: otherIdRaw.privateKey, }); - // 'sign() error' + // 'signSignature() error' expect(signature).toEqual({ data, signature: { @@ -66,12 +71,12 @@ describe('Signature', () => { }); }); - it('can sign() with ECDSA_ETHEREUM', () => { - const signature = sign(data, { + it('can signSignature() with ECDSA_ETHEREUM', () => { + const signature = signSignature(data, { method: SignatureTypes.METHOD.ECDSA_ETHEREUM, privateKey: otherIdRaw.privateKey, }); - // 'sign() error' + // 'signSignature() error' expect(signature).toEqual({ data, signature: { @@ -82,12 +87,12 @@ describe('Signature', () => { }); }); - it('can sign() with different case', () => { - const signature = sign(dataDiffCase, { + it('can signSignature() with different case', () => { + const signature = signSignature(dataDiffCase, { method: SignatureTypes.METHOD.ECDSA, privateKey: otherIdRaw.privateKey, }); - // 'sign() error' + // 'signSignature() error' expect(signature).toEqual({ data: dataDiffCase, signature: { @@ -103,15 +108,15 @@ describe('Signature', () => { method: 'notECDSA', privateKey: otherIdRaw.privateKey, }; - expect(() => sign(normalizeKeccak256Hash(data), params)).toThrowError( + expect(() => signSignature(normalizeKeccak256Hash(data), params)).toThrowError( 'signatureParams.method not supported', ); }); }); describe('recover', () => { - it('can recover() ECDSA signature', () => { - const id = recover({ + it('can recoverSignature() ECDSA signature', () => { + const id = recoverSignature({ data, signature: { method: SignatureTypes.METHOD.ECDSA, @@ -119,12 +124,12 @@ describe('Signature', () => { '0x801f4240516509c28660f096830d52e8523e2136d557d65728e39f3ea37b72bb3f20accff461cabe3515431d0e6c468d4631540b7c6f9c29acfa7c9231781a3c1c', }, }); - // 'recover() error' + // 'recoverSignature() error' expect(id).toEqual(otherIdRaw.identity); }); - it('can recover() ECDSA_ETHEREUM signature', () => { - const id = recover({ + it('can recoverSignature() ECDSA_ETHEREUM signature', () => { + const id = recoverSignature({ data, signature: { method: SignatureTypes.METHOD.ECDSA_ETHEREUM, @@ -132,14 +137,14 @@ describe('Signature', () => { '0x3fbc7ed9dfa003067f646749d4223def2a69df70371d4f15ec001bc1491cdee40558de1f31fdc7cc5d805a5c4080b54cda3430b29ab14f04e17a5b23fcd39b391b', }, }); - // 'recover() error' + // 'recoverSignature() error' expect(id.value).toEqual(otherIdRaw.identity.value.toLowerCase()); - // 'recover() error' + // 'recoverSignature() error' expect(id.type).toEqual(otherIdRaw.identity.type); }); - it('can recover() with different case', () => { - const id = recover({ + it('can recoverSignature() with different case', () => { + const id = recoverSignature({ data: dataDiffCase, signature: { method: SignatureTypes.METHOD.ECDSA, @@ -147,7 +152,7 @@ describe('Signature', () => { '0x801f4240516509c28660f096830d52e8523e2136d557d65728e39f3ea37b72bb3f20accff461cabe3515431d0e6c468d4631540b7c6f9c29acfa7c9231781a3c1c', }, }); - // 'recover() error' + // 'recoverSignature() error' expect(id).toEqual(otherIdRaw.identity); }); @@ -156,7 +161,7 @@ describe('Signature', () => { method: 'notECDSA', value: '0x00000000000000000000', }; - expect(() => recover({ data, signature: params })).toThrowError( + expect(() => recoverSignature({ data, signature: params })).toThrowError( 'signatureParams.method not supported', ); }); diff --git a/packages/web3-signature/src/web3-signature-provider.ts b/packages/web3-signature/src/web3-signature-provider.ts index 00d3d5495..0292e628f 100644 --- a/packages/web3-signature/src/web3-signature-provider.ts +++ b/packages/web3-signature/src/web3-signature-provider.ts @@ -1,6 +1,6 @@ import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import { areEqual, normalize, recover } from '@requestnetwork/utils'; +import { areEqualIdentities, normalizeData, recoverSignature } from '@requestnetwork/utils'; import { providers } from 'ethers'; @@ -41,7 +41,7 @@ export default class Web3SignatureProvider implements SignatureProviderTypes.ISi throw Error(`Identity type not supported ${signer.type}`); } - const normalizedData = normalize(data); + const normalizedData = normalizeData(data); const signerEthers = this.web3Provider.getSigner(signer.value); let signatureValue; @@ -82,7 +82,7 @@ export default class Web3SignatureProvider implements SignatureProviderTypes.ISi value, }, }; - if (areEqual(recover(signedData), signer)) { + if (areEqualIdentities(recoverSignature(signedData), signer)) { return signedData; } return null; From d85a02e957119431aa5a90c066f2785b21e92407 Mon Sep 17 00:00:00 2001 From: marcohefti Date: Sat, 14 Jan 2023 15:33:26 +0700 Subject: [PATCH 12/13] Fix README, identity, and signature file updates -Removed list of utils from README to avoid staleness -Changed 'hasError' to 'identityHasError' -Changed 'sign' back to original name 'sign' -Changed 'recover' to 'recoverSigner' Addressed comments by @MantisClone Signed-off-by: marcohefti --- .../test/api/request-network.test.ts | 4 +- .../test/data-test-real-btc.ts | 4 +- packages/request-client.js/test/data-test.ts | 24 ++--- .../test/declarative-payments.test.ts | 4 +- .../request-logic/specs/example/example.ts | 6 +- packages/request-logic/src/action.ts | 4 +- packages/request-logic/src/actions/create.ts | 18 ++-- packages/request-logic/test/index.test.ts | 90 +++++++++---------- .../test/unit/utils/test-data-generator.ts | 8 +- packages/utils/README.md | 18 ---- packages/utils/src/identity.ts | 4 +- packages/utils/src/index.ts | 4 +- packages/utils/src/signature.ts | 6 +- packages/utils/test/signature.test.ts | 46 +++++----- .../src/web3-signature-provider.ts | 4 +- 15 files changed, 110 insertions(+), 134 deletions(-) diff --git a/packages/request-client.js/test/api/request-network.test.ts b/packages/request-client.js/test/api/request-network.test.ts index 1b3c0249b..fed1c9dd8 100644 --- a/packages/request-client.js/test/api/request-network.test.ts +++ b/packages/request-client.js/test/api/request-network.test.ts @@ -6,7 +6,7 @@ import RequestNetwork from '../../src/api/request-network'; import Request from '../../src/api/request'; import * as TestData from '../data-test'; -import { normalizeKeccak256Hash, signSignature } from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; const mockDataAccess: DataAccessTypes.IDataAccess = { _getStatus: jest.fn(), @@ -59,7 +59,7 @@ describe('api/request-network', () => { timestamp: 1549953337, transaction: { data: 'broken transaction' }, }; - const actionWrongSigner = signSignature(TestData.data, { + const actionWrongSigner = sign(TestData.data, { method: SignatureTypes.METHOD.ECDSA, privateKey: '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', }); diff --git a/packages/request-client.js/test/data-test-real-btc.ts b/packages/request-client.js/test/data-test-real-btc.ts index 3fb9c3853..6ed341a2c 100644 --- a/packages/request-client.js/test/data-test-real-btc.ts +++ b/packages/request-client.js/test/data-test-real-btc.ts @@ -4,7 +4,7 @@ import { SignatureTypes, TransactionTypes, } from '@requestnetwork/types'; -import { signSignature } from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; const payee = { identity: { @@ -50,7 +50,7 @@ export const data = { version: '2.0.3', }; -export const action: RequestLogicTypes.IAction = signSignature(data, payee.signatureParams); +export const action: RequestLogicTypes.IAction = sign(data, payee.signatureParams); export const timestampedTransaction: TransactionTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, diff --git a/packages/request-client.js/test/data-test.ts b/packages/request-client.js/test/data-test.ts index 6f56eeaf0..74b625611 100644 --- a/packages/request-client.js/test/data-test.ts +++ b/packages/request-client.js/test/data-test.ts @@ -8,7 +8,7 @@ import { SignatureTypes, TransactionTypes, } from '@requestnetwork/types'; -import { normalizeKeccak256Hash, signSignature } from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; import AxiosMockAdapter from 'axios-mock-adapter'; import axios from 'axios'; import { Types } from '../src'; @@ -155,15 +155,12 @@ const dataWithDeclarativeNoPaymentInfo = { version: '2.0.3', }; -export const action: RequestLogicTypes.IAction = signSignature( - dataWithDeclarative, - payee.signatureParams, -); -const actionWithoutExtensionsData: RequestLogicTypes.IAction = signSignature( +export const action: RequestLogicTypes.IAction = sign(dataWithDeclarative, payee.signatureParams); +const actionWithoutExtensionsData: RequestLogicTypes.IAction = sign( dataWithoutExtensionsData, payee.signatureParams, ); -const actionWithoutPaymentInfo: RequestLogicTypes.IAction = signSignature( +const actionWithoutPaymentInfo: RequestLogicTypes.IAction = sign( dataWithDeclarativeNoPaymentInfo, payee.signatureParams, ); @@ -193,10 +190,7 @@ export const timestampedTransactionWithoutPaymentInfo: TransactionTypes.ITimesta export const actionRequestId = MultiFormat.serialize(normalizeKeccak256Hash(action)); -export const anotherCreationAction: RequestLogicTypes.IAction = signSignature( - data, - payer.signatureParams, -); +export const anotherCreationAction: RequestLogicTypes.IAction = sign(data, payer.signatureParams); export const anotherCreationTransactionConfirmed: TransactionTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, @@ -220,7 +214,7 @@ const dataSecondRequest = { version: '2.0.3', }; -export const actionCreationSecondRequest: RequestLogicTypes.IAction = signSignature( +export const actionCreationSecondRequest: RequestLogicTypes.IAction = sign( dataSecondRequest, payee.signatureParams, ); @@ -265,11 +259,11 @@ export const signatureParametersDelegate: SignatureTypes.ISignatureParameters = export const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, signer: IdentityTypes.IIdentity): any => { if (signer.value === payee.identity.value) { - return signSignature(data, signatureParametersPayee); + return sign(data, signatureParametersPayee); } else if (signer.value === payer.identity.value) { - return signSignature(data, signatureParametersPayer); + return sign(data, signatureParametersPayer); } else { - return signSignature(data, signatureParametersDelegate); + return sign(data, signatureParametersDelegate); } }, supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], diff --git a/packages/request-client.js/test/declarative-payments.test.ts b/packages/request-client.js/test/declarative-payments.test.ts index 1b3096694..54a1fd9de 100644 --- a/packages/request-client.js/test/declarative-payments.test.ts +++ b/packages/request-client.js/test/declarative-payments.test.ts @@ -20,7 +20,7 @@ import { } from '@requestnetwork/payment-detection'; import { IRequestDataWithEvents } from '../src/types'; import { CurrencyManager } from '@requestnetwork/currency'; -import { signSignature } from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; const httpConfig: Partial = { getConfirmationDeferDelay: 0, @@ -417,7 +417,7 @@ describe('request-client.js: declarative payments', () => { timestamp: TestData.arbitraryTimestamp, transaction: { data: JSON.stringify( - signSignature( + sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { diff --git a/packages/request-logic/specs/example/example.ts b/packages/request-logic/specs/example/example.ts index 847608f62..69f4915b2 100644 --- a/packages/request-logic/specs/example/example.ts +++ b/packages/request-logic/specs/example/example.ts @@ -8,7 +8,7 @@ import { } from '@requestnetwork/types'; import RequestLogic from '../../src/requestLogicCore'; -import { signSignature } from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; async function foo(): Promise { // Bob (the payee) @@ -38,8 +38,8 @@ async function foo(): Promise { const signatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, identity: IdentityTypes.IIdentity): any => ({ - [aliceRaw.identity.value as string]: signSignature(data, aliceRaw.signatureParams), - [bobRaw.identity.value as string]: signSignature(data, bobRaw.signatureParams), + [aliceRaw.identity.value as string]: sign(data, aliceRaw.signatureParams), + [bobRaw.identity.value as string]: sign(data, bobRaw.signatureParams), }[identity.value]), supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], supportedMethods: [SignatureTypes.METHOD.ECDSA], diff --git a/packages/request-logic/src/action.ts b/packages/request-logic/src/action.ts index 1da075bfb..bc2ec49b7 100644 --- a/packages/request-logic/src/action.ts +++ b/packages/request-logic/src/action.ts @@ -3,7 +3,7 @@ import { IdentityTypes, RequestLogicTypes, SignatureProviderTypes } from '@reque import * as Semver from 'semver'; import Role from './role'; import Version from './version'; -import { normalizeKeccak256Hash, recoverSignature } from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, recoverSigner } from '@requestnetwork/utils'; /** * Function to manage Request logic action (object that will be interpreted to create or modify a request) @@ -45,7 +45,7 @@ function createAction( * @returns RequestEnum.ROLE the role of the signer (payee, payer or third party) */ function getSignerIdentityFromAction(action: RequestLogicTypes.IAction): IdentityTypes.IIdentity { - return recoverSignature(action); + return recoverSigner(action); } /** diff --git a/packages/request-logic/src/actions/create.ts b/packages/request-logic/src/actions/create.ts index ff2f745ad..c6c24ca7b 100644 --- a/packages/request-logic/src/actions/create.ts +++ b/packages/request-logic/src/actions/create.ts @@ -5,7 +5,7 @@ import Version from '../version'; import { deepCopy, getCurrentTimestampInSecond, - hasErrorIdentities, + identityHasError, isString, isValidAmount, } from '@requestnetwork/utils'; @@ -42,12 +42,12 @@ function format( throw new Error('expectedAmount must be a positive integer'); } - if (requestParameters.payee && hasErrorIdentities(requestParameters.payee)) { - throw new Error(`payee: ${hasErrorIdentities(requestParameters.payee)}̀`); + if (requestParameters.payee && identityHasError(requestParameters.payee)) { + throw new Error(`payee: ${identityHasError(requestParameters.payee)}̀`); } - if (requestParameters.payer && hasErrorIdentities(requestParameters.payer)) { - throw new Error(`payer: ${hasErrorIdentities(requestParameters.payer)}̀`); + if (requestParameters.payer && identityHasError(requestParameters.payer)) { + throw new Error(`payer: ${identityHasError(requestParameters.payer)}̀`); } if (!requestParameters.timestamp) { @@ -91,12 +91,12 @@ function createRequest( throw new Error('action.parameters.payee or action.parameters.payer must be given'); } - if (action.data.parameters.payee && hasErrorIdentities(action.data.parameters.payee)) { - throw new Error(`payee: ${hasErrorIdentities(action.data.parameters.payee)}̀`); + if (action.data.parameters.payee && identityHasError(action.data.parameters.payee)) { + throw new Error(`payee: ${identityHasError(action.data.parameters.payee)}̀`); } - if (action.data.parameters.payer && hasErrorIdentities(action.data.parameters.payer)) { - throw new Error(`payer: ${hasErrorIdentities(action.data.parameters.payer)}̀`); + if (action.data.parameters.payer && identityHasError(action.data.parameters.payer)) { + throw new Error(`payer: ${identityHasError(action.data.parameters.payer)}̀`); } if ( diff --git a/packages/request-logic/test/index.test.ts b/packages/request-logic/test/index.test.ts index 67ff7e613..d0b3cbd0d 100644 --- a/packages/request-logic/test/index.test.ts +++ b/packages/request-logic/test/index.test.ts @@ -7,7 +7,7 @@ import { RequestLogic } from '../src/index'; import * as TestData from './unit/utils/test-data-generator'; import Version from '../src/version'; -import { normalizeKeccak256Hash, signSignature } from '@requestnetwork/utils'; +import { normalizeKeccak256Hash, sign } from '@requestnetwork/utils'; const CURRENT_VERSION = Version.currentVersion; @@ -26,7 +26,7 @@ const unsignedAction: RequestLogicTypes.IUnsignedAction = { parameters: createParams, version: CURRENT_VERSION, }; -const action = signSignature(unsignedAction, TestData.payeeRaw.signatureParams); +const action = sign(unsignedAction, TestData.payeeRaw.signatureParams); const requestId = MultiFormat.serialize(normalizeKeccak256Hash(action)); const fakeTxHash = '01aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; @@ -496,7 +496,7 @@ describe('index', () => { }); it('cannot accept as payee', async () => { - const actionCreate = signSignature( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -592,7 +592,7 @@ describe('index', () => { }); it('cannot cancel if not payee or payer', async () => { - const actionCreate = signSignature( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -693,7 +693,7 @@ describe('index', () => { ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot increaseExpectedAmountRequest as payee', async () => { - const actionCreate = signSignature( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -799,7 +799,7 @@ describe('index', () => { ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot reduceExpectedAmountRequest as payer', async () => { - const actionCreate = signSignature( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -908,7 +908,7 @@ describe('index', () => { }, }; - const actionCreate = signSignature( + const actionCreate = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -962,7 +962,7 @@ describe('index', () => { describe('getRequestFromId', () => { it('can getRequestFromId', async () => { - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -980,7 +980,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = signSignature( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -991,7 +991,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = signSignature( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1098,7 +1098,7 @@ describe('index', () => { }); it('can getRequestFromId ignore old pending transaction', async () => { - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1116,7 +1116,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = signSignature( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1127,7 +1127,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = signSignature( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1237,7 +1237,7 @@ describe('index', () => { }); it('can getRequestFromId with pending transaction', async () => { - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1255,7 +1255,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = signSignature( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1266,7 +1266,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = signSignature( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1376,7 +1376,7 @@ describe('index', () => { }); it('can getRequestFromId ignore the same transactions even with different case', async () => { - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1394,7 +1394,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = signSignature( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1405,7 +1405,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const actionReduce: RequestLogicTypes.IAction = signSignature( + const actionReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1417,7 +1417,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionReduce2: RequestLogicTypes.IAction = signSignature( + const actionReduce2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1538,7 +1538,7 @@ describe('index', () => { }); it('can getRequestFromId do not ignore the same transactions if different nonces', async () => { - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1556,7 +1556,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionAccept: RequestLogicTypes.IAction = signSignature( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1567,7 +1567,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const actionReduce: RequestLogicTypes.IAction = signSignature( + const actionReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1579,7 +1579,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const actionReduce2: RequestLogicTypes.IAction = signSignature( + const actionReduce2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1736,7 +1736,7 @@ describe('index', () => { }); it('should ignored the corrupted data (e.g: wrong properties)', async () => { - const actionCorrupted: RequestLogicTypes.IAction = signSignature( + const actionCorrupted: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -1811,13 +1811,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = signSignature( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1828,7 +1828,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = signSignature( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -1854,13 +1854,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = signSignature( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = signSignature( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -1885,7 +1885,7 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = signSignature( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); @@ -1974,13 +1974,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = signSignature( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -1991,7 +1991,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = signSignature( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -2017,13 +2017,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = signSignature( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = signSignature( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -2048,7 +2048,7 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = signSignature( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); @@ -2143,7 +2143,7 @@ describe('index', () => { }); it('should ignore the transaction none parsable and the rejected action', async () => { - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { @@ -2161,7 +2161,7 @@ describe('index', () => { TestData.payeeRaw.signatureParams, ); - const acceptNotValid: RequestLogicTypes.IAction = signSignature( + const acceptNotValid: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -2238,13 +2238,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate: RequestLogicTypes.IAction = signSignature( + const actionCreate: RequestLogicTypes.IAction = sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation)); - const actionAccept: RequestLogicTypes.IAction = signSignature( + const actionAccept: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { @@ -2255,7 +2255,7 @@ describe('index', () => { TestData.payerRaw.signatureParams, ); - const rxReduce: RequestLogicTypes.IAction = signSignature( + const rxReduce: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { @@ -2281,13 +2281,13 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate2: RequestLogicTypes.IAction = signSignature( + const actionCreate2: RequestLogicTypes.IAction = sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize(normalizeKeccak256Hash(unsignedActionCreation2)); - const actionCancel2: RequestLogicTypes.IAction = signSignature( + const actionCancel2: RequestLogicTypes.IAction = sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { @@ -2312,7 +2312,7 @@ describe('index', () => { }, version: CURRENT_VERSION, }; - const actionCreate3: RequestLogicTypes.IAction = signSignature( + const actionCreate3: RequestLogicTypes.IAction = sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); diff --git a/packages/request-logic/test/unit/utils/test-data-generator.ts b/packages/request-logic/test/unit/utils/test-data-generator.ts index b974f80be..25a107eb2 100644 --- a/packages/request-logic/test/unit/utils/test-data-generator.ts +++ b/packages/request-logic/test/unit/utils/test-data-generator.ts @@ -6,7 +6,7 @@ import { SignatureTypes, } from '@requestnetwork/types'; -import { signSignature } from '@requestnetwork/utils'; +import { sign } from '@requestnetwork/utils'; import Version from '../../../src/version'; const CURRENT_VERSION = Version.currentVersion; @@ -280,9 +280,9 @@ export const fakeIdentity = { export const fakeSignatureProvider: SignatureProviderTypes.ISignatureProvider = { sign: (data: any, identity: IdentityTypes.IIdentity): any => ({ - [payeeRaw.address as string]: signSignature(data, payeeRaw.signatureParams), - [payerRaw.address as string]: signSignature(data, payerRaw.signatureParams), - [otherIdRaw.address as string]: signSignature(data, otherIdRaw.signatureParams), + [payeeRaw.address as string]: sign(data, payeeRaw.signatureParams), + [payerRaw.address as string]: sign(data, payerRaw.signatureParams), + [otherIdRaw.address as string]: sign(data, otherIdRaw.signatureParams), }[identity.value]), supportedIdentityTypes: [IdentityTypes.TYPE.ETHEREUM_ADDRESS], supportedMethods: [SignatureTypes.METHOD.ECDSA], diff --git a/packages/utils/README.md b/packages/utils/README.md index c5e07b8bd..5905257c5 100644 --- a/packages/utils/README.md +++ b/packages/utils/README.md @@ -3,24 +3,6 @@ `@requestnetwork/utils` is a typescript library part of the [Request Network protocol](https://github.com/RequestNetwork/requestNetwork). It is a collection of tools shared between the @requestnetwork packages. -- Elliptic curve crypto and signature - - normalizeKeccak256Hash() - - EcUtils.getAddressFromPrivateKey() - - EcUtils.recover() - - EcUtils.sign() - - getIdentityFromSignatureParams() - - recover() - - sign() -- Identity - - areEqual() - - normalizeIdentityValue() - - isString -- Miscellaneous - - deepCopy() - - deepSort() - - flatten2DimensionsArray() - - getCurrentTimestampInSecond() - ## Installation ```bash diff --git a/packages/utils/src/identity.ts b/packages/utils/src/identity.ts index 96b4b078a..febe2f887 100644 --- a/packages/utils/src/identity.ts +++ b/packages/utils/src/identity.ts @@ -8,7 +8,7 @@ const supportedIdentities: IdentityTypes.TYPE[] = [ /** * Module to manage Request Logic Identity */ -export { areEqualIdentities, hasErrorIdentities, normalizeIdentityValue, supportedIdentities }; +export { areEqualIdentities, identityHasError, normalizeIdentityValue, supportedIdentities }; /** * Checks if two identities are equals @@ -42,7 +42,7 @@ function normalizeIdentityValue(value: string): string { * @param id identity to check * @returns the error or null if valid */ -function hasErrorIdentities(id: IdentityTypes.IIdentity): string | null { +function identityHasError(id: IdentityTypes.IIdentity): string | null { if (!supportedIdentities.includes(id.type)) { return 'identity type not supported'; } diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 868546adb..52c11c16f 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -25,7 +25,7 @@ export { estimateGasFees } from './estimate-gas-fees'; export { areEqualIdentities, - hasErrorIdentities, + identityHasError, normalizeIdentityValue, supportedIdentities, } from './identity'; @@ -40,7 +40,7 @@ export { export { retry } from './retry'; -export { getIdentityFromSignatureParams, recoverSignature, signSignature } from './signature'; +export { getIdentityFromSignatureParams, recoverSigner, sign } from './signature'; export { SimpleLogger } from './simple-logger'; diff --git a/packages/utils/src/signature.ts b/packages/utils/src/signature.ts index 4de3837bc..1ffb69b1f 100644 --- a/packages/utils/src/signature.ts +++ b/packages/utils/src/signature.ts @@ -5,7 +5,7 @@ import { EcUtils, normalizeData, normalizeKeccak256Hash } from './crypto'; /** * Function to manage Request Logic Signature */ -export { getIdentityFromSignatureParams, recoverSignature, signSignature }; +export { getIdentityFromSignatureParams, recoverSigner, sign }; // Use to localize the parameter V in an ECDSA signature in hex format const V_POSITION_FROM_END_IN_ECDSA_HEX = -2; @@ -39,7 +39,7 @@ function getIdentityFromSignatureParams( * @param signatureParams Signature parameters * @returns ISignature the signature */ -function signSignature( +function sign( data: unknown, signatureParams: SignatureTypes.ISignatureParameters, ): SignatureTypes.ISignedData { @@ -67,7 +67,7 @@ function signSignature( * @param signedData the data signed * @returns identity of the signer */ -function recoverSignature(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentity { +function recoverSigner(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentity { let value: string; if (signedData.signature.method === SignatureTypes.METHOD.ECDSA) { value = EcUtils.recover( diff --git a/packages/utils/test/signature.test.ts b/packages/utils/test/signature.test.ts index 83d6b8c9a..bbf3c166b 100644 --- a/packages/utils/test/signature.test.ts +++ b/packages/utils/test/signature.test.ts @@ -2,8 +2,8 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import { getIdentityFromSignatureParams, normalizeKeccak256Hash, - recoverSignature, - signSignature, + recoverSigner, + sign, } from '../src'; const otherIdRaw = { @@ -55,12 +55,12 @@ describe('Signature', () => { }); describe('sign', () => { - it('can signSignature() with ECDSA', () => { - const signature = signSignature(data, { + it('can sign() with ECDSA', () => { + const signature = sign(data, { method: SignatureTypes.METHOD.ECDSA, privateKey: otherIdRaw.privateKey, }); - // 'signSignature() error' + // 'sign() error' expect(signature).toEqual({ data, signature: { @@ -71,12 +71,12 @@ describe('Signature', () => { }); }); - it('can signSignature() with ECDSA_ETHEREUM', () => { - const signature = signSignature(data, { + it('can sign() with ECDSA_ETHEREUM', () => { + const signature = sign(data, { method: SignatureTypes.METHOD.ECDSA_ETHEREUM, privateKey: otherIdRaw.privateKey, }); - // 'signSignature() error' + // 'sign() error' expect(signature).toEqual({ data, signature: { @@ -87,12 +87,12 @@ describe('Signature', () => { }); }); - it('can signSignature() with different case', () => { - const signature = signSignature(dataDiffCase, { + it('can sign() with different case', () => { + const signature = sign(dataDiffCase, { method: SignatureTypes.METHOD.ECDSA, privateKey: otherIdRaw.privateKey, }); - // 'signSignature() error' + // 'sign() error' expect(signature).toEqual({ data: dataDiffCase, signature: { @@ -108,15 +108,15 @@ describe('Signature', () => { method: 'notECDSA', privateKey: otherIdRaw.privateKey, }; - expect(() => signSignature(normalizeKeccak256Hash(data), params)).toThrowError( + expect(() => sign(normalizeKeccak256Hash(data), params)).toThrowError( 'signatureParams.method not supported', ); }); }); describe('recover', () => { - it('can recoverSignature() ECDSA signature', () => { - const id = recoverSignature({ + it('can recoverSigner() ECDSA signature', () => { + const id = recoverSigner({ data, signature: { method: SignatureTypes.METHOD.ECDSA, @@ -124,12 +124,12 @@ describe('Signature', () => { '0x801f4240516509c28660f096830d52e8523e2136d557d65728e39f3ea37b72bb3f20accff461cabe3515431d0e6c468d4631540b7c6f9c29acfa7c9231781a3c1c', }, }); - // 'recoverSignature() error' + // 'recoverSigner() error' expect(id).toEqual(otherIdRaw.identity); }); - it('can recoverSignature() ECDSA_ETHEREUM signature', () => { - const id = recoverSignature({ + it('can recoverSigner() ECDSA_ETHEREUM signature', () => { + const id = recoverSigner({ data, signature: { method: SignatureTypes.METHOD.ECDSA_ETHEREUM, @@ -137,14 +137,14 @@ describe('Signature', () => { '0x3fbc7ed9dfa003067f646749d4223def2a69df70371d4f15ec001bc1491cdee40558de1f31fdc7cc5d805a5c4080b54cda3430b29ab14f04e17a5b23fcd39b391b', }, }); - // 'recoverSignature() error' + // 'recoverSigner() error' expect(id.value).toEqual(otherIdRaw.identity.value.toLowerCase()); - // 'recoverSignature() error' + // 'recoverSigner() error' expect(id.type).toEqual(otherIdRaw.identity.type); }); - it('can recoverSignature() with different case', () => { - const id = recoverSignature({ + it('can recoverSigner() with different case', () => { + const id = recoverSigner({ data: dataDiffCase, signature: { method: SignatureTypes.METHOD.ECDSA, @@ -152,7 +152,7 @@ describe('Signature', () => { '0x801f4240516509c28660f096830d52e8523e2136d557d65728e39f3ea37b72bb3f20accff461cabe3515431d0e6c468d4631540b7c6f9c29acfa7c9231781a3c1c', }, }); - // 'recoverSignature() error' + // 'recoverSigner() error' expect(id).toEqual(otherIdRaw.identity); }); @@ -161,7 +161,7 @@ describe('Signature', () => { method: 'notECDSA', value: '0x00000000000000000000', }; - expect(() => recoverSignature({ data, signature: params })).toThrowError( + expect(() => recoverSigner({ data, signature: params })).toThrowError( 'signatureParams.method not supported', ); }); diff --git a/packages/web3-signature/src/web3-signature-provider.ts b/packages/web3-signature/src/web3-signature-provider.ts index 0292e628f..a1485f62e 100644 --- a/packages/web3-signature/src/web3-signature-provider.ts +++ b/packages/web3-signature/src/web3-signature-provider.ts @@ -1,6 +1,6 @@ import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import { areEqualIdentities, normalizeData, recoverSignature } from '@requestnetwork/utils'; +import { areEqualIdentities, normalizeData, recoverSigner } from '@requestnetwork/utils'; import { providers } from 'ethers'; @@ -82,7 +82,7 @@ export default class Web3SignatureProvider implements SignatureProviderTypes.ISi value, }, }; - if (areEqualIdentities(recoverSignature(signedData), signer)) { + if (areEqualIdentities(recoverSigner(signedData), signer)) { return signedData; } return null; From 25d66f1abab1ca5083b2c9148460bb8c2ef6f7e6 Mon Sep 17 00:00:00 2001 From: marcohefti Date: Mon, 16 Jan 2023 16:35:37 +0700 Subject: [PATCH 13/13] Refactor crypto and ec-utils modules -Removed the named const from crypto-wrapper.ts and exported functions individually -Removed the named const from ec-utils.ts and exported functions individually -Renamed recover() to recoverSigner() in ec-utils.ts -Prefixed functions with 'ec' to prevent duplicate variables -Reverted normalizeData() to normalize() Signed-off-by: marcohefti --- ...thereum-private-key-decryption-provider.ts | 4 +- ...ethereum-private-key-signature-provider.ts | 6 +- ...eum-private-key-signature-provider.test.ts | 4 +- packages/request-client.js/test/index.test.ts | 10 ++-- packages/utils/src/crypto.ts | 44 ++++++++++---- packages/utils/src/crypto/crypto-wrapper.ts | 2 +- packages/utils/src/crypto/ec-utils.ts | 26 ++++----- packages/utils/src/encryption.ts | 24 +++++--- packages/utils/src/index.ts | 15 ++++- packages/utils/src/signature.ts | 25 ++++---- packages/utils/test/crypto.test.ts | 10 ++-- .../utils/test/crypto/crypto-wrapper.test.ts | 33 ++++++----- packages/utils/test/crypto/ec-utils.test.ts | 58 ++++++++++--------- .../src/web3-signature-provider.ts | 4 +- .../test/web3-signature-provider.test.ts | 4 +- 15 files changed, 161 insertions(+), 108 deletions(-) diff --git a/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts b/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts index 95f5aacef..4a35c595a 100644 --- a/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts +++ b/packages/epk-decryption/src/ethereum-private-key-decryption-provider.ts @@ -1,6 +1,6 @@ import { DecryptionProviderTypes, EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import { decrypt, EcUtils } from '@requestnetwork/utils'; +import { decrypt, getAddressFromPrivateKey } from '@requestnetwork/utils'; /** Type of the dictionary of decryptionParameters (private keys) indexed by ethereum address */ type IDecryptionParametersDictionary = Map; @@ -87,7 +87,7 @@ export default class EthereumPrivateKeyDecryptionProvider // compute the address from private key // toLowerCase to avoid mismatch because of case - const address = EcUtils.getAddressFromPrivateKey(decryptionParameters.key).toLowerCase(); + const address = getAddressFromPrivateKey(decryptionParameters.key).toLowerCase(); this.decryptionParametersDictionary.set(address, decryptionParameters); diff --git a/packages/epk-signature/src/ethereum-private-key-signature-provider.ts b/packages/epk-signature/src/ethereum-private-key-signature-provider.ts index 07414f04e..8643360bf 100644 --- a/packages/epk-signature/src/ethereum-private-key-signature-provider.ts +++ b/packages/epk-signature/src/ethereum-private-key-signature-provider.ts @@ -1,6 +1,6 @@ import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; +import { ecSign, getAddressFromPrivateKey, normalizeKeccak256Hash } from '@requestnetwork/utils'; /** Type of the dictionary of signatureParameters (private keys) indexed by ethereum address */ type ISignatureParametersDictionary = Map; @@ -56,7 +56,7 @@ export default class EthereumPrivateKeySignatureProvider // the hash format in request start by 01 but the ec-utils need a hash starting by 0x const hashData = normalizeKeccak256Hash(data).value; - const signatureValue = EcUtils.sign(signatureParameter.privateKey, hashData); + const signatureValue = ecSign(signatureParameter.privateKey, hashData); return { data, @@ -83,7 +83,7 @@ export default class EthereumPrivateKeySignatureProvider // compute the address from private key // toLowerCase to avoid mismatch because of case - const address = EcUtils.getAddressFromPrivateKey(signatureParams.privateKey).toLowerCase(); + const address = getAddressFromPrivateKey(signatureParams.privateKey).toLowerCase(); this.signatureParametersDictionary.set(address, signatureParams); diff --git a/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts b/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts index 451de7200..5f2c001f0 100644 --- a/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts +++ b/packages/epk-signature/test/ethereum-private-key-signature-provider.test.ts @@ -1,7 +1,7 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import EthereumPrivateKeySignatureProvider from '../src/ethereum-private-key-signature-provider'; -import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; +import { ecSign, normalizeKeccak256Hash } from '@requestnetwork/utils'; const id1Raw = { address: '0xaf083f77f1ffd54218d91491afd06c9296eac3ce', @@ -35,7 +35,7 @@ export const id2Raw = { const data = { What: 'ever', the: 'data', are: true }; const hashData = normalizeKeccak256Hash(data).value; -const signatureValueExpected = EcUtils.sign(id1Raw.privateKey, hashData); +const signatureValueExpected = ecSign(id1Raw.privateKey, hashData); const signedDataExpected = { data, signature: { diff --git a/packages/request-client.js/test/index.test.ts b/packages/request-client.js/test/index.test.ts index 6433e9731..140452cb7 100644 --- a/packages/request-client.js/test/index.test.ts +++ b/packages/request-client.js/test/index.test.ts @@ -9,7 +9,7 @@ import { PaymentTypes, RequestLogicTypes, } from '@requestnetwork/types'; -import { CryptoWrapper, decrypt } from '@requestnetwork/utils'; +import { decrypt, random32Bytes } from '@requestnetwork/utils'; import { ethers } from 'ethers'; import AxiosMockAdapter from 'axios-mock-adapter'; @@ -1439,8 +1439,8 @@ describe('request-client.js', () => { useMockStorage: true, }); // generate address randomly to avoid collisions - const paymentAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); - const refundAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const paymentAddress = '0x' + (await random32Bytes()).slice(12).toString('hex'); + const refundAddress = '0x' + (await random32Bytes()).slice(12).toString('hex'); const paymentNetwork: PaymentTypes.PaymentNetworkCreateParameters = { id: ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_ADDRESS_BASED, @@ -1583,8 +1583,8 @@ describe('request-client.js', () => { }); // generate address randomly to avoid collisions - const paymentAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); - const refundAddress = '0x' + (await CryptoWrapper.random32Bytes()).slice(12).toString('hex'); + const paymentAddress = '0x' + (await random32Bytes()).slice(12).toString('hex'); + const refundAddress = '0x' + (await random32Bytes()).slice(12).toString('hex'); const paymentNetwork: PaymentTypes.PaymentNetworkCreateParameters = { id: ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_ADDRESS_BASED, diff --git a/packages/utils/src/crypto.ts b/packages/utils/src/crypto.ts index 8051a0112..bc99fa376 100644 --- a/packages/utils/src/crypto.ts +++ b/packages/utils/src/crypto.ts @@ -1,20 +1,42 @@ import { MultiFormatTypes } from '@requestnetwork/types'; import { ethers } from 'ethers'; -import { CryptoWrapper } from './crypto/crypto-wrapper'; -import { EcUtils } from './crypto/ec-utils'; +import { + decryptWithAes256cbc, + decryptWithAes256gcm, + encryptWithAes256cbc, + encryptWithAes256gcm, + random32Bytes, +} from './crypto/crypto-wrapper'; +import { + ecDecrypt, + ecEncrypt, + getAddressFromPrivateKey, + getAddressFromPublicKey, + ecRecover, + ecSign, +} from './crypto/ec-utils'; import { deepSort } from './utils'; /** * manages crypto functions */ export { - CryptoWrapper, - EcUtils, + decryptWithAes256cbc, + decryptWithAes256gcm, + encryptWithAes256cbc, + encryptWithAes256gcm, + random32Bytes, + ecDecrypt, + ecEncrypt, + getAddressFromPrivateKey, + getAddressFromPublicKey, + ecRecover, + ecSign, generate32BufferKey, generate8randomBytes, keccak256Hash, last20bytesOfNormalizedKeccak256Hash, - normalizeData, + normalize, normalizeKeccak256Hash, }; @@ -29,7 +51,7 @@ export { function normalizeKeccak256Hash(data: unknown): MultiFormatTypes.HashTypes.IHash { return { type: MultiFormatTypes.HashTypes.TYPE.KECCAK256, - value: keccak256Hash(normalizeData(data)), + value: keccak256Hash(normalize(data)), }; } @@ -39,7 +61,7 @@ function normalizeKeccak256Hash(data: unknown): MultiFormatTypes.HashTypes.IHash * @param data The data to normalize * @returns The normalized data */ -function normalizeData(data: unknown): string { +function normalize(data: unknown): string { if (data === undefined) { return 'undefined'; } @@ -70,7 +92,7 @@ function keccak256Hash(data: string): string { * @returns The hashed data multi-formatted */ function last20bytesOfNormalizedKeccak256Hash(data: unknown): string { - const hash = keccak256Hash(normalizeData(data)); + const hash = keccak256Hash(normalize(data)); // eslint-disable-next-line no-magic-numbers return `0x${hash.slice(-40)}`; } @@ -81,7 +103,7 @@ function last20bytesOfNormalizedKeccak256Hash(data: unknown): string { * @returns a random buffer of 32 bytes in a base64 string */ async function generate32BufferKey(): Promise { - return (await CryptoWrapper.random32Bytes()).toString('base64'); + return (await random32Bytes()).toString('base64'); } /** @@ -92,6 +114,6 @@ async function generate32BufferKey(): Promise { * @returns a string of 8 random bytes */ async function generate8randomBytes(): Promise { - const random32Bytes = await CryptoWrapper.random32Bytes(); - return random32Bytes.slice(0, 8).toString('hex'); + const random32BytesHex = await random32Bytes(); + return random32BytesHex.slice(0, 8).toString('hex'); } diff --git a/packages/utils/src/crypto/crypto-wrapper.ts b/packages/utils/src/crypto/crypto-wrapper.ts index 8517f6d38..50b015186 100644 --- a/packages/utils/src/crypto/crypto-wrapper.ts +++ b/packages/utils/src/crypto/crypto-wrapper.ts @@ -3,7 +3,7 @@ import { createCipheriv, createDecipheriv, randomBytes as cryptoRandomBytes } fr /** * Functions to manage native crypto functions of nodeJs */ -export const CryptoWrapper = { +export { decryptWithAes256cbc, decryptWithAes256gcm, encryptWithAes256cbc, diff --git a/packages/utils/src/crypto/ec-utils.ts b/packages/utils/src/crypto/ec-utils.ts index 78c097b1d..36caf4696 100644 --- a/packages/utils/src/crypto/ec-utils.ts +++ b/packages/utils/src/crypto/ec-utils.ts @@ -4,13 +4,13 @@ import { ethers } from 'ethers'; /** * Function to manage Elliptic-curve cryptography */ -export const EcUtils = { - decrypt, - encrypt, +export { + ecDecrypt, + ecEncrypt, getAddressFromPrivateKey, getAddressFromPublicKey, - recover, - sign, + ecRecover, + ecSign, }; /** @@ -61,13 +61,13 @@ function getAddressFromPublicKey(publicKey: string): string { } /** - * Function sign data with ECDSA + * Function ecSigndata with ECDSA * * @param data the data to sign * * @returns the signature */ -function sign(privateKey: string, data: string): string { +function ecSign(privateKey: string, data: string): string { try { const signingKey = new ethers.utils.SigningKey(privateKey); return ethers.utils.joinSignature(signingKey.signDigest(data)); @@ -91,7 +91,7 @@ function sign(privateKey: string, data: string): string { * * @returns the address */ -function recover(signature: string, data: string): string { +function ecRecover(signature: string, data: string): string { try { signature = signature.replace(/^0x/, ''); data = data.replace(/^0x/, ''); @@ -131,9 +131,9 @@ function recover(signature: string, data: string): string { * * @returns the encrypted data */ -async function encrypt(publicKey: string, data: string): Promise { +async function ecEncrypt(publicKey: string, data: string): Promise { try { - // Encrypts the data with the publicKey, returns the encrypted data with encryption parameters (such as IV..) + // encrypts the data with the publicKey, returns the encrypted data with encryption parameters (such as IV..) const compressed = compressPublicKey(publicKey); const encrypted = await EcCrypto.encrypt(Buffer.from(compressed), Buffer.from(data)); @@ -163,11 +163,11 @@ async function encrypt(publicKey: string, data: string): Promise { * * @returns the decrypted data */ -async function decrypt(privateKey: string, encrypted: string): Promise { +async function ecDecrypt(privateKey: string, data: string): Promise { try { const buf = await EcCrypto.decrypt( Buffer.from(privateKey.replace(/^0x/, ''), 'hex'), - eciesSplit(encrypted), + eciesSplit(data), ); return buf.toString(); } catch (e) { @@ -204,7 +204,7 @@ function compressPublicKey(publicKey: string): Uint8Array { /** * Split an encrypted string to ECIES params - * inspired from https://github.com/pubkey/eth-crypto/blob/master/src/decrypt-with-private-key.js + * inspired from https://github.com/pubkey/eth-crypto/blob/master/src/ecDecrypt-with-private-key.js */ const eciesSplit = (str: string): EcCrypto.Ecies => { const buf = Buffer.from(str, 'hex'); diff --git a/packages/utils/src/encryption.ts b/packages/utils/src/encryption.ts index 195470d6f..746c917b3 100644 --- a/packages/utils/src/encryption.ts +++ b/packages/utils/src/encryption.ts @@ -1,5 +1,13 @@ import { EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import { CryptoWrapper, EcUtils } from './crypto'; +import { + decryptWithAes256cbc, + decryptWithAes256gcm, + ecDecrypt, + ecEncrypt, + encryptWithAes256cbc, + encryptWithAes256gcm, + getAddressFromPublicKey, +} from './index'; /** * Functions to manage encryption @@ -19,7 +27,7 @@ function getIdentityFromEncryptionParams( if (encryptionParams.method === EncryptionTypes.METHOD.ECIES) { return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, - value: EcUtils.getAddressFromPublicKey(encryptionParams.key), + value: getAddressFromPublicKey(encryptionParams.key), }; } @@ -38,7 +46,7 @@ async function encrypt( encryptionParams: EncryptionTypes.IEncryptionParameters, ): Promise { if (encryptionParams.method === EncryptionTypes.METHOD.ECIES) { - const encryptedData = await EcUtils.encrypt(encryptionParams.key, data); + const encryptedData = await ecEncrypt(encryptionParams.key, data); return { type: EncryptionTypes.METHOD.ECIES, value: encryptedData, @@ -46,7 +54,7 @@ async function encrypt( } if (encryptionParams.method === EncryptionTypes.METHOD.AES256_CBC) { - const encryptedDataBuffer = await CryptoWrapper.encryptWithAes256cbc( + const encryptedDataBuffer = await encryptWithAes256cbc( Buffer.from(data, 'utf-8'), Buffer.from(encryptionParams.key, 'base64'), ); @@ -57,7 +65,7 @@ async function encrypt( } if (encryptionParams.method === EncryptionTypes.METHOD.AES256_GCM) { - const encryptedDataBuffer = await CryptoWrapper.encryptWithAes256gcm( + const encryptedDataBuffer = await encryptWithAes256gcm( Buffer.from(data, 'utf-8'), Buffer.from(encryptionParams.key, 'base64'), ); @@ -87,14 +95,14 @@ async function decrypt( if (decryptionParams.method !== EncryptionTypes.METHOD.ECIES) { throw new Error(`decryptionParams.method should be ${EncryptionTypes.METHOD.ECIES}`); } - return EcUtils.decrypt(decryptionParams.key, encryptedData.value); + return ecDecrypt(decryptionParams.key, encryptedData.value); } if (encryptedData.type === EncryptionTypes.METHOD.AES256_CBC) { if (decryptionParams.method !== EncryptionTypes.METHOD.AES256_CBC) { throw new Error(`decryptionParams.method should be ${EncryptionTypes.METHOD.AES256_CBC}`); } - const dataBuffer = await CryptoWrapper.decryptWithAes256cbc( + const dataBuffer = await decryptWithAes256cbc( // remove the multi-format padding and decode from the base64 to a buffer Buffer.from(encryptedData.value, 'base64'), Buffer.from(decryptionParams.key, 'base64'), @@ -107,7 +115,7 @@ async function decrypt( throw new Error(`decryptionParams.method should be ${EncryptionTypes.METHOD.AES256_GCM}`); } - const dataBuffer = await CryptoWrapper.decryptWithAes256gcm( + const dataBuffer = await decryptWithAes256gcm( // remove the multi-format padding and decode from the base64 to a buffer Buffer.from(encryptedData.value, 'base64'), Buffer.from(decryptionParams.key, 'base64'), diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 52c11c16f..2d28f7945 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -9,13 +9,22 @@ export { minBigNumber, maxBigNumber } from './bignumber'; export { cachedThrottle } from './cached-throttle'; export { - CryptoWrapper, - EcUtils, + decryptWithAes256cbc, + decryptWithAes256gcm, + encryptWithAes256cbc, + encryptWithAes256gcm, + random32Bytes, + ecDecrypt, + ecEncrypt, + getAddressFromPrivateKey, + getAddressFromPublicKey, + ecRecover, + ecSign, generate32BufferKey, generate8randomBytes, keccak256Hash, last20bytesOfNormalizedKeccak256Hash, - normalizeData, + normalize, normalizeKeccak256Hash, } from './crypto'; diff --git a/packages/utils/src/signature.ts b/packages/utils/src/signature.ts index 1ffb69b1f..869208810 100644 --- a/packages/utils/src/signature.ts +++ b/packages/utils/src/signature.ts @@ -1,6 +1,12 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import { ethers } from 'ethers'; -import { EcUtils, normalizeData, normalizeKeccak256Hash } from './crypto'; +import { + ecRecover, + ecSign, + getAddressFromPrivateKey, + normalize, + normalizeKeccak256Hash, +} from './crypto'; /** * Function to manage Request Logic Signature @@ -23,7 +29,7 @@ function getIdentityFromSignatureParams( if (signatureParams.method === SignatureTypes.METHOD.ECDSA) { return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, - value: EcUtils.getAddressFromPrivateKey(signatureParams.privateKey), + value: getAddressFromPrivateKey(signatureParams.privateKey), }; } @@ -45,13 +51,13 @@ function sign( ): SignatureTypes.ISignedData { let value: string; if (signatureParams.method === SignatureTypes.METHOD.ECDSA) { - value = EcUtils.sign(signatureParams.privateKey, normalizeKeccak256Hash(data).value); + value = ecSign(signatureParams.privateKey, normalizeKeccak256Hash(data).value); return { data, signature: { method: signatureParams.method, value } }; } if (signatureParams.method === SignatureTypes.METHOD.ECDSA_ETHEREUM) { - const normalizedData = normalizeData(data); - value = EcUtils.sign(signatureParams.privateKey, ethers.utils.hashMessage(normalizedData)); + const normalizedData = normalize(data); + value = ecSign(signatureParams.privateKey, ethers.utils.hashMessage(normalizedData)); return { data, signature: { method: signatureParams.method, value } }; } @@ -70,10 +76,7 @@ function sign( function recoverSigner(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentity { let value: string; if (signedData.signature.method === SignatureTypes.METHOD.ECDSA) { - value = EcUtils.recover( - signedData.signature.value, - normalizeKeccak256Hash(signedData.data).value, - ); + value = ecRecover(signedData.signature.value, normalizeKeccak256Hash(signedData.data).value); return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value, @@ -91,8 +94,8 @@ function recoverSigner(signedData: SignatureTypes.ISignedData): IdentityTypes.II } else if (v.toLowerCase() === '01') { signature = `${signedData.signature.value.slice(0, V_POSITION_FROM_END_IN_ECDSA_HEX)}1b`; } - const normalizedData = ethers.utils.hashMessage(normalizeData(signedData.data)); - value = EcUtils.recover(signature, normalizedData).toLowerCase(); + const normalizedData = ethers.utils.hashMessage(normalize(signedData.data)); + value = ecRecover(signature, normalizedData).toLowerCase(); return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, diff --git a/packages/utils/test/crypto.test.ts b/packages/utils/test/crypto.test.ts index 944957303..4647b33e2 100644 --- a/packages/utils/test/crypto.test.ts +++ b/packages/utils/test/crypto.test.ts @@ -3,7 +3,7 @@ import { generate32BufferKey, generate8randomBytes, last20bytesOfNormalizedKeccak256Hash, - normalizeData, + normalize, normalizeKeccak256Hash, } from '../src'; @@ -89,11 +89,11 @@ describe('Utils/crypto', () => { }); it('can normalize integer, null, string, undefined', () => { - expect(normalizeData('TesT')).toBe('"test"'); + expect(normalize('TesT')).toBe('"test"'); // eslint-disable-next-line no-magic-numbers - expect(normalizeData(12345)).toBe('12345'); - expect(normalizeData(null)).toBe('null'); - expect(normalizeData(undefined)).toBe('undefined'); + expect(normalize(12345)).toBe('12345'); + expect(normalize(null)).toBe('null'); + expect(normalize(undefined)).toBe('undefined'); }); it('can generate32BufferKey()', async () => { diff --git a/packages/utils/test/crypto/crypto-wrapper.test.ts b/packages/utils/test/crypto/crypto-wrapper.test.ts index 05ea73cfa..d794d39ec 100644 --- a/packages/utils/test/crypto/crypto-wrapper.test.ts +++ b/packages/utils/test/crypto/crypto-wrapper.test.ts @@ -1,4 +1,11 @@ -import { CryptoWrapper, unique } from '../../src'; +import { + decryptWithAes256cbc, + decryptWithAes256gcm, + encryptWithAes256cbc, + encryptWithAes256gcm, + random32Bytes, + unique, +} from '../../src'; const anyData = 'this is any data!'; const arbitraryKey = '12345678901234567890123456789012'; @@ -7,7 +14,7 @@ const arbitraryKey = '12345678901234567890123456789012'; describe('Utils/cryptoWrapper', () => { describe('random32Bytes', () => { it('can create a 32 bytes buffer', async () => { - const randomBytes = await CryptoWrapper.random32Bytes(); + const randomBytes = await random32Bytes(); // 'random32Bytes() error' expect(Buffer.isBuffer(randomBytes)).toBe(true); // eslint-disable-next-line no-magic-numbers @@ -17,7 +24,7 @@ describe('Utils/cryptoWrapper', () => { it('can create 1000 buffers with no duplicates random32Bytes()', async () => { // eslint-disable-next-line no-magic-numbers - const promises = new Array(1000).fill('').map(async () => CryptoWrapper.random32Bytes()); + const promises = new Array(1000).fill('').map(async () => random32Bytes()); const randomBytes1000 = await Promise.all(promises); // 'randomBytes gives duplicate' expect(unique(randomBytes1000).duplicates.length).toBe(0); @@ -26,7 +33,7 @@ describe('Utils/cryptoWrapper', () => { describe('encryptWithAes256cbc', () => { it('can encrypt with the aes256-cbc algorithm', async () => { - const encrypted = await CryptoWrapper.encryptWithAes256cbc( + const encrypted = await encryptWithAes256cbc( Buffer.from(anyData, 'utf8'), Buffer.from(arbitraryKey, 'utf8'), ); @@ -36,15 +43,15 @@ describe('Utils/cryptoWrapper', () => { expect(encrypted.length).toBe(48); // 'decrypt() error' - expect( - await CryptoWrapper.decryptWithAes256cbc(encrypted, Buffer.from(arbitraryKey, 'utf8')), - ).toEqual(Buffer.from(anyData, 'utf8')); + expect(await decryptWithAes256cbc(encrypted, Buffer.from(arbitraryKey, 'utf8'))).toEqual( + Buffer.from(anyData, 'utf8'), + ); }); }); describe('decryptWithAes256cbc', () => { it('can decrypt a message encrypted with the aes256-cbc algorithm', async () => { - const decrypted = await CryptoWrapper.decryptWithAes256cbc( + const decrypted = await decryptWithAes256cbc( Buffer.from('GAM/RiH/7R0MZC03cviYHQmCdH8VrBEAPAhSt2j+IH9ZNCZiut/JtZbVYmcslyWa', 'base64'), Buffer.from(arbitraryKey, 'utf8'), ); @@ -57,7 +64,7 @@ describe('Utils/cryptoWrapper', () => { describe('encryptWithAes256gcm', () => { it('can encrypt with the aes256-gcm algorithm', async () => { - const encrypted = await CryptoWrapper.encryptWithAes256gcm( + const encrypted = await encryptWithAes256gcm( Buffer.from(anyData, 'utf8'), Buffer.from(arbitraryKey, 'utf8'), ); @@ -66,14 +73,14 @@ describe('Utils/cryptoWrapper', () => { // 'encryptWithAes256gcm() error' expect(encrypted.length).toBe(49); // 'decrypt() error' - expect( - await CryptoWrapper.decryptWithAes256gcm(encrypted, Buffer.from(arbitraryKey, 'utf8')), - ).toEqual(Buffer.from(anyData, 'utf8')); + expect(await decryptWithAes256gcm(encrypted, Buffer.from(arbitraryKey, 'utf8'))).toEqual( + Buffer.from(anyData, 'utf8'), + ); }); }); describe('decryptWithAes256gcm', () => { it('can decrypt a message encrypted with the aes256-gcm algorithm', async () => { - const decrypted = await CryptoWrapper.decryptWithAes256gcm( + const decrypted = await decryptWithAes256gcm( Buffer.from( 'TTu/6w1cLS6ToK68ILt56eJ/dJGGbo+z/IwGLEg0WfD/naOONpInlrzQ2Zv1vYL+Vg==', 'base64', diff --git a/packages/utils/test/crypto/ec-utils.test.ts b/packages/utils/test/crypto/ec-utils.test.ts index 1770e079c..41d68b491 100644 --- a/packages/utils/test/crypto/ec-utils.test.ts +++ b/packages/utils/test/crypto/ec-utils.test.ts @@ -1,4 +1,11 @@ -import { EcUtils } from '../../src'; +import { + ecDecrypt, + ecEncrypt, + ecRecover, + ecSign, + getAddressFromPrivateKey, + getAddressFromPublicKey, +} from '../../src'; const rawId = { address: '0x818B6337657A23F58581715Fc610577292e521D0', @@ -14,22 +21,22 @@ const rawId = { const anyData = 'this is any data!'; /* eslint-disable @typescript-eslint/no-unused-expressions */ -describe('Utils.EcUtils', () => { +describe('Utils/EcUtils', () => { describe('getAddressFromPrivateKey', () => { it('can get Address From PrivateKey', () => { - const identity = EcUtils.getAddressFromPrivateKey(rawId.privateKey); + const identity = getAddressFromPrivateKey(rawId.privateKey); // 'getAddressFromPrivateKey() error' expect(identity).toBe(rawId.address); }); it('cannot get Address From PrivateKey if the private key is wrong', () => { // 'getAddressFromPrivateKey() error' - expect(() => EcUtils.getAddressFromPrivateKey('aa')).toThrowError( + expect(() => getAddressFromPrivateKey('aa')).toThrowError( 'The private key must be a string representing 32 bytes', ); }); it('can get an address from a private key without 0x', () => { expect( - EcUtils.getAddressFromPrivateKey( + getAddressFromPrivateKey( 'af16c10a33bd8c2a0d55551080c3eb248ab727e5ff17d052c95f9d92b7e6528e', ), ).toBe('0xe011e28aBAa005223a2d4AEfFD5c2fF8D7B5291c'); @@ -38,13 +45,13 @@ describe('Utils.EcUtils', () => { describe('getAddressFromPublicKey', () => { it('can get Address From Public Key', () => { - const identity = EcUtils.getAddressFromPublicKey(rawId.publicKey); + const identity = getAddressFromPublicKey(rawId.publicKey); // 'getAddressFromPublicKey() error' expect(identity).toBe(rawId.address); }); it('cannot get Address From Public Key if the Public key is wrong', () => { // 'getAddressFromPrivateKey() error' - expect(() => EcUtils.getAddressFromPublicKey('aa')).toThrowError( + expect(() => getAddressFromPublicKey('aa')).toThrowError( 'The public key must be a string representing 64 bytes', ); }); @@ -52,7 +59,7 @@ describe('Utils.EcUtils', () => { describe('sign', () => { it('can sign', () => { - const signature = EcUtils.sign( + const signature = ecSign( rawId.privateKey, '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f', ); @@ -64,14 +71,14 @@ describe('Utils.EcUtils', () => { it('cannot signs if the private key is wrong', () => { // 'sign() error' expect(() => - EcUtils.sign('aa', '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f'), + ecSign('aa', '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f'), ).toThrowError('The private key must be a string representing 32 bytes'); }); }); - describe('recover', () => { + describe('ecRecover', () => { it('can recover address from a signature', () => { - const id = EcUtils.recover( + const id = ecRecover( '0xdf4d49c7c01e00a970378e5a400dd4168aed6c43a1c510b124026467c78a3566048549c6ab5e0f618e2939c518e9fbe52e07836d4cb07fa44186fa3ffe3b3b981b', '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f', ); @@ -81,25 +88,22 @@ describe('Utils.EcUtils', () => { it('cannot recover address from signature if signature is not well formatted', () => { // 'sign() error' expect(() => - EcUtils.recover( - '0xaa', - '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f', - ), + ecRecover('0xaa', '0xfd6201dabdd4d7177f7c3baba47c5533b12f0a8127ab5d8c71d831fa4df2b19f'), ).toThrowError('The signature must be a string representing 66 bytes'); }); }); describe('encrypt', () => { it('can encrypt', async () => { - const encryptedData = await EcUtils.encrypt(rawId.publicKey, anyData); + const encryptedData = await ecEncrypt(rawId.publicKey, anyData); // 'encrypt() error' expect(encryptedData.length).toBe(226); // 'decrypt() error' - expect(await EcUtils.decrypt(rawId.privateKey, encryptedData)).toBe(anyData); + expect(await ecDecrypt(rawId.privateKey, encryptedData)).toBe(anyData); }); it('can encrypt with other public key formats', async () => { - const encryptedData = await EcUtils.encrypt( + const encryptedData = await ecEncrypt( '0396212fc129c2f78771218b2e93da7a5aac63490a42bb41b97848c39c14fe65cd', anyData, ); @@ -107,7 +111,7 @@ describe('Utils.EcUtils', () => { }); it('cannot encrypt data with a wrong public key', async () => { - await expect(EcUtils.encrypt('cf4a', anyData)).rejects.toThrowError( + await expect(ecEncrypt('cf4a', anyData)).rejects.toThrowError( 'The public key must be a string representing 64 bytes', ); }); @@ -115,7 +119,7 @@ describe('Utils.EcUtils', () => { describe('decrypt', () => { it('can decrypt', async () => { - const data = await EcUtils.decrypt( + const data = await ecDecrypt( rawId.privateKey, '307bac038efaa5bf8a0ac8db53fd4de8024a0c0baf37283a9e6671589eba18edc12b3915ff0df66e6ffad862440228a65ead99e3320e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc70a', ); @@ -125,7 +129,7 @@ describe('Utils.EcUtils', () => { it('cannot decrypt data with a wrong private key', async () => { await expect( - EcUtils.decrypt( + ecDecrypt( '0xaa', '307bac038efaa5bf8a0ac8db53fd4de8024a0c0baf37283a9e6671589eba18edc12b3915ff0df66e6ffad862440228a65ead99e3320e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc70a', ), @@ -133,14 +137,14 @@ describe('Utils.EcUtils', () => { }); it('cannot decrypt data with a wrong encrypted data: public key too short', async () => { - await expect(EcUtils.decrypt(rawId.privateKey, 'aa')).rejects.toThrowError( + await expect(ecDecrypt(rawId.privateKey, 'aa')).rejects.toThrowError( 'The encrypted data is not well formatted', ); }); it('cannot decrypt data with a wrong encrypted data: public key not parsable', async () => { await expect( - EcUtils.decrypt( + ecDecrypt( rawId.privateKey, 'e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc7', ), @@ -149,7 +153,7 @@ describe('Utils.EcUtils', () => { it('cannot decrypt data with a wrong encrypted data: bad MAC', async () => { await expect( - EcUtils.decrypt( + ecDecrypt( rawId.privateKey, '307bac038efaa5bf8a0ac8db53fd4de8024a0c0baf37283a9e6671589eba18edc12b3915ff0df66e6ffad862440228a65ead99e3320e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc7', ), @@ -158,15 +162,15 @@ describe('Utils.EcUtils', () => { }); it('can encrypt()', async () => { - const encryptedData = await EcUtils.encrypt(rawId.publicKey, anyData); + const encryptedData = await ecEncrypt(rawId.publicKey, anyData); // 'encrypt() error' expect(encryptedData.length).toBe(226); // 'decrypt() error' - expect(await EcUtils.decrypt(rawId.privateKey, encryptedData)).toBe(anyData); + expect(await ecDecrypt(rawId.privateKey, encryptedData)).toBe(anyData); }); it('can decrypt()', async () => { - const data = await EcUtils.decrypt( + const data = await ecDecrypt( rawId.privateKey, '307bac038efaa5bf8a0ac8db53fd4de8024a0c0baf37283a9e6671589eba18edc12b3915ff0df66e6ffad862440228a65ead99e3320e50aa90008961e3d68acc35b314e98020e3280bf4ce4258419dbb775185e60b43e7b88038a776a9322ff7cb3e886b2d92060cff2951ef3beedcc70a', ); diff --git a/packages/web3-signature/src/web3-signature-provider.ts b/packages/web3-signature/src/web3-signature-provider.ts index a1485f62e..3527b631b 100644 --- a/packages/web3-signature/src/web3-signature-provider.ts +++ b/packages/web3-signature/src/web3-signature-provider.ts @@ -1,6 +1,6 @@ import { IdentityTypes, SignatureProviderTypes, SignatureTypes } from '@requestnetwork/types'; -import { areEqualIdentities, normalizeData, recoverSigner } from '@requestnetwork/utils'; +import { areEqualIdentities, normalize, recoverSigner } from '@requestnetwork/utils'; import { providers } from 'ethers'; @@ -41,7 +41,7 @@ export default class Web3SignatureProvider implements SignatureProviderTypes.ISi throw Error(`Identity type not supported ${signer.type}`); } - const normalizedData = normalizeData(data); + const normalizedData = normalize(data); const signerEthers = this.web3Provider.getSigner(signer.value); let signatureValue; diff --git a/packages/web3-signature/test/web3-signature-provider.test.ts b/packages/web3-signature/test/web3-signature-provider.test.ts index eae6173f2..280e75d2a 100644 --- a/packages/web3-signature/test/web3-signature-provider.test.ts +++ b/packages/web3-signature/test/web3-signature-provider.test.ts @@ -2,7 +2,7 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import Web3SignatureProvider from '../src/web3-signature-provider'; -import { EcUtils, normalizeKeccak256Hash } from '@requestnetwork/utils'; +import { ecSign, normalizeKeccak256Hash } from '@requestnetwork/utils'; const id1Raw = { identity: { @@ -17,7 +17,7 @@ const id1Raw = { const data = { What: 'ever', the: 'data', are: true }; const hashData = normalizeKeccak256Hash(data).value; -const signatureValueExpected = EcUtils.sign(id1Raw.signatureParams.privateKey, hashData); +const signatureValueExpected = ecSign(id1Raw.signatureParams.privateKey, hashData); const mockWeb3: any = { getSigner: jest.fn().mockImplementation(() => ({