diff --git a/packages/advanced-logic/src/extensions/abstract-extension.ts b/packages/advanced-logic/src/extensions/abstract-extension.ts index b0c0f847b1..1b545a4543 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 15df7d9fa6..a21350b02e 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 { areEqualIdentities, 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 (!areEqualIdentities(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 (!areEqualIdentities(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 231a18bd74..634f21cc7a 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 { 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 (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValidAmount(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 = 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 (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValidAmount(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 = 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 (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValidAmount(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 = 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 (!Utils.amount.isValid(extensionAction.parameters.amount)) { + if (!isValidAmount(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 = addAmount( 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 (areEqualIdentities(actionSigner, requestState.payee)) { delegateStr = 'payeeDelegate'; - } else if (Utils.identity.areEqual(actionSigner, requestState.payer)) { + } else if (areEqualIdentities(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; @@ -567,8 +567,8 @@ export default class DeclarativePaymentNetwork< throw Error(`The request must have a ${requestRoleStr}`); } if ( - !Utils.identity.areEqual(actionSigner, requestRole) && - !Utils.identity.areEqual(actionSigner, requestRoleDelegate) + !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 e64f24787c..1b8e2da50e 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 { 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 && - !Utils.amount.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 && - !Utils.amount.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 26ff07ef88..132f264ff0 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 { 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 && !Utils.amount.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 && !Utils.amount.isValid(addFeeParameters.feeAmount)) { + if (addFeeParameters.feeAmount && !isValidAmount(addFeeParameters.feeAmount)) { throw Error('feeAmount is not a valid amount'); } @@ -103,7 +103,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< } if ( extensionAction.parameters.feeAmount && - !Utils.amount.isValid(extensionAction.parameters.feeAmount) + !isValidAmount(extensionAction.parameters.feeAmount) ) { throw Error('feeAmount is not a valid amount'); } @@ -162,7 +162,7 @@ export abstract class FeeReferenceBasedPaymentNetwork< } if ( extensionAction.parameters.feeAmount && - !Utils.amount.isValid(extensionAction.parameters.feeAmount) + !isValidAmount(extensionAction.parameters.feeAmount) ) { throw Error('feeAmount is not a valid amount'); } @@ -172,11 +172,11 @@ export abstract class FeeReferenceBasedPaymentNetwork< if (!requestState.payee) { throw Error(`The request must have a payee`); } - if (!Utils.identity.areEqual(actionSigner, requestState.payee)) { + if (!areEqualIdentities(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 87bc868c7b..53cba4d377 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 f832ef72e7..a23d9629d0 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 6efd8bd628..7975ba1d62 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 95329b82ea..9c33c9d562 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 c9eaef8add..b9e099d1ce 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 5e62bb7902..1671625232 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 3b193bcc9c..7133bad547 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 6628872c80..e500322d49 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 7a8c3306c2..f55fbe41c6 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 b7c0079459..824f0a3f81 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 822f168fa2..af4e4e4205 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 d45766ad10..640eec5547 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 226c27f6e7..8bfd5557b7 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 dba01e5d3d..a29f0e2d76 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 de53e5a98e..66e970df6b 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 4232f5dd66..b12f63de09 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 df9ddf8728..47a961b898 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 93c6263848..c84cc6d84d 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 e293092f31..534477d0d3 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 974fec219b..4a35c595ac 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, getAddressFromPrivateKey } 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 = 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 7869098246..da11831808 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 3991ac1051..8643360bf0 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 { ecSign, getAddressFromPrivateKey, 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 = ecSign(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 = 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 fbf75dc8ff..5f2c001f05 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 { ecSign, 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 = ecSign(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 249d695099..01623fe035 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 c7a6878867..05e7737ddc 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 e38eed5dda..52180f5bf5 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 1e8233b566..672d4503f8 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 fff8224c24..09afa7c8d7 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 6cc60927a8..7bd232392b 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 8c711653fa..3f7b9e5a79 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 e2eb0fdb5c..f84928d4ac 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 f405cab967..411a75e0b2 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 65fc0938ab..a4d2cd8484 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 603dd4ff63..6df4a11b1a 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 fa15336e8d..2c184c37ae 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 d087235551..2ba90d6a04 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 ab02c30bab..bcc4ffa622 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 2d9b09d3d4..1e72d03a60 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 f5e7a546a6..41a1ae5283 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 e760cd1e64..1e135712fc 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 2ff4628239..9e336cc8c8 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 b8e3f42ede..3963d2949a 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 '@requestnetwork/utils'; /** 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 19a37a7c2b..9419633018 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 a161e61504..e9914b2d0b 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 4d7d4290a8..83ec48fa74 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 6ac867f730..8258ce457f 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 9a799e64ba..c138c985d0 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 85cf51921a..d8dec80d4a 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 13508da647..68b8888a14 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 4fff9e8ad7..2f128d97e8 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 41a0cae66e..2ce08aa646 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 6090052165..ff21683f41 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 cca9da8eec..789cefdd23 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 7df5724262..1922c65633 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 6dd8736513..3ba743999b 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 904485b1cd..8204115fb6 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 842b98518e..59be645432 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 111d953260..934e2c34e0 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 773bc66ddb..14e5216031 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 da95d9f1bf..48822ca8d1 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 c48df462a2..9ce12f0b2a 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/any-to-near.test.ts b/packages/payment-processor/test/payment/any-to-near.test.ts index 8d43edb0d1..323bce6a07 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: { 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 6a7e977ea8..800685317c 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 3b9bef071b..1391f50088 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 2c2003feb2..592b5a527f 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 9356a02d0a..5139c18ef9 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 468ed981f1..2b01b425d9 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 86327cbc84..f44ae6fbed 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 b46174a3e7..5f39d8d0c7 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 5a52eeaca4..f4eaefd648 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 534b592315..979090db5a 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 886341368e..a95aec8c21 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 d395917041..dd5e5a74af 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 54dfd91030..db4166116b 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 8e9a9fe782..a74c16faa3 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 e403fa0f44..9d236811b5 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 7712094bf3..4eee0e979a 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 bb4f646131..cf43976699 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 dd13b9fc0d..ca27f67cfb 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 3599ce9638..6cfb0394d7 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 d0b2aa2817..fed1c9dd8f 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 8f22d33061..6ed341a2c9 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 42c8a3339a..74b625611b 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 6e105fc244..54a1fd9dec 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 c4ee9e2a7c..140452cb74 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 { decrypt, random32Bytes } 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 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, @@ -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 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/request-logic/specs/example/example.ts b/packages/request-logic/specs/example/example.ts index a3d9af920f..69f4915b2f 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 1a15ca1dd0..bc2ec49b77 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, 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 Utils.signature.recover(action); + return recoverSigner(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 a8538323c0..712ad73206 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 66c711dac1..9fd3034ad5 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 48d432b21b..b09816a3b3 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 bd0b60c80e..c6c24ca7b6 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, + identityHasError, + isString, + isValidAmount, +} 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 (!isValidAmount(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 && identityHasError(requestParameters.payee)) { + throw new Error(`payee: ${identityHasError(requestParameters.payee)}̀`); } - if (requestParameters.payer && Utils.identity.hasError(requestParameters.payer)) { - throw new Error(`payer: ${Utils.identity.hasError(requestParameters.payer)}̀`); + if (requestParameters.payer && identityHasError(requestParameters.payer)) { + throw new Error(`payer: ${identityHasError(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 && identityHasError(action.data.parameters.payee)) { + throw new Error(`payee: ${identityHasError(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 && identityHasError(action.data.parameters.payer)) { + throw new Error(`payer: ${identityHasError(action.data.parameters.payer)}̀`); } if ( - !Utils.isString(action.data.parameters.expectedAmount) || - !Utils.amount.isValid(action.data.parameters.expectedAmount) + !isString(action.data.parameters.expectedAmount) || + !isValidAmount(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 0a47e68588..f273b092d2 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 { 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 (!Utils.amount.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 (!Utils.amount.isValid(action.data.parameters.deltaAmount)) { + if (!isValidAmount(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'); } // increase the expected amount and store it as string - requestCopied.expectedAmount = Utils.amount.add( + requestCopied.expectedAmount = addAmount( request.expectedAmount, action.data.parameters.deltaAmount, ); diff --git a/packages/request-logic/src/actions/reduceExpectedAmount.ts b/packages/request-logic/src/actions/reduceExpectedAmount.ts index dda8868dfa..dfc0485a6e 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, 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 (!Utils.amount.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 (!Utils.amount.isValid(action.data.parameters.deltaAmount)) { + if (!isValidAmount(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 = reduceAmount( 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 6ad87a8312..63b5c323c3 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 25eb798a7e..04b8720e67 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 { 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 (!Utils.amount.isValid(request.expectedAmount)) { + if (!isValidAmount(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 2d3c497c9a..f4da831dd3 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 098cb99f19..b918392163 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 { 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 && Utils.identity.areEqual(parameters.payee, identity)) { + if (parameters.payee && areEqualIdentities(parameters.payee, identity)) { return RequestLogicTypes.ROLE.PAYEE; } - if (parameters.payer && Utils.identity.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 e8650a8dff..d0b3cbd0dc 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 4a53d3a0a7..a308739dbf 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 b006bdbdc1..2f7b3d1726 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 840fc793dc..95b769f839 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 3608378fa8..580be2f782 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 781a9b43ab..bfcd3fcdf4 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 6cee4bfd6e..f9166d9ab9 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 c03c4c3451..190e3aeb5c 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 4c7b610215..bb85cfcf68 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 3e8f190e0f..25a107eb20 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 f9e5650745..fb2980810f 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 9b190c369c..768e72244e 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 3ca028e001..5fcd451841 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 12666e35f0..81c05c5be4 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 81bbddcf5a..757a603329 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 d5a7db0370..4cd49ecd5b 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 e02716a455..6d304a7130 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 637c4ce360..e1c3c689a1 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 f6445261eb..344126d209 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 c8e8e00880..c9026faf4a 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 5f12cc1315..6506ae36a0 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 d08067258c..93288dcaa7 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/thegraph-data-access/src/data-access.ts b/packages/thegraph-data-access/src/data-access.ts index 273b1ad9dc..9078137d8b 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 585f9a0f69..b92a3ea419 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 52404a3641..2a903bb076 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 fcfc86eabb..3733127abe 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 427c818c8c..d285111054 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 658ac3b350..9a639d078c 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 0aae90e5d0..979aa9ddbd 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 4441cc7ce7..6ad4b4cfae 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 e34c119d19..52b1aaf7ef 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 156119639b..c42d65ded0 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 821e7de438..8f80914b4c 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 54dfd91030..db4166116b 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/.eslintrc b/packages/utils/.eslintrc new file mode 100644 index 0000000000..f465e15adc --- /dev/null +++ b/packages/utils/.eslintrc @@ -0,0 +1,5 @@ +{ + "rules": { + "import/no-default-export": "error" + } +} diff --git a/packages/utils/README.md b/packages/utils/README.md index 0198b28554..5905257c54 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 - - crypto.normalizeKeccak256Hash() - - crypto.ecUtils.getAddressFromPrivateKey() - - crypto.ecUtils.recover() - - crypto.ecUtils.sign() - - signature.getIdentityFromSignatureParams() - - signature.recover() - - signature.sign() -- Identity - - identity.areEqual() - - identity.normalizeIdentityValue() - - isString -- Miscellaneous - - deepCopy() - - deepSort() - - flatten2DimensionsArray() - - getCurrentTimestampInSecond() - ## Installation ```bash @@ -30,9 +12,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/src/amount.ts b/packages/utils/src/amount.ts index 9982f1e9d2..b78f36bb40 100644 --- a/packages/utils/src/amount.ts +++ b/packages/utils/src/amount.ts @@ -1,16 +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 { - add, - isValid, - reduce, -}; +export { addAmount, isValidAmount, reduceAmount }; const regexInteger = RegExp(/^[\d]+$/); @@ -21,9 +17,9 @@ 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 ( - (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) ); } @@ -36,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'); } @@ -59,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'); } @@ -72,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 876db4126e..1f94abbbe5 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 default { min, max }; +export { minBigNumber, maxBigNumber }; diff --git a/packages/utils/src/cached-throttle.ts b/packages/utils/src/cached-throttle.ts index 175f9bd40a..cd98bc061c 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 11acb1f3e0..bc99fa3769 100644 --- a/packages/utils/src/crypto.ts +++ b/packages/utils/src/crypto.ts @@ -1,15 +1,37 @@ 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 { + 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 default { - CryptoWrapper, - EcUtils, +export { + decryptWithAes256cbc, + decryptWithAes256gcm, + encryptWithAes256cbc, + encryptWithAes256gcm, + random32Bytes, + ecDecrypt, + ecEncrypt, + getAddressFromPrivateKey, + getAddressFromPublicKey, + ecRecover, + ecSign, generate32BufferKey, generate8randomBytes, keccak256Hash, @@ -45,7 +67,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(); @@ -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 a102e47fdf..50b0151868 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 { decryptWithAes256cbc, decryptWithAes256gcm, encryptWithAes256cbc, diff --git a/packages/utils/src/crypto/ec-utils.ts b/packages/utils/src/crypto/ec-utils.ts index 3030d9b514..36caf46965 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 default { - 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 feddb5c620..746c917b33 100644 --- a/packages/utils/src/encryption.ts +++ b/packages/utils/src/encryption.ts @@ -1,14 +1,18 @@ import { EncryptionTypes, IdentityTypes } from '@requestnetwork/types'; -import Crypto from './crypto'; +import { + decryptWithAes256cbc, + decryptWithAes256gcm, + ecDecrypt, + ecEncrypt, + encryptWithAes256cbc, + encryptWithAes256gcm, + getAddressFromPublicKey, +} from './index'; /** * Functions to manage encryption */ -export default { - decrypt, - encrypt, - getIdentityFromEncryptionParams, -}; +export { decrypt, encrypt, getIdentityFromEncryptionParams }; /** * Function to get the identity from the encryption parameters @@ -23,7 +27,7 @@ function getIdentityFromEncryptionParams( if (encryptionParams.method === EncryptionTypes.METHOD.ECIES) { return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, - value: Crypto.EcUtils.getAddressFromPublicKey(encryptionParams.key), + value: getAddressFromPublicKey(encryptionParams.key), }; } @@ -42,7 +46,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 ecEncrypt(encryptionParams.key, data); return { type: EncryptionTypes.METHOD.ECIES, value: encryptedData, @@ -50,7 +54,7 @@ async function encrypt( } if (encryptionParams.method === EncryptionTypes.METHOD.AES256_CBC) { - const encryptedDataBuffer = await Crypto.CryptoWrapper.encryptWithAes256cbc( + const encryptedDataBuffer = await encryptWithAes256cbc( Buffer.from(data, 'utf-8'), Buffer.from(encryptionParams.key, 'base64'), ); @@ -61,7 +65,7 @@ async function encrypt( } if (encryptionParams.method === EncryptionTypes.METHOD.AES256_GCM) { - const encryptedDataBuffer = await Crypto.CryptoWrapper.encryptWithAes256gcm( + const encryptedDataBuffer = await encryptWithAes256gcm( Buffer.from(data, 'utf-8'), Buffer.from(encryptionParams.key, 'base64'), ); @@ -91,14 +95,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 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 Crypto.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'), @@ -111,7 +115,7 @@ async function decrypt( throw new Error(`decryptionParams.method should be ${EncryptionTypes.METHOD.AES256_GCM}`); } - const dataBuffer = await Crypto.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/estimate-gas-fees.ts b/packages/utils/src/estimate-gas-fees.ts index 15f4ebce14..ec21ef3b69 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 { 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 = Utils.max(suggestedFee.baseFeeSuggestion, gasPriceMin || constants.Zero); + const baseFee = maxBigNumber(suggestedFee.baseFeeSuggestion, gasPriceMin || constants.Zero); - const maxPriorityFeePerGas = Utils.max( + const maxPriorityFeePerGas = maxBigNumber( 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 dc0b52c97b..febe2f887f 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 default { - areEqual, - hasError, - normalizeIdentityValue, - supportedIdentities, -}; +export { areEqualIdentities, identityHasError, normalizeIdentityValue, supportedIdentities }; /** * Checks if two identities are equals @@ -22,7 +17,7 @@ export default { * @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 && @@ -47,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 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 71289d7296..2d28f79455 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -1,30 +1,66 @@ -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, - cachedThrottle, - crypto, - encryption, - identity, - retry, - signature, - ...providers, - ...utils, - ...bignumbers, - estimateGasFees, -}; + +export { addAmount, isValidAmount, reduceAmount } from './amount'; + +export { minBigNumber, maxBigNumber } from './bignumber'; + +export { cachedThrottle } from './cached-throttle'; + +export { + decryptWithAes256cbc, + decryptWithAes256gcm, + encryptWithAes256cbc, + encryptWithAes256gcm, + random32Bytes, + ecDecrypt, + ecEncrypt, + getAddressFromPrivateKey, + getAddressFromPublicKey, + ecRecover, + ecSign, + generate32BufferKey, + generate8randomBytes, + keccak256Hash, + last20bytesOfNormalizedKeccak256Hash, + normalize, + normalizeKeccak256Hash, +} from './crypto'; + +export { decrypt, encrypt, getIdentityFromEncryptionParams } from './encryption'; + +export { estimateGasFees } from './estimate-gas-fees'; + +export { + areEqualIdentities, + identityHasError, + normalizeIdentityValue, + supportedIdentities, +} from './identity'; + +export { + setProviderFactory, + initPaymentDetectionApiKeys, + getDefaultProvider, + getCeloProvider, + networkRpcs, +} from './providers'; + +export { retry } from './retry'; + +export { getIdentityFromSignatureParams, recoverSigner, 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 13cdc1046b..93c2e73b68 100644 --- a/packages/utils/src/providers.ts +++ b/packages/utils/src/providers.ts @@ -147,7 +147,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 10a20e21d6..fe534442ce 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 0ec39b24b6..8692088108 100644 --- a/packages/utils/src/signature.ts +++ b/packages/utils/src/signature.ts @@ -1,15 +1,17 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; import { ethers } from 'ethers'; -import Crypto from './crypto'; +import { + ecRecover, + ecSign, + getAddressFromPrivateKey, + normalize, + normalizeKeccak256Hash, +} from './crypto'; /** * Function to manage Request Logic Signature */ -export default { - getIdentityFromSignatureParams, - recover, - sign, -}; +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; @@ -27,7 +29,7 @@ function getIdentityFromSignatureParams( if (signatureParams.method === SignatureTypes.METHOD.ECDSA) { return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, - value: Crypto.EcUtils.getAddressFromPrivateKey(signatureParams.privateKey), + value: getAddressFromPrivateKey(signatureParams.privateKey), }; } @@ -49,19 +51,13 @@ function sign( ): SignatureTypes.ISignedData { let value: string; if (signatureParams.method === SignatureTypes.METHOD.ECDSA) { - value = Crypto.EcUtils.sign( - signatureParams.privateKey, - Crypto.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 = Crypto.normalize(data); - value = Crypto.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 } }; } @@ -77,13 +73,10 @@ function sign( * @param signedData the data signed * @returns identity of the signer */ -function recover(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentity { +function recoverSigner(signedData: SignatureTypes.ISignedData): IdentityTypes.IIdentity { let value: string; if (signedData.signature.method === SignatureTypes.METHOD.ECDSA) { - value = Crypto.EcUtils.recover( - signedData.signature.value, - Crypto.normalizeKeccak256Hash(signedData.data).value, - ); + value = ecRecover(signedData.signature.value, normalizeKeccak256Hash(signedData.data).value); return { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value, @@ -101,8 +94,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 = ecRecover(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 45b2595e44..a2f709d109 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 5e8f622f48..f512a539ed 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 4d8892487d..d13cd746ac 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 { 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(Amount.isValid(magicIntegerSmall)).toBe(true); + expect(isValidAmount(magicIntegerSmall)).toBe(true); }); it('cannot valid amount as big integer', () => { // 'Big integer should not be valid' - expect(Amount.isValid(magicIntegerBig)).toBe(false); + expect(isValidAmount(magicIntegerBig)).toBe(false); }); it('cannot valid amount as bn', () => { // 'BN should not be valid' - expect(Amount.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(Amount.isValid('10000')).toBe(true); + expect(isValidAmount('10000')).toBe(true); }); it('cannot valid amount as a small decimal', () => { // 'decimal should not be valid' - expect(Amount.isValid(magicFloatSmall)).toBe(false); + expect(isValidAmount(magicFloatSmall)).toBe(false); }); it('cannot valid amount as a big decimal', () => { // 'decimal should not be valid' - expect(Amount.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(Amount.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(Amount.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(Amount.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(Amount.isValid(-magicIntegerSmall)).toBe(false); + expect(isValidAmount(-magicIntegerSmall)).toBe(false); }); it('cannot valid amount as big integer negative', () => { // 'Big integer should not be valid' - expect(Amount.isValid(-magicIntegerBig)).toBe(false); + expect(isValidAmount(-magicIntegerBig)).toBe(false); }); it('cannot valid an empty string', () => { // 'Empty string should not be valid' - expect(Amount.isValid('')).toBe(false); + expect(isValidAmount('')).toBe(false); }); }); describe('add', () => { it('cannot add amounts not number', () => { - expect(() => Amount.add('Not a number', '1000000000000000000')).toThrowError( + expect(() => addAmount('Not a number', '1000000000000000000')).toThrowError( 'amount must represent a positive integer', ); - expect(() => Amount.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(Amount.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(() => Amount.reduce('Not a number', '1000000000000000000')).toThrowError( + expect(() => reduceAmount('Not a number', '1000000000000000000')).toThrowError( 'amount must represent a positive integer', ); - expect(() => Amount.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(Amount.reduce(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( + expect(reduceAmount(arbitraryExpectedAmount, arbitraryDeltaAmount)).toBe( arbitraryExpectedAmountMinusDelta, ); }); it('cannot reduce lower zero', () => { - expect(() => Amount.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 73135f12b9..1b2a9c907b 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 { maxBigNumber, minBigNumber } 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(minBigNumber(1, 2)).toMatchObject(BigNumber.from(1)); + expect(minBigNumber(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(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(Utils.max(1, 2)).toMatchObject(BigNumber.from(2)); - expect(Utils.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(Utils.max(1, 0)).toMatchObject(BigNumber.from(1)); - expect(Utils.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/cached-thottle.test.ts b/packages/utils/test/cached-thottle.test.ts index 59ca968b01..fed1d7b67f 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 085020ffee..4647b33e23 100644 --- a/packages/utils/test/crypto.test.ts +++ b/packages/utils/test/crypto.test.ts @@ -1,8 +1,14 @@ 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', () => { +describe('Utils/crypto', () => { it('can normalizeKeccak256Hash', () => { const arbitraryObject = { param1: 'valC', @@ -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 80c63d3259..d794d39ec9 100644 --- a/packages/utils/test/crypto/crypto-wrapper.test.ts +++ b/packages/utils/test/crypto/crypto-wrapper.test.ts @@ -1,14 +1,20 @@ -import CryptoWrapper from '../../src/crypto/crypto-wrapper'; -import utils from '../../src/utils'; +import { + decryptWithAes256cbc, + decryptWithAes256gcm, + encryptWithAes256cbc, + encryptWithAes256gcm, + random32Bytes, + unique, +} from '../../src'; 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(); + const randomBytes = await random32Bytes(); // 'random32Bytes() error' expect(Buffer.isBuffer(randomBytes)).toBe(true); // eslint-disable-next-line no-magic-numbers @@ -18,16 +24,16 @@ 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(utils.unique(randomBytes1000).duplicates.length).toBe(0); + expect(unique(randomBytes1000).duplicates.length).toBe(0); }); }); 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'), ); @@ -37,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'), ); @@ -58,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'), ); @@ -67,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 2b0c9f50d6..41d68b4916 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/crypto/ec-utils'; +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/utils/test/encryption.test.ts b/packages/utils/test/encryption.test.ts index 696496c911..dd6bfaaa14 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,46 +57,37 @@ describe('Encryption', () => { describe('encrypt', () => { it('can encrypt with ECIES', async () => { - const encryptedData = await Encryption.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' 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( - JSON.stringify(data), - arbitraryAES256cbcEncryptionParams, - ); + const encryptedData = await encrypt(JSON.stringify(data), arbitraryAES256cbcEncryptionParams); // 'encrypt() error' expect(encryptedData.value.length).toBe(88); // '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( - JSON.stringify(data), - arbitraryAES256gcmEncryptionParams, - ); + const encryptedData = await encrypt(JSON.stringify(data), arbitraryAES256gcmEncryptionParams); // 'encrypt() error' expect(encryptedData.value.length).toBe(100); // '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 +98,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 +106,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 +120,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 +133,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 +143,7 @@ describe('Encryption', () => { ).rejects.toThrowError('decryptionParams.method should be ecies'); await expect( - Encryption.decrypt( + decrypt( { type: EncryptionTypes.METHOD.AES256_CBC, value: 'c9a9', @@ -162,7 +153,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 9d06a0b750..17462f1eae 100644 --- a/packages/utils/test/identity.test.ts +++ b/packages/utils/test/identity.test.ts @@ -1,16 +1,16 @@ import { IdentityTypes } from '@requestnetwork/types'; -import Identity from '../src/identity'; +import { areEqualIdentities, 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', ); }); - 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(Identity.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(Identity.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(Identity.areEqual(id1, id2)).toBe(false); + // 'areEqualIdentities() error' + expect(areEqualIdentities(id1, id2)).toBe(false); }); }); diff --git a/packages/utils/test/retry.test.ts b/packages/utils/test/retry.test.ts index 5667699472..5d143033b4 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 e6a2f008e3..bbf3c166b6 100644 --- a/packages/utils/test/signature.test.ts +++ b/packages/utils/test/signature.test.ts @@ -1,6 +1,10 @@ import { IdentityTypes, SignatureTypes } from '@requestnetwork/types'; -import Crypto from '../src/crypto'; -import Signature from '../src/signature'; +import { + getIdentityFromSignatureParams, + normalizeKeccak256Hash, + recoverSigner, + sign, +} from '../src'; const otherIdRaw = { address: '0x818B6337657A23F58581715Fc610577292e521D0', @@ -31,7 +35,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 +48,7 @@ describe('Signature', () => { method: 'notECDSA', privateKey: otherIdRaw.privateKey, }; - expect(() => Signature.getIdentityFromSignatureParams(params)).toThrowError( + expect(() => getIdentityFromSignatureParams(params)).toThrowError( 'signatureParams.method not supported', ); }); @@ -52,7 +56,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 +72,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 +88,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,15 +108,15 @@ 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', ); }); }); describe('recover', () => { - it('can recover() ECDSA signature', () => { - const id = Signature.recover({ + it('can recoverSigner() ECDSA signature', () => { + const id = recoverSigner({ data, signature: { method: SignatureTypes.METHOD.ECDSA, @@ -120,12 +124,12 @@ describe('Signature', () => { '0x801f4240516509c28660f096830d52e8523e2136d557d65728e39f3ea37b72bb3f20accff461cabe3515431d0e6c468d4631540b7c6f9c29acfa7c9231781a3c1c', }, }); - // 'recover() error' + // 'recoverSigner() error' expect(id).toEqual(otherIdRaw.identity); }); - it('can recover() ECDSA_ETHEREUM signature', () => { - const id = Signature.recover({ + it('can recoverSigner() ECDSA_ETHEREUM signature', () => { + const id = recoverSigner({ data, signature: { method: SignatureTypes.METHOD.ECDSA_ETHEREUM, @@ -133,14 +137,14 @@ describe('Signature', () => { '0x3fbc7ed9dfa003067f646749d4223def2a69df70371d4f15ec001bc1491cdee40558de1f31fdc7cc5d805a5c4080b54cda3430b29ab14f04e17a5b23fcd39b391b', }, }); - // 'recover() error' + // 'recoverSigner() error' expect(id.value).toEqual(otherIdRaw.identity.value.toLowerCase()); - // 'recover() error' + // 'recoverSigner() error' expect(id.type).toEqual(otherIdRaw.identity.type); }); - it('can recover() with different case', () => { - const id = Signature.recover({ + it('can recoverSigner() with different case', () => { + const id = recoverSigner({ data: dataDiffCase, signature: { method: SignatureTypes.METHOD.ECDSA, @@ -148,7 +152,7 @@ describe('Signature', () => { '0x801f4240516509c28660f096830d52e8523e2136d557d65728e39f3ea37b72bb3f20accff461cabe3515431d0e6c468d4631540b7c6f9c29acfa7c9231781a3c1c', }, }); - // 'recover() error' + // 'recoverSigner() error' expect(id).toEqual(otherIdRaw.identity); }); @@ -157,7 +161,7 @@ describe('Signature', () => { method: 'notECDSA', value: '0x00000000000000000000', }; - expect(() => Signature.recover({ data, signature: params })).toThrowError( + expect(() => recoverSigner({ 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 fcd2fd65ef..245026c054 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 cda4f810e8..6177dedb78 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]); }); @@ -251,7 +260,7 @@ describe('Utils', () => { expect.assertions(3); const promise = new Promise(() => {}); - Utils.timeoutPromise(promise, 1000, errorMessage) + timeoutPromise(promise, 1000, errorMessage) .then(() => { fail('timeoutPromise should not be fulfilled'); }) diff --git a/packages/web3-signature/src/web3-signature-provider.ts b/packages/web3-signature/src/web3-signature-provider.ts index 64949eddc3..3527b631ba 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 { 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 = 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 (areEqualIdentities(recoverSigner(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 e34f38f833..280e75d2ad 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 { ecSign, 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 = ecSign(id1Raw.signatureParams.privateKey, hashData); const mockWeb3: any = { getSigner: jest.fn().mockImplementation(() => ({