diff --git a/README.md b/README.md index cb7e01b88c..600f705a18 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ ## Polymesh version -This release is compatible with Polymesh v7.3-v8.0 +This release is compatible with Polymesh v8.0 ## Getting Started diff --git a/src/api/client/AccountManagement.ts b/src/api/client/AccountManagement.ts index 78c3937253..77ae653f9b 100644 --- a/src/api/client/AccountManagement.ts +++ b/src/api/client/AccountManagement.ts @@ -121,10 +121,6 @@ export class AccountManagement { }, context ); - this.subsidizeAccount = createProcedureMethod( - { getProcedureAndArgs: args => [subsidizeAccount, { ...args, isV7Method: true }] }, - context - ); this.acceptSubsidy = createProcedureMethod( { getProcedureAndArgs: args => [acceptSubsidy, args] }, context @@ -134,7 +130,7 @@ export class AccountManagement { context ); this.approveSubsidy = createProcedureMethod( - { getProcedureAndArgs: args => [subsidizeAccount, { ...args, isV7Method: false }] }, + { getProcedureAndArgs: args => [subsidizeAccount, { ...args }] }, context ); this.createMultiSigAccount = createProcedureMethod( @@ -197,17 +193,6 @@ export class AccountManagement { */ public unfreezeSecondaryAccounts: NoArgsProcedureMethod; - /** - * Send an Authorization Request to an Account to subsidize its transaction fees - * - * @note this will create an {@link AuthorizationRequest | Authorization Request} which has to be accepted by the `beneficiary` Account. - * An {@link Account} or {@link Identity} can fetch its pending Authorization Requests by calling {@link api/entities/common/namespaces/Authorizations!Authorizations.getReceived | authorizations.getReceived}. - * Also, an Account or Identity can directly fetch the details of an Authorization Request by calling {@link api/entities/common/namespaces/Authorizations!Authorizations.getOne | authorizations.getOne} - * - * @deprecated use {@link approveSubsidy} instead from chain v8 - */ - public subsidizeAccount: ProcedureMethod; - /** * Approves a subsidy request * @@ -215,9 +200,7 @@ export class AccountManagement { * * @note this will create a pending subsidies entry, which has to be accepted by the `beneficiary` Account. Pending subsidies for a beneficiary can be fetched by calling {@link api/entities/Subsidies!Subsidies.getPendingSubsidies | subsidies.getPendingSubsidies}. * - * @throws - * - if called for a v7 chain - * - if same allowance amount is pending for acceptance with respect to same beneficiary + * @throws if same allowance amount is pending for acceptance with respect to same beneficiary */ public approveSubsidy: ProcedureMethod; @@ -225,7 +208,6 @@ export class AccountManagement { * Accepts a pending subsidy request from subsidizer * * @note Only the beneficiary can accept an already approved subsidy request. Pending subsidies for a beneficiary can be fetched by calling {@link api/entities/Subsidies!Subsidies.getPendingSubsidies | subsidies.getPendingSubsidies}. - * @note this is only available from chain v8 */ public acceptSubsidy: ProcedureMethod; @@ -233,7 +215,6 @@ export class AccountManagement { * Revokes an already approved subsidy request * * @note Only the subsidizer can revoke an already approved subsidy request. Pending subsidies for a beneficiary can be fetched by calling {@link api/entities/Subsidies!Subsidies.getPendingSubsidies | subsidies.getPendingSubsidies}. - * @note this is only available from chain v8 */ public revokeSubsidy: ProcedureMethod; diff --git a/src/api/client/Claims.ts b/src/api/client/Claims.ts index 31e726ff13..2e0f365af0 100644 --- a/src/api/client/Claims.ts +++ b/src/api/client/Claims.ts @@ -1,7 +1,5 @@ -import { Vec } from '@polkadot/types'; -import { IdentityClaim } from '@polymeshassociation/polymesh-types/polkadot/polymesh'; import BigNumber from 'bignumber.js'; -import { filter, flatten, isEqual, uniqBy, uniqWith } from 'lodash'; +import { isEqual, uniqBy, uniqWith } from 'lodash'; import { Context, @@ -17,7 +15,6 @@ import { } from '~/middleware/queries/claims'; import { ClaimsOrderBy, Query } from '~/middleware/types'; import { - CddClaim, ClaimData, ClaimOperation, ClaimScope, @@ -43,12 +40,8 @@ import { bigNumberToU32, bytesToString, claimTypeInputToMiddlewareClaimTypeDetails, - identityIdToString, - meshClaimToClaim, - momentToDate, scopeToMiddlewareScope, signerToString, - stringToIdentityId, toCustomClaimTypeWithIdentity, toIdentityWithClaimsArray, u32ToBigNumber, @@ -240,7 +233,7 @@ export class Claims { ); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - targetIssuers = flatten(groupedTargets!.map(groupedTarget => groupedTarget.keys!)); + targetIssuers = groupedTargets!.map(groupedTarget => groupedTarget.keys!).flat(); } // note: pagination count is based on the target issuers and not the claims count @@ -386,71 +379,6 @@ export class Claims { ); } - /** - * Retrieve the list of CDD claims for a target Identity - * - * @deprecated CDD claims are no longer supported with v8 chains - * - * @param opts.target - Identity for which to fetch CDD claims (optional, defaults to the signing Identity) - * @param opts.includeExpired - whether to include expired claims. Defaults to true - */ - public async getCddClaims( - opts: { - target?: string | Identity; - includeExpired?: boolean; - } = {} - ): Promise[]> { - const { - context, - context: { - polymeshApi: { call }, - }, - } = this; - - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'CDD claims are no longer supported in chain v8', - }); - } - - const { identityApi: identity } = call; - - if (!identity) { - return []; - } - - const { target, includeExpired = true } = opts; - - const did = await getDid(target, context); - - const rawDid = stringToIdentityId(did, context); - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const result: Vec = await (identity as any).validCddClaims(rawDid, null); - - const data: ClaimData[] = []; - - result.forEach(optClaim => { - const { claimIssuer, issuanceDate, lastUpdateDate, expiry: rawExpiry, claim } = optClaim; - - const expiry = rawExpiry.isSome ? momentToDate(rawExpiry.unwrap()) : null; - - if ((!includeExpired && (expiry === null || expiry > new Date())) || includeExpired) { - data.push({ - target: new Identity({ did }, context), - issuer: new Identity({ did: identityIdToString(claimIssuer) }, context), - issuedAt: momentToDate(issuanceDate), - lastUpdatedAt: momentToDate(lastUpdateDate), - expiry, - claim: meshClaimToClaim(claim) as CddClaim, - }); - } - }); - - return data; - } - /** * @hidden */ @@ -475,7 +403,7 @@ export class Claims { const identitiesWithClaims = issuers.map(identity => ({ identity, - claims: filter(identityClaimsFromChain, ({ issuer }) => issuer.isEqual(identity)), + claims: identityClaimsFromChain.filter(({ issuer }) => issuer.isEqual(identity)), })); return { @@ -539,7 +467,7 @@ export class Claims { ); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - claimIssuers = flatten(groupedIssuers!.map(groupedAggregate => groupedAggregate.keys!)); + claimIssuers = groupedIssuers!.map(groupedAggregate => groupedAggregate.keys!).flat(); } // note: pagination count is based on the claim issuers and not the claims count diff --git a/src/api/client/Identities.ts b/src/api/client/Identities.ts index 3faf824b20..14673e794a 100644 --- a/src/api/client/Identities.ts +++ b/src/api/client/Identities.ts @@ -3,10 +3,7 @@ import { allowIdentityToCreatePortfolios, attestPrimaryKeyRotation, AuthorizationRequest, - ChildIdentity, Context, - createChildIdentities, - createChildIdentity, createPortfolios, Identity, NumberedPortfolio, @@ -19,8 +16,6 @@ import { import { AllowIdentityToCreatePortfoliosParams, AttestPrimaryKeyRotationParams, - CreateChildIdentitiesParams, - CreateChildIdentityParams, NoArgsProcedureMethod, ProcedureMethod, RegisterIdentityParams, @@ -96,20 +91,6 @@ export class Identities { context ); - this.createChild = createProcedureMethod( - { - getProcedureAndArgs: args => [createChildIdentity, args], - }, - context - ); - - this.createChildren = createProcedureMethod( - { - getProcedureAndArgs: args => [createChildIdentities, args], - }, - context - ); - this.allowIdentityToCreatePortfolios = createProcedureMethod( { getProcedureAndArgs: args => [allowIdentityToCreatePortfolios, args] }, context @@ -210,18 +191,6 @@ export class Identities { return this.context.getIdentity(args.did); } - /** - * Create a ChildIdentity instance from a DID - * - * @throws if there is no ChildIdentity with the passed DID - * - * @deprecated Child identities are no longer supported in chain v8 - */ - public getChildIdentity(args: { did: string }): Promise { - // NOSONAR - return this.context.getChildIdentity(args.did); - } - /** * Return whether the supplied Identity/DID exists */ @@ -229,36 +198,6 @@ export class Identities { return asIdentity(args.identity, this.context).exists(); } - /** - * Creates a child identity and makes the `secondaryKey` as the primary key of the child identity - * - * @note the given `secondaryKey` is removed as secondary key from the signing Identity - * - * @throws if - * - the transaction signer is not the primary account of which the `secondaryKey` is a secondary key - * - the `secondaryKey` can't be unlinked (can happen when it's part of a multisig with some balance) - * - the signing account is not a primary key - * - the signing Identity is already a child of some other identity - * - * @deprecated Child identities are no longer supported in chain v8 - */ - public createChild: ProcedureMethod; - - /** - * Create child identities using off chain authorization - * - * @note the list of `key` provided in the params should not be linked to any other account - * - * @throws if - * - the signing account is not a primary key - * - the signing Identity is already a child of some other identity - * - `expiresAt` is not a future date - * - the any `key` in `childKeyAuths` is already linked to an Identity - * - * @deprecated Child identities are no longer supported in chain v8 - */ - public createChildren: ProcedureMethod; - /** * Gives permission to the Identity to create Portfolios on behalf of the signing Identity * diff --git a/src/api/client/Staking.ts b/src/api/client/Staking.ts index cf745fbc8d..914549d94e 100644 --- a/src/api/client/Staking.ts +++ b/src/api/client/Staking.ts @@ -20,7 +20,6 @@ import { PaginationOptions, ProcedureMethod, ResultSet, - SetStakingControllerParams, SetStakingPayeeParams, StakingCommission, StakingEraInfo, @@ -87,7 +86,8 @@ export class Staking { this.setController = createProcedureMethod( { - getProcedureAndArgs: args => [setStakingController, args], + getProcedureAndArgs: () => [setStakingController, undefined], + voidArgs: true, }, context ); @@ -134,12 +134,11 @@ export class Staking { public nominate: ProcedureMethod; /** - * Allow for a stash account to update its controller + * Allow for a stash account to update its controller so the stash becomes its own controller * * @note the transaction must be signed by a stash account - * @note Polymesh v8 makes it so the stash will become its own controller account */ - public setController: ProcedureMethod; + public setController: NoArgsProcedureMethod; /** * Allow for a stash account to update where it's staking rewards are deposited diff --git a/src/api/client/__tests__/AccountManagement.ts b/src/api/client/__tests__/AccountManagement.ts index 37ab18044c..fff847b578 100644 --- a/src/api/client/__tests__/AccountManagement.ts +++ b/src/api/client/__tests__/AccountManagement.ts @@ -180,26 +180,6 @@ describe('AccountManagement class', () => { }); }); - describe('method: subsidizeAccount', () => { - it('should prepare the procedure with the correct arguments and context, and return the resulting transaction', async () => { - const args = { - beneficiary: 'someAccount', - allowance: new BigNumber(1000), - }; - - const expectedTransaction = - 'someTransaction' as unknown as PolymeshTransaction; - - when(procedureMockUtils.getPrepareMock()) - .calledWith({ args: { ...args, isV7Method: true }, transformer: undefined }, context, {}) - .mockResolvedValue(expectedTransaction); - - const tx = await accountManagement.subsidizeAccount(args); // NOSONAR - - expect(tx).toEqual(expectedTransaction); - }); - }); - describe('method: acceptSubsidy', () => { it('should prepare the procedure with the correct arguments and context, and return the resulting transaction', async () => { const args = { @@ -247,7 +227,7 @@ describe('AccountManagement class', () => { 'someTransaction' as unknown as PolymeshTransaction; when(procedureMockUtils.getPrepareMock()) - .calledWith({ args: { ...args, isV7Method: false }, transformer: undefined }, context, {}) + .calledWith({ args, transformer: undefined }, context, {}) .mockResolvedValue(expectedTransaction); const tx = await accountManagement.approveSubsidy(args); @@ -439,7 +419,6 @@ describe('AccountManagement class', () => { it('should prepare the procedure with the correct arguments and context, and return the resulting transaction', async () => { const args = { ownerAuth: new BigNumber(1), - cddAuth: new BigNumber(2), }; const expectedTransaction = 'someTransaction' as unknown as PolymeshTransaction; diff --git a/src/api/client/__tests__/Claims.ts b/src/api/client/__tests__/Claims.ts index 81be935970..c50b624335 100644 --- a/src/api/client/__tests__/Claims.ts +++ b/src/api/client/__tests__/Claims.ts @@ -28,7 +28,6 @@ import { } from '~/types'; import { DEFAULT_GQL_PAGE_SIZE } from '~/utils/constants'; import * as utilsConversionModule from '~/utils/conversion'; -import * as utilsInternalModule from '~/utils/internal'; jest.mock( '~/api/entities/Identity', @@ -189,7 +188,7 @@ describe('Claims Class', () => { expect(result.data).toEqual(expect.arrayContaining(expectedClaims)); expect(result.count).toEqual(new BigNumber(1)); - expect(result.next).toEqual(null); + expect(result.next).toBeNull(); dsMockUtils.createApolloMultipleQueriesMock([ { @@ -221,7 +220,7 @@ describe('Claims Class', () => { expect(result.data).toEqual(expect.arrayContaining(expectedClaims)); expect(result.count).toEqual(new BigNumber(1)); - expect(result.next).toEqual(null); + expect(result.next).toBeNull(); }); it('should return a list of Identities with claims associated to them filtered by scope', async () => { @@ -427,99 +426,6 @@ describe('Claims Class', () => { }); }); - describe('method: getCddClaims', () => { - afterAll(() => { - jest.restoreAllMocks(); - }); - it('should return a list of cdd claims', async () => { - context.isV7 = true; - const target = 'someTarget'; - jest.spyOn(utilsInternalModule, 'getDid').mockResolvedValue(target); - - const rawTarget = dsMockUtils.createMockIdentityId(target); - jest.spyOn(utilsConversionModule, 'stringToIdentityId').mockReturnValue(rawTarget); - - const claimIssuer = 'someClaimIssuer'; - const issuanceDate = new Date('2023/01/01'); - const lastUpdateDate = new Date('2023/06/01'); - const claim = { - type: ClaimType.CustomerDueDiligence, - id: 'someCddId', - }; - - const rawIdentityClaim = { - claimIssuer: dsMockUtils.createMockIdentityId(claimIssuer), - issuanceDate: dsMockUtils.createMockMoment(new BigNumber(issuanceDate.getTime())), - lastUpdateDate: dsMockUtils.createMockMoment(new BigNumber(lastUpdateDate.getTime())), - expiry: dsMockUtils.createMockOption(), - claim: dsMockUtils.createMockClaim({ - CustomerDueDiligence: dsMockUtils.createMockCddId(claim.id), - }), - }; - - jest.spyOn(utilsConversionModule, 'identityIdToString').mockReturnValue(claimIssuer); - dsMockUtils.createCallMock<'identityApi', 'validCddClaims'>('identityApi', 'validCddClaims', { - returnValue: [rawIdentityClaim], - }); - - const mockResult = { - target: expect.objectContaining({ - did: target, - }), - issuer: expect.objectContaining({ - did: claimIssuer, - }), - issuedAt: issuanceDate, - lastUpdatedAt: lastUpdateDate, - expiry: null, - claim, - }; - let result = await claims.getCddClaims(); - - expect(result).toEqual([mockResult]); - - const expiry = new Date('2030/01/01'); - dsMockUtils.createCallMock('identityApi', 'validCddClaims', { - returnValue: [ - { - ...rawIdentityClaim, - expiry: dsMockUtils.createMockOption( - dsMockUtils.createMockMoment(new BigNumber(expiry.getTime())) - ), - }, - ], - }); - - result = await claims.getCddClaims({ target, includeExpired: false }); - - expect(result).toEqual([ - { - ...mockResult, - expiry, - }, - ]); - }); - - it('should throw an error if the chain version is v8', async () => { - context.isV7 = false; - await expect( - claims.getCddClaims() // NOSONAR - ).rejects.toThrow('CDD claims are no longer supported in chain v8'); - }); - - it('should return an empty list if identityApi is not available on call', async () => { - context.isV7 = true; - const identityApi = context.polymeshApi.call.identityApi; - // @ts-expect-error The operand of a 'delete' operator must be optional - delete context.polymeshApi.call.identityApi; - - const result = await claims.getCddClaims(); // NOSONAR - expect(result).toEqual([]); - - context.polymeshApi.call.identityApi = identityApi; - }); - }); - describe('method: getClaimScopes', () => { it('should return a list of scopes and asset IDs', async () => { const target = 'someTarget'; @@ -560,7 +466,7 @@ describe('Claims Class', () => { result = await claims.getClaimScopes(); - expect(result.length).toEqual(2); + expect(result).toHaveLength(2); }); it('should return a list of scopes and asset IDs with middleware enabled', async () => { @@ -749,7 +655,7 @@ describe('Claims Class', () => { expect(result[0]!.scope).toEqual({ type: ScopeType.Identity, value: someDid }); expect(result[1]!.assetId).toEqual(assetId); expect(result[1]!.scope).toEqual({ type: ScopeType.Asset, value: assetId }); - expect(result.length).toEqual(2); + expect(result).toHaveLength(2); expect(getIdentitiesWithClaimsSpy).toHaveBeenCalledTimes(2); }); }); @@ -834,7 +740,7 @@ describe('Claims Class', () => { expect(result.data).toEqual(fakeClaims); expect(result.count).toEqual(new BigNumber(1)); - expect(result.next).toEqual(null); + expect(result.next).toBeNull(); dsMockUtils.createApolloMultipleQueriesMock([ { @@ -942,13 +848,13 @@ describe('Claims Class', () => { target, }); - expect(result.data.length).toEqual(2); + expect(result.data).toHaveLength(2); expect(result.data[0]!.identity.did).toEqual(issuer); - expect(result.data[0]!.claims.length).toEqual(2); + expect(result.data[0]!.claims).toHaveLength(2); expect(result.data[0]!.claims[0]!.claim).toEqual(identityClaims[0]!.claim); expect(result.data[0]!.claims[1]!.claim).toEqual(identityClaims[1]!.claim); expect(result.data[1]!.identity.did).toEqual(otherIssuer); - expect(result.data[1]!.claims.length).toEqual(1); + expect(result.data[1]!.claims).toHaveLength(1); expect(result.data[1]!.claims[0]!.claim).toEqual(identityClaims[2]!.claim); result = await claims.getTargetingClaims({ @@ -956,7 +862,7 @@ describe('Claims Class', () => { trustedClaimIssuers: ['trusted'], }); - expect(result.data.length).toEqual(2); + expect(result.data).toHaveLength(2); }); }); diff --git a/src/api/client/__tests__/Identities.ts b/src/api/client/__tests__/Identities.ts index 29ee281b57..ef97ca7206 100644 --- a/src/api/client/__tests__/Identities.ts +++ b/src/api/client/__tests__/Identities.ts @@ -2,16 +2,10 @@ import { when } from 'jest-when'; import { Identities } from '~/api/client/Identities'; import { createPortfolioTransformer } from '~/api/entities/Venue'; -import { - ChildIdentity, - Context, - Identity, - NumberedPortfolio, - PolymeshTransaction, -} from '~/internal'; +import { Context, Identity, NumberedPortfolio, PolymeshTransaction } from '~/internal'; import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; import { Mocked } from '~/testUtils/types'; -import { CreateChildIdentitiesParams, RotatePrimaryKeyToSecondaryParams } from '~/types'; +import { RotatePrimaryKeyToSecondaryParams } from '~/types'; import { tuple } from '~/types/utils'; import * as utilsConversionModule from '~/utils/conversion'; @@ -63,64 +57,6 @@ describe('Identities Class', () => { }); }); - describe('method: getChildIdentity', () => { - it('should return a ChildIdentity object with the passed did', async () => { - const params = { did: 'testDid' }; - - const childIdentity = new ChildIdentity(params, context); - context.getChildIdentity.mockResolvedValue(childIdentity); - - const result = await identities.getChildIdentity(params); - - expect(result).toMatchObject(childIdentity); - }); - }); - - describe('method: createChild', () => { - it('should prepare the procedure with the correct arguments and context, and return the resulting transaction', async () => { - const args = { - secondaryKey: 'someChild', - }; - - const expectedTransaction = - 'someTransaction' as unknown as PolymeshTransaction; - - when(procedureMockUtils.getPrepareMock()) - .calledWith({ args, transformer: undefined }, context, {}) - .mockResolvedValue(expectedTransaction); - - const tx = await identities.createChild(args); - - expect(tx).toBe(expectedTransaction); - }); - }); - - describe('method: createChildren', () => { - it('should prepare the procedure with the correct arguments and context, and return the resulting transaction', async () => { - const args: CreateChildIdentitiesParams = { - childKeyAuths: [ - { - key: 'someKey', - authSignature: '0xsignature', - }, - ], - expiresAt: new Date('2050/01/01'), - }; - - const expectedTransaction = 'someTransaction' as unknown as PolymeshTransaction< - ChildIdentity[] - >; - - when(procedureMockUtils.getPrepareMock()) - .calledWith({ args, transformer: undefined }, context, {}) - .mockResolvedValue(expectedTransaction); - - const tx = await identities.createChildren(args); - - expect(tx).toBe(expectedTransaction); - }); - }); - describe('method: registerIdentity', () => { it('should prepare the procedure with the correct arguments and context, and return the resulting transaction', async () => { const args = { diff --git a/src/api/client/__tests__/Staking.ts b/src/api/client/__tests__/Staking.ts index 448d5c5cc2..28cf68c36d 100644 --- a/src/api/client/__tests__/Staking.ts +++ b/src/api/client/__tests__/Staking.ts @@ -154,17 +154,13 @@ describe('Staking Class', () => { describe('method: setController', () => { it('should prepare the procedure with the correct arguments and context, and return the resulting transaction', async () => { - const args = { - controller: 'someAccount', - }; - const expectedTransaction = 'someTransaction' as unknown as PolymeshTransaction; when(procedureMockUtils.getPrepareMock()) - .calledWith({ args, transformer: undefined }, mockContext, {}) + .calledWith({ args: undefined, transformer: undefined }, mockContext, {}) .mockResolvedValue(expectedTransaction); - const tx = await staking.setController(args); + const tx = await staking.setController(); expect(tx).toBe(expectedTransaction); }); diff --git a/src/api/entities/Account/Staking/index.ts b/src/api/entities/Account/Staking/index.ts index ef3ed24297..d02c08fcc0 100644 --- a/src/api/entities/Account/Staking/index.ts +++ b/src/api/entities/Account/Staking/index.ts @@ -1,6 +1,6 @@ import { Option } from '@polkadot/types'; import { AccountId, RewardDestination } from '@polkadot/types/interfaces'; -import { PalletStakingNominations, PalletStakingRewardDestination } from '@polkadot/types/lookup'; +import { PalletStakingNominations } from '@polkadot/types/lookup'; import { Account, Namespace } from '~/internal'; import { @@ -96,10 +96,7 @@ export class Staking extends Namespace { }); const payeeUnsub = await query.staking.payee(rawAddress, rawPayee => { - // istanbul ignore next: will be removed with v7 support - const payee = context.isV7 - ? (rawPayee as unknown as PalletStakingRewardDestination) - : rawPayee.unwrapOr(null); + const payee = rawPayee.unwrapOr(null); const result = assembleResult(payee, controller); // eslint-disable-next-line @typescript-eslint/no-floating-promises @@ -117,10 +114,7 @@ export class Staking extends Namespace { this.getController(), ]); - // istanbul ignore next: will be removed with v7 support - const payee = context.isV7 - ? (rawPayee as unknown as PalletStakingRewardDestination) - : rawPayee.unwrap(); + const payee = rawPayee.unwrap(); return assembleResult(payee, controller); } diff --git a/src/api/entities/Account/__tests__/index.ts b/src/api/entities/Account/__tests__/index.ts index f71ca7fc43..2a243925d9 100644 --- a/src/api/entities/Account/__tests__/index.ts +++ b/src/api/entities/Account/__tests__/index.ts @@ -1151,16 +1151,7 @@ describe('Account class', () => { }); describe('method: getCollections', () => { - it('should throw an error if the chain version is v7', async () => { - context.isV7 = true; - await expect(account.getCollections()).rejects.toThrow( - 'Account.getCollections is not supported for chain 7.x' - ); - }); - it('should return collections held by the Account', async () => { - context.isV7 = false; - const rawAccountId = dsMockUtils.createMockAccountId(address); jest.spyOn(utilsConversionModule, 'stringToAccountId').mockReturnValue(rawAccountId); diff --git a/src/api/entities/Account/index.ts b/src/api/entities/Account/index.ts index 7621c27148..e4e07df1fc 100644 --- a/src/api/entities/Account/index.ts +++ b/src/api/entities/Account/index.ts @@ -767,13 +767,6 @@ export class Account extends Entity { context, } = this; - if (context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'Account.getCollections is not supported for chain 7.x', - }); - } - const rawAccountId = stringToAccountId(address, context); let queriedCollections: string[] | undefined; diff --git a/src/api/entities/Asset/NonFungible/Nft.ts b/src/api/entities/Asset/NonFungible/Nft.ts index fadee86a09..b6835cc7fd 100644 --- a/src/api/entities/Asset/NonFungible/Nft.ts +++ b/src/api/entities/Asset/NonFungible/Nft.ts @@ -1,4 +1,3 @@ -import { PolymeshPrimitivesNftNftOwnerStatus } from '@polkadot/types/lookup'; import BigNumber from 'bignumber.js'; import { Account, Context, Entity, NftCollection, PolymeshError, redeemNft } from '~/internal'; @@ -262,20 +261,11 @@ export class Nft extends Entity { const rawNftId = bigNumberToU64(id, context); if (owner instanceof Account) { - let rawLocked: PolymeshPrimitivesNftNftOwnerStatus; - if (context.isV7) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - rawLocked = await (nft.nftHolder as any)(stringToAccountId(owner.address, context), [ - rawAssetId, - rawNftId, - ]); - } else { - rawLocked = await nft.nftHolder( - stringToAccountId(owner.address, context), - rawAssetId, - rawNftId - ); - } + const rawLocked = await nft.nftHolder( + stringToAccountId(owner.address, context), + rawAssetId, + rawNftId + ); return meshNftOwnerStatusToNftOwnerStatus(rawLocked) === NftOwnerStatus.OwnerLocked; } diff --git a/src/api/entities/Asset/__tests__/NonFungible/Nft.ts b/src/api/entities/Asset/__tests__/NonFungible/Nft.ts index cb9641e77f..61f51aff7c 100644 --- a/src/api/entities/Asset/__tests__/NonFungible/Nft.ts +++ b/src/api/entities/Asset/__tests__/NonFungible/Nft.ts @@ -485,35 +485,7 @@ describe('Nft class', () => { expect(result).toBe(true); }); - - it('should return whether NFT is locked in any settlement when owner is an Account (context isV7)', async () => { - const owner = entityMockUtils.getAccountInstance({ address: 'ownerAddress' }); - ownerSpy.mockResolvedValue(owner); - - context.isV7 = true; - - const rawOwner = dsMockUtils.createMockAccountId(owner.address); - const stringToAccountIdSpy = jest.spyOn(utilsConversionModule, 'stringToAccountId'); - when(stringToAccountIdSpy).calledWith(owner.address, context).mockReturnValue(rawOwner); - - const rawLocked = dsMockUtils.createMockNftOwnerStatus(NftOwnerStatus.OwnerLocked); - const nftHolderMock = dsMockUtils.createQueryMock('nft', 'nftHolder'); - nftHolderMock.mockResolvedValue(rawLocked); - - const meshNftOwnerStatusToNftOwnerStatusSpy = jest.spyOn( - utilsConversionModule, - 'meshNftOwnerStatusToNftOwnerStatus' - ); - when(meshNftOwnerStatusToNftOwnerStatusSpy) - .calledWith(rawLocked) - .mockReturnValue(NftOwnerStatus.OwnerLocked); - - const result = await nft.isLocked(); - - expect(result).toBe(true); - }); }); - describe('method: toHuman', () => { it('should return a human readable version of the entity', () => { const context = dsMockUtils.getContextInstance(); diff --git a/src/api/entities/AuthorizationRequest.ts b/src/api/entities/AuthorizationRequest.ts index 8e2226c380..4fc486fe84 100644 --- a/src/api/entities/AuthorizationRequest.ts +++ b/src/api/entities/AuthorizationRequest.ts @@ -3,8 +3,6 @@ import BigNumber from 'bignumber.js'; import { consumeAddMultiSigSignerAuthorization, ConsumeAddMultiSigSignerAuthorizationParams, - consumeAddRelayerPayingKeyAuthorization, - ConsumeAddRelayerPayingKeyAuthorizationParams, consumeAuthorizationRequests, ConsumeAuthorizationRequestsParams, consumeJoinOrRotateAuthorization, @@ -12,10 +10,12 @@ import { Context, Entity, Identity, + PolymeshError, } from '~/internal'; import { Authorization, AuthorizationType, + ErrorCode, NoArgsProcedureMethod, Signer, SignerValue, @@ -117,8 +117,7 @@ export class AuthorizationRequest extends Entity { switch (this.data.type) { - case AuthorizationType.AddRelayerPayingKey: { - return [consumeAddRelayerPayingKeyAuthorization, { authRequest: this, accept: true }]; + case AuthorizationType.OldAddRelayerPayingKey: { + throw new PolymeshError({ + code: ErrorCode.NotSupported, + message: + 'Accepting this type of Authorization Request is no longer supported. Use AccountManagement.approveSubsidy instead', + }); } case AuthorizationType.JoinIdentity: case AuthorizationType.RotatePrimaryKey: @@ -150,8 +153,7 @@ export class AuthorizationRequest extends Entity { switch (this.data.type) { - case AuthorizationType.AddRelayerPayingKey: { - return [ - consumeAddRelayerPayingKeyAuthorization, - { authRequest: this, accept: false }, - ]; - } case AuthorizationType.JoinIdentity: case AuthorizationType.RotatePrimaryKeyToSecondary: { return [consumeJoinOrRotateAuthorization, { authRequest: this, accept: false }]; diff --git a/src/api/entities/Identity/ChildIdentity.ts b/src/api/entities/Identity/ChildIdentity.ts deleted file mode 100644 index 3c6fb5725b..0000000000 --- a/src/api/entities/Identity/ChildIdentity.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { UniqueIdentifiers } from '~/api/entities/Identity'; -import { unlinkChildIdentity } from '~/api/procedures/unlinkChildIdentity'; -import { Context, Identity, PolymeshError } from '~/internal'; -import { ErrorCode, NoArgsProcedureMethod } from '~/types'; -import { identityIdToString, stringToIdentityId } from '~/utils/conversion'; -import { createProcedureMethod } from '~/utils/internal'; - -/** - * Represents a child identity - * - * @deprecated child identities are no longer supported in chain v8 - */ -export class ChildIdentity extends Identity { - /** - * @hidden - */ - public constructor(identifiers: UniqueIdentifiers, context: Context) { - super(identifiers, context); - - this.unlinkFromParent = createProcedureMethod( - { - getProcedureAndArgs: () => [unlinkChildIdentity, { child: this }], - voidArgs: true, - }, - context - ); - } - - /** - * Returns the parent of this Identity (if any) - * - * @deprecated - */ - public async getParentDid(): Promise { - const { - context: { - polymeshApi: { - query: { identity }, - }, - }, - context, - did, - } = this; - - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'getParentDid is not supported in v8', - }); - } - - const rawIdentityId = stringToIdentityId(did, context); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const rawParentDid = await (identity as any).parentDid(rawIdentityId); - - if (rawParentDid.isEmpty) { - return null; - } - - const parentDid = identityIdToString(rawParentDid.unwrap()); - - return new Identity({ did: parentDid }, context); - } - - /** - * @hidden - * since a child Identity doesn't has any other children, this method overrides the base implementation to return empty array - * - * @deprecated - */ - public override getChildIdentities(): Promise { - return Promise.resolve([]); - } - - /** - * Determine whether this child Identity exists - * - * @note asset Identities aren't considered to exist for this check - */ - public override async exists(): Promise { - const parentDid = await this.getParentDid(); - - return parentDid !== null; - } - - /** - * Unlinks this child identity from its parent - * - * @throws if - * - this identity doesn't have a parent - * - the transaction signer is not the primary key of the child identity - * - * @deprecated - */ - public unlinkFromParent: NoArgsProcedureMethod; -} diff --git a/src/api/entities/Identity/__tests__/ChildIdentity.ts b/src/api/entities/Identity/__tests__/ChildIdentity.ts deleted file mode 100644 index 88233c4cb0..0000000000 --- a/src/api/entities/Identity/__tests__/ChildIdentity.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { PolymeshPrimitivesIdentityId } from '@polkadot/types/lookup'; -import { when } from 'jest-when'; - -import { ChildIdentity, Context, Entity, PolymeshTransaction } from '~/internal'; -import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; -import { MockContext } from '~/testUtils/mocks/dataSources'; -import * as utilsConversionModule from '~/utils/conversion'; - -jest.mock( - '~/base/Procedure', - require('~/testUtils/mocks/procedure').mockProcedureModule('~/base/Procedure') -); - -describe('ChildIdentity class', () => { - let context: MockContext; - - let childIdentity: ChildIdentity; - let did: string; - - let stringToIdentityIdSpy: jest.SpyInstance; - let identityIdToStringSpy: jest.SpyInstance; - - beforeAll(() => { - dsMockUtils.initMocks(); - entityMockUtils.initMocks(); - procedureMockUtils.initMocks(); - - did = 'someDid'; - stringToIdentityIdSpy = jest.spyOn(utilsConversionModule, 'stringToIdentityId'); - identityIdToStringSpy = jest.spyOn(utilsConversionModule, 'identityIdToString'); - }); - - beforeEach(() => { - context = dsMockUtils.getContextInstance({ - isV7: true, - }); - childIdentity = new ChildIdentity({ did }, context); - }); - - afterEach(() => { - dsMockUtils.reset(); - entityMockUtils.reset(); - procedureMockUtils.reset(); - }); - - afterAll(() => { - dsMockUtils.cleanup(); - procedureMockUtils.reset(); - }); - - it('should extend Entity', () => { - expect(ChildIdentity.prototype).toBeInstanceOf(Entity); - }); - - describe('constructor', () => { - it('should assign did to instance', () => { - expect(childIdentity.did).toBe(did); - }); - }); - - describe('method: getParentDid', () => { - it('should parent identity for the current child identity instance', async () => { - const rawIdentity = dsMockUtils.createMockIdentityId(did); - when(stringToIdentityIdSpy).calledWith(did, context).mockReturnValue(rawIdentity); - - dsMockUtils.createQueryMock('identity', 'parentDid', { - returnValue: dsMockUtils.createMockOption(), - }); - - let result = await childIdentity.getParentDid(); - - expect(result).toBe(null); - - const parentDid = 'parentDid'; - - const rawParentDid = dsMockUtils.createMockIdentityId(parentDid); - when(identityIdToStringSpy).calledWith(rawParentDid).mockReturnValue(parentDid); - - dsMockUtils.createQueryMock('identity', 'parentDid', { - returnValue: dsMockUtils.createMockOption(rawParentDid), - }); - - result = await childIdentity.getParentDid(); - - expect(result?.did).toBe(parentDid); - }); - - it('should throw an error if the chain version is v8', async () => { - context.isV7 = false; - await expect( - childIdentity.getParentDid() // NOSONAR - ).rejects.toThrow('getParentDid is not supported in v8'); - }); - }); - - describe('method: getChildIdentities', () => { - it('should return an empty array', async () => { - await expect(childIdentity.getChildIdentities()).resolves.toEqual([]); - }); - }); - - describe('method: exists', () => { - it('should return whether the ChildIdentity exists', async () => { - const getParentDidSpy = jest.spyOn(childIdentity, 'getParentDid'); - - getParentDidSpy.mockResolvedValueOnce(null); - await expect(childIdentity.exists()).resolves.toBe(false); - - getParentDidSpy.mockResolvedValueOnce(entityMockUtils.getIdentityInstance()); - await expect(childIdentity.exists()).resolves.toBe(true); - }); - }); - - describe('method: unlinkFromParent', () => { - it('should prepare the procedure and return the resulting transaction', async () => { - const expectedTransaction = 'someTransaction' as unknown as PolymeshTransaction; - - when(procedureMockUtils.getPrepareMock()) - .calledWith({ args: { child: childIdentity }, transformer: undefined }, context, {}) - .mockResolvedValue(expectedTransaction); - - const transaction = await childIdentity.unlinkFromParent(); - - expect(transaction).toBe(expectedTransaction); - }); - }); -}); diff --git a/src/api/entities/Identity/__tests__/index.ts b/src/api/entities/Identity/__tests__/index.ts index 6308cab78a..86fb0e5de9 100644 --- a/src/api/entities/Identity/__tests__/index.ts +++ b/src/api/entities/Identity/__tests__/index.ts @@ -81,12 +81,6 @@ jest.mock( '~/api/entities/DefaultPortfolio' ) ); -jest.mock( - '~/api/entities/Identity/ChildIdentity', - require('~/testUtils/mocks/entities').mockChildIdentityModule( - '~/api/entities/Identity/ChildIdentity' - ) -); jest.mock( '~/api/entities/Instruction', require('~/testUtils/mocks/entities').mockInstructionModule('~/api/entities/Instruction') @@ -140,7 +134,7 @@ describe('Identity class', () => { }); it('should extend Entity', () => { - expect(Identity.prototype instanceof Entity).toBe(true); + expect(Identity.prototype).toBeInstanceOf(Entity); }); describe('constructor', () => { @@ -258,30 +252,6 @@ describe('Identity class', () => { expect(hasRole).toBe(false); }); - it('should check CDD Provider / DidRegistrar role against cddServiceProviders on v7', async () => { - const did = 'someDid'; - const mockContext = dsMockUtils.getContextInstance({ isV7: true }); - const identity = new Identity({ did }, mockContext); - const role: Role = { type: RoleType.DidRegistrar }; - const rawDid = dsMockUtils.createMockIdentityId(did); - - dsMockUtils - .createQueryMock('cddServiceProviders', 'activeMembers') - .mockResolvedValue([rawDid]); - - when(identityIdToStringSpy).calledWith(rawDid).mockReturnValue(did); - - let hasRole = await identity.hasRole(role); - - expect(hasRole).toBe(true); - - identity.did = 'otherDid'; - - hasRole = await identity.hasRole(role); - - expect(hasRole).toBe(false); - }); - it('should check whether the Identity has the Venue Owner role', async () => { const did = 'someDid'; const identity = new Identity({ did }, context); @@ -470,45 +440,6 @@ describe('Identity class', () => { }); }); - describe('method: hasValidCdd', () => { - it('should return whether the Identity has valid CDD', async () => { - const did = 'someDid'; - const statusResponse = true; - const mockContext = dsMockUtils.getContextInstance({ isV7: true }); - const rawIdentityId = dsMockUtils.createMockIdentityId(did); - const fakeHasValidCdd = dsMockUtils.createMockCddStatus({ - Ok: rawIdentityId, - }); - - when(stringToIdentityIdSpy).calledWith(did, mockContext).mockReturnValue(rawIdentityId); - - when(dsMockUtils.createCallMock('identityApi', 'isIdentityHasValidCdd')) - .calledWith(rawIdentityId, null) - .mockResolvedValue(fakeHasValidCdd); - - when(jest.spyOn(utilsConversionModule, 'cddStatusToBoolean')) - .calledWith(fakeHasValidCdd) - .mockReturnValue(statusResponse); - - const identity = new Identity({ did }, mockContext); - const result = await identity.hasValidCdd(); // NOSONAR - expect(result).toEqual(statusResponse); - }); - - it('should return whether the Identity exists if the chain version is v8', async () => { - const did = 'someDid'; - const mockContext = dsMockUtils.getContextInstance({ isV7: false }); - const identity = new Identity({ did }, mockContext); - - const existsSpy = jest.spyOn(identity, 'exists').mockResolvedValue(true); - - const result = await identity.hasValidCdd(); // NOSONAR - - expect(result).toBe(true); - expect(existsSpy).toHaveBeenCalled(); - }); - }); - describe('method: isGcMember', () => { it('should return whether the Identity is GC member', async () => { const did = 'someDid'; @@ -545,23 +476,6 @@ describe('Identity class', () => { expect(result).toBeTruthy(); }); - - it('should use cddServiceProviders.activeMembers when chain is v7', async () => { - const did = 'someDid'; - const rawDid = dsMockUtils.createMockIdentityId(did); - const mockContext = dsMockUtils.getContextInstance({ isV7: true }); - const identity = new Identity({ did }, mockContext); - - when(identityIdToStringSpy).calledWith(rawDid).mockReturnValue(did); - - dsMockUtils - .createQueryMock('cddServiceProviders', 'activeMembers') - .mockResolvedValue([rawDid, dsMockUtils.createMockIdentityId('otherDid')]); - - const result = await identity.isCddProvider(); - - expect(result).toBeTruthy(); - }); }); describe('method: getPrimaryAccount', () => { @@ -1418,95 +1332,6 @@ describe('Identity class', () => { }); }); - describe('method: getChildIdentities', () => { - it('should return the list of all child identities of which the given Identity is a parent', async () => { - const mockContext = dsMockUtils.getContextInstance({ - middlewareEnabled: true, - isV7: true, - }); - const identity = new Identity({ did: 'someDid' }, mockContext); - - const rawIdentity = dsMockUtils.createMockIdentityId(identity.did); - when(identityIdToStringSpy).calledWith(rawIdentity).mockReturnValue(identity.did); - - const children = ['someChild', 'someOtherChild']; - const rawChildren = children.map(child => dsMockUtils.createMockIdentityId(child)); - - when(identityIdToStringSpy).calledWith(rawChildren[0]!).mockReturnValue(children[0]!); - when(identityIdToStringSpy).calledWith(rawChildren[1]!).mockReturnValue(children[1]!); - - dsMockUtils.createQueryMock('identity', 'parentDid', { - entries: rawChildren.map(child => - tuple([child], dsMockUtils.createMockOption(rawIdentity)) - ), - }); - - const result = await identity.getChildIdentities(); - - expect(result).toEqual( - expect.arrayContaining([ - expect.objectContaining({ did: children[0] }), - expect.objectContaining({ did: children[1] }), - ]) - ); - }); - - it('should throw an error if the chain version is v8', async () => { - const mockContext = dsMockUtils.getContextInstance({ - isV7: false, - }); - const identity = new Identity({ did: 'someDid' }, mockContext); - - await expect( - identity.getChildIdentities() // NOSONAR - ).rejects.toThrow('getChildIdentities is not supported in v8'); - }); - }); - - describe('method: unlinkChild', () => { - it('should prepare the procedure and return the resulting transaction', async () => { - const expectedTransaction = 'someQueue' as unknown as PolymeshTransaction; - - const identity = new Identity({ did: 'someDid' }, context); - - const args = { - child: 'someChild', - }; - - when(procedureMockUtils.getPrepareMock()) - .calledWith({ args, transformer: undefined }, context, {}) - .mockResolvedValue(expectedTransaction); - - const transaction = await identity.unlinkChild(args); - - expect(transaction).toBe(expectedTransaction); - }); - }); - - describe('method: isChild', () => { - it('should return whether the Identity is a child Identity', async () => { - entityMockUtils.configureMocks({ - childIdentityOptions: { - exists: true, - }, - }); - const identity = new Identity({ did: 'someDid' }, context); - let result = await identity.isChild(); - - expect(result).toBeTruthy(); - - entityMockUtils.configureMocks({ - childIdentityOptions: { - exists: false, - }, - }); - - result = await identity.isChild(); - - expect(result).toBeFalsy(); - }); - }); - describe('method: preApprovedAssets', () => { it('should the list of pre-approved assets for the identity', async () => { const did = 'someDid'; diff --git a/src/api/entities/Identity/index.ts b/src/api/entities/Identity/index.ts index 629f4b151b..e571273fa0 100644 --- a/src/api/entities/Identity/index.ts +++ b/src/api/entities/Identity/index.ts @@ -5,17 +5,15 @@ import { PolymeshPrimitivesIdentityId, } from '@polkadot/types/lookup'; import BigNumber from 'bignumber.js'; -import { chunk, differenceWith, flatten, intersectionWith, uniqBy } from 'lodash'; +import { chunk, differenceWith, intersectionWith, uniqBy } from 'lodash'; import { AssetPermissions } from '~/api/entities/Identity/AssetPermissions'; import { IdentityAuthorizations } from '~/api/entities/Identity/IdentityAuthorizations'; import { Portfolios } from '~/api/entities/Identity/Portfolios'; -import { unlinkChildIdentity } from '~/api/procedures/unlinkChildIdentity'; import { assertAssetHolderExists } from '~/api/procedures/utils'; import { Account, BaseAsset, - ChildIdentity, Context, Entity, FungibleAsset, @@ -53,12 +51,10 @@ import { ResultSet, Role, SubCallback, - UnlinkChildParams, UnsubCallback, } from '~/types'; import { Ensured, tuple } from '~/types/utils'; import { - isCddProviderRole, isDidRegistrarRole, isIdentityRole, isPortfolioCustodianRole, @@ -74,7 +70,6 @@ import { assetToMeshAssetId, balanceToBigNumber, boolToBoolean, - cddStatusToBoolean, corporateActionIdentifierToCaId, identityIdToString, middlewareInstructionToHistoricInstruction, @@ -141,13 +136,6 @@ export class Identity extends Entity { this.portfolios = new Portfolios(this, context); this.assetPermissions = new AssetPermissions(this, context); - this.unlinkChild = createProcedureMethod( - { - getProcedureAndArgs: args => [unlinkChildIdentity, args], - }, - context - ); - this.setMandatoryReceiverAffirmation = createProcedureMethod( { getProcedureAndArgs: args => [setMandatoryReceiverAffirmation, { ...args, did: this.did }], @@ -169,17 +157,13 @@ export class Identity extends Entity { const { owner } = await reservation.details(); return owner ? this.isEqual(owner) : false; - } else if (isCddProviderRole(role) || isDidRegistrarRole(role)) { + } else if (isDidRegistrarRole(role)) { const { polymeshApi: { query }, } = context; - const activeMembersStorage = context.isV7 - ? // eslint-disable-next-line @typescript-eslint/no-explicit-any - (query as any).cddServiceProviders.activeMembers - : query.didRegistrars.activeMembers; - - const rawMembers: Vec = await activeMembersStorage(); + const rawMembers: Vec = + await query.didRegistrars.activeMembers(); const memberDids = rawMembers.map(identityIdToString); return memberDids.includes(did); @@ -296,30 +280,6 @@ export class Identity extends Entity { return balanceToBigNumber(balance); } - /** - * Check whether this Identity has a valid CDD claim - * - * @deprecated CDD claims are discontinued from chain v8. If invoked with a v8 chain, this returns true if DID exists - */ - public async hasValidCdd(): Promise { - const { - context, - did, - context: { - polymeshApi: { call }, - }, - } = this; - const identityId = stringToIdentityId(did, context); - - if (!context.isV7) { - return this.exists(); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const result = await (call.identityApi as any).isIdentityHasValidCdd(identityId, null); - return cddStatusToBoolean(result); - } - /** * Check whether this Identity is Governance Committee member */ @@ -345,16 +305,10 @@ export class Identity extends Entity { context: { polymeshApi: { query }, }, - context, did, } = this; - const activeMembersStorage = context.isV7 - ? // eslint-disable-next-line @typescript-eslint/no-explicit-any - (query as any).cddServiceProviders.activeMembers - : query.didRegistrars.activeMembers; - - const activeMembers = await activeMembersStorage(); + const activeMembers = await query.didRegistrars.activeMembers(); return activeMembers.map(identityIdToString).includes(did); } @@ -695,7 +649,7 @@ export class Identity extends Entity { ); const uniqueEntries = uniqBy( - flatten(auths).map(([key, status]) => ({ id: key.args[1], status })), + auths.flat().map(([key, status]) => ({ id: key.args[1], status })), ({ id, status }) => `${id.toString()}-${status.type}` ); @@ -1072,65 +1026,6 @@ export class Identity extends Entity { }; } - /** - * Returns the list of all child identities - * - * @note this query can be potentially **SLOW** depending on the number of parent Identities present on the chain - * - * @deprecated Child identites are no longer supported in chain v8 - */ - public async getChildIdentities(): Promise { - const { - context: { - polymeshApi: { - query: { identity }, - }, - }, - context, - did, - } = this; - - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'getChildIdentities is not supported in v8', - }); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const rawEntries: any[] = await (identity as any).parentDid.entries(); - - return rawEntries - .filter(([, rawParentDid]) => identityIdToString(rawParentDid.unwrapOrDefault()) === did) - .map( - ([ - { - args: [rawChildDid], - }, - ]) => new ChildIdentity({ did: identityIdToString(rawChildDid) }, context) - ); - } - - /** - * Unlinks a child identity - * - * @throws if - * - the `child` is not a child of this identity - * - the transaction signer is not the primary key of the parent identity - */ - public unlinkChild: ProcedureMethod; - - /** - * Check whether this Identity is a child Identity - */ - public isChild(): Promise { - const { did, context } = this; - - const childIdentity = new ChildIdentity({ did }, context); - - return childIdentity.exists(); - } - /** * Returns a list of all assets this Identity has pre-approved. These assets will not require affirmation when being received in settlements */ diff --git a/src/api/entities/Instruction/__tests__/index.ts b/src/api/entities/Instruction/__tests__/index.ts index 520df068c6..b42e31a785 100644 --- a/src/api/entities/Instruction/__tests__/index.ts +++ b/src/api/entities/Instruction/__tests__/index.ts @@ -107,7 +107,7 @@ describe('Instruction class', () => { }); it('should extend Entity', () => { - expect(Instruction.prototype instanceof Entity).toBe(true); + expect(Instruction.prototype).toBeInstanceOf(Entity); }); describe('method: isUniqueIdentifiers', () => { @@ -1489,31 +1489,6 @@ describe('Instruction class', () => { }); }); - describe('method: withdraw', () => { - afterAll(() => { - jest.restoreAllMocks(); - }); - - it('should prepare the procedure and return the resulting transaction', async () => { - const expectedTransaction = 'someTransaction' as unknown as PolymeshTransaction; - - when(procedureMockUtils.getPrepareMock()) - .calledWith( - { - args: { id, operation: InstructionAffirmationOperation.Withdraw }, - transformer: undefined, - }, - context, - {} - ) - .mockResolvedValue(expectedTransaction); - - const tx = await instruction.withdraw(); - - expect(tx).toBe(expectedTransaction); - }); - }); - describe('method: lockForExecution', () => { afterAll(() => { jest.restoreAllMocks(); @@ -1589,31 +1564,6 @@ describe('Instruction class', () => { }); }); - describe('method: withdrawAsMediator', () => { - afterAll(() => { - jest.restoreAllMocks(); - }); - - it('should prepare the procedure and return the resulting transaction', async () => { - const expectedTransaction = 'someTransaction' as unknown as PolymeshTransaction; - - when(procedureMockUtils.getPrepareMock()) - .calledWith( - { - args: { id, operation: InstructionAffirmationOperation.WithdrawAsMediator }, - transformer: undefined, - }, - context, - {} - ) - .mockResolvedValue(expectedTransaction); - - const tx = await instruction.withdrawAsMediator(); - - expect(tx).toBe(expectedTransaction); - }); - }); - describe('method: executeManually', () => { afterAll(() => { jest.restoreAllMocks(); @@ -2808,7 +2758,6 @@ describe('Instruction class', () => { signer, }); }); - it('should throw an error if expiresAt is not provided and chain is v8', () => { return expect( instruction.generateOffChainAffirmationReceipt({ @@ -2817,58 +2766,5 @@ describe('Instruction class', () => { }) ).rejects.toThrow('`expiresAt` is mandatory from chain 8.x'); }); - - it('should return the affirmation receipt for offchain leg on v7 chain', async () => { - const v7Context = dsMockUtils.getContextInstance({ - isV7: true, - }); - const v7Instruction = new Instruction({ id }, v7Context); - when(bigNumberToU64Spy).calledWith(id, v7Context).mockReturnValue(rawId); - when(bigNumberToU64Spy).calledWith(uid, v7Context).mockReturnValue(rawUid); - when(bigNumberToU64Spy).calledWith(legId, v7Context).mockReturnValue(rawLegId); - - const senderIdentity = 'senderDid'; - const rawSenderIdentity = dsMockUtils.createMockIdentityId(senderIdentity); - const receiverIdentity = 'receiverDid'; - const rawReceiverIdentity = dsMockUtils.createMockIdentityId(receiverIdentity); - - const ticker = 'ABCDEF'; - const rawTicker = dsMockUtils.createMockTicker(ticker); - rawTicker.toHex = jest.fn().mockReturnValue('0xABCDEF0000'); - - const amount = new BigNumber(10); - const rawAmount = dsMockUtils.createMockU128(amount.shiftedBy(6)); - - dsMockUtils.createQueryMock('settlement', 'instructionLegs', { - returnValue: dsMockUtils.createMockOption( - dsMockUtils.createMockInstructionLeg({ - OffChain: { - senderIdentity: rawSenderIdentity, - receiverIdentity: rawReceiverIdentity, - amount: rawAmount, - ticker: rawTicker, - }, - }) - ), - }); - - const result = await v7Instruction.generateOffChainAffirmationReceipt({ - legId, - uid, - }); - - expect(result).toEqual({ - uid, - legId, - signer: expect.objectContaining({ - address: '0xdummy', - }), - signature: { - type: SignerKeyRingType.Sr25519, - value: '0xsignature', - }, - metadata: undefined, - }); - }); }); }); diff --git a/src/api/entities/Instruction/index.ts b/src/api/entities/Instruction/index.ts index 4fa34b58e9..743a45241c 100644 --- a/src/api/entities/Instruction/index.ts +++ b/src/api/entities/Instruction/index.ts @@ -64,7 +64,6 @@ import { SignerKeyRingType, SubCallback, UnsubCallback, - WithdrawInstructionParams, } from '~/types'; import { InstructionStatus as InternalInstructionStatus } from '~/types/internal'; import { Ensured } from '~/types/utils'; @@ -157,21 +156,6 @@ export class Instruction extends Entity { context ); - this.withdraw = createProcedureMethod( - { - getProcedureAndArgs: args => [ - modifyInstructionAffirmation, - { - id, - operation: InstructionAffirmationOperation.Withdraw, // NOSONAR - ...args, - }, - ], - optionalArgs: true, - }, - context - ); - this.rejectAsMediator = createProcedureMethod( { getProcedureAndArgs: () => [ @@ -194,17 +178,6 @@ export class Instruction extends Entity { context ); - this.withdrawAsMediator = createProcedureMethod( - { - getProcedureAndArgs: () => [ - modifyInstructionAffirmation, - { id, operation: InstructionAffirmationOperation.WithdrawAsMediator }, - ], - voidArgs: true, - }, - context - ); - this.executeManually = createProcedureMethod( { getProcedureAndArgs: args => [executeManualInstruction, { id, ...args }], @@ -909,13 +882,6 @@ export class Instruction extends Entity { */ public affirm: OptionalArgsProcedureMethod; - /** - * Withdraw affirmation from this instruction (unauthorize) - * - * @deprecated Withdrawing affirmation is no longer supported in chain v8. If you need to revoke the affirmation, you can do that by using `reject` method. - */ - public withdraw: OptionalArgsProcedureMethod; - /** * Reject this instruction as a mediator * @@ -930,13 +896,6 @@ export class Instruction extends Entity { */ public affirmAsMediator: OptionalArgsProcedureMethod; - /** - * Withdraw affirmation from this instruction as a mediator (unauthorize) - * - * @deprecated Withdrawing affirmation is no longer supported in chain v8. If you need to revoke the affirmation, you can do that by using `rejectAsMediator` method. - */ - public withdrawAsMediator: NoArgsProcedureMethod; - /** * Executes an Instruction either of type `SettleManual` or a `Failed` instruction */ @@ -1313,7 +1272,7 @@ export class Instruction extends Entity { expiresAt, } = args; - if (!expiresAt && !context.isV7) { + if (!expiresAt) { throw new PolymeshError({ code: ErrorCode.UnmetPrerequisite, message: '`expiresAt` is mandatory from chain 8.x', @@ -1345,35 +1304,19 @@ export class Instruction extends Entity { const rawUid = bigNumberToU64(uid, context); - let payloadStrings: string[]; - - if (context.isV7) { - payloadStrings = [ - stringToHex(''), - rawUid.toHex(true), - rawId.toHex(true), - rawLegId.toHex(true), - senderIdentity.toHex(), - receiverIdentity.toHex(), - ticker.toHex(), - amount.toHex(true), - stringToHex(''), - ]; - } else { - payloadStrings = [ - stringToHex(''), - rawUid.toHex(true), - stringToHex('Polymesh Settlement Receipt'), - dateToMoment(expiresAt!, context).toHex(), - rawId.toHex(true), - rawLegId.toHex(true), - senderIdentity.toHex(), - receiverIdentity.toHex(), - ticker.toHex(), - amount.toHex(true), - stringToHex(''), - ]; - } + const payloadStrings: string[] = [ + stringToHex(''), + rawUid.toHex(true), + stringToHex('Polymesh Settlement Receipt'), + dateToMoment(expiresAt, context).toHex(), + rawId.toHex(true), + rawLegId.toHex(true), + senderIdentity.toHex(), + receiverIdentity.toHex(), + ticker.toHex(), + amount.toHex(true), + stringToHex(''), + ]; const rawPayload = hexAddPrefix(payloadStrings.map(e => hexStripPrefix(e)).join('')); diff --git a/src/api/entities/Portfolio/__tests__/index.ts b/src/api/entities/Portfolio/__tests__/index.ts index 6052f08862..a831384895 100644 --- a/src/api/entities/Portfolio/__tests__/index.ts +++ b/src/api/entities/Portfolio/__tests__/index.ts @@ -286,7 +286,7 @@ describe('Portfolio class', () => { assets: [hexToUuid(assetId0), new FungibleAsset({ assetId: otherAssetId }, context)], }); - expect(result.length).toBe(2); + expect(result).toHaveLength(2); expect(result[0]!.asset.id).toBe(hexToUuid(assetId0)); expect(result[0]!.total).toEqual(total0); expect(result[0]!.locked).toEqual(locked0); @@ -358,14 +358,14 @@ describe('Portfolio class', () => { }); beforeEach(() => { - dsMockUtils.configureMocks({ contextOptions: { did, isV7: true } }); + dsMockUtils.configureMocks({ contextOptions: { did } }); dsMockUtils.createQueryMock('portfolio', 'portfolioNFT', { entries: [ - tuple([rawPortfolioId, [rawAssetId, rawNftId]], rawTrue), - tuple([rawPortfolioId, [rawAssetId, rawSecondId]], rawTrue), - tuple([rawPortfolioId, [rawAssetId, rawLockedId]], rawTrue), - tuple([rawPortfolioId, [rawHeldOnlyAssetId, rawHeldOnlyId]], rawTrue), - tuple([rawPortfolioId, [rawLockedOnlyAssetId, rawLockedOnlyId]], rawTrue), + tuple([rawPortfolioId, rawAssetId, rawNftId], rawTrue), + tuple([rawPortfolioId, rawAssetId, rawSecondId], rawTrue), + tuple([rawPortfolioId, rawAssetId, rawLockedId], rawTrue), + tuple([rawPortfolioId, rawHeldOnlyAssetId, rawHeldOnlyId], rawTrue), + tuple([rawPortfolioId, rawLockedOnlyAssetId, rawLockedOnlyId], rawTrue), ], }); dsMockUtils.createQueryMock('portfolio', 'portfolioLockedNFT', { @@ -419,44 +419,7 @@ describe('Portfolio class', () => { const result = await portfolio.getCollections({ collections: [hexToUuid(assetId)] }); - expect(result.length).toEqual(1); - - expect(result).toEqual( - expect.arrayContaining([ - { - collection: expect.objectContaining({ id: hexToUuid(assetId) }), - free: expect.arrayContaining([ - expect.objectContaining({ id: nftId }), - expect.objectContaining({ id: secondNftId }), - ]), - locked: expect.arrayContaining([expect.objectContaining({ id: lockedNftId })]), - total: new BigNumber(3), - }, - ]) - ); - }); - - it("should return all of the portfolio's NFTs when no args are given on a v8 chain", async () => { - const v8Context = dsMockUtils.getContextInstance({ did, isV7: false }); - const portfolio = new NonAbstract({ did, id: portfolioId }, v8Context); - - dsMockUtils.createQueryMock('portfolio', 'portfolioNFT', { - entries: [ - tuple([rawPortfolioId, rawAssetId, rawNftId], rawTrue), - tuple([rawPortfolioId, rawAssetId, rawSecondId], rawTrue), - tuple([rawPortfolioId, rawAssetId, rawLockedId], rawTrue), - tuple([rawPortfolioId, rawHeldOnlyAssetId, rawHeldOnlyId], rawTrue), - tuple([rawPortfolioId, rawLockedOnlyAssetId, rawLockedOnlyId], rawTrue), - ], - }); - dsMockUtils.createQueryMock('portfolio', 'portfolioLockedNFT', { - entries: [ - tuple([rawPortfolioId, [rawAssetId, rawLockedId]], rawTrue), - tuple([rawPortfolioId, [rawLockedOnlyAssetId, rawLockedOnlyId]], rawTrue), - ], - }); - - const result = await portfolio.getCollections(); + expect(result).toHaveLength(1); expect(result).toEqual( expect.arrayContaining([ @@ -469,18 +432,6 @@ describe('Portfolio class', () => { locked: expect.arrayContaining([expect.objectContaining({ id: lockedNftId })]), total: new BigNumber(3), }, - expect.objectContaining({ - collection: expect.objectContaining({ id: hexToUuid(heldOnlyAssetId) }), - free: expect.arrayContaining([expect.objectContaining({ id: heldOnlyNftId })]), - locked: [], - total: new BigNumber(1), - }), - expect.objectContaining({ - collection: expect.objectContaining({ id: hexToUuid(lockedOnlyAssetId) }), - free: [], - locked: expect.arrayContaining([expect.objectContaining({ id: lockedOnlyNftId })]), - total: new BigNumber(1), - }), ]) ); }); diff --git a/src/api/entities/Portfolio/index.ts b/src/api/entities/Portfolio/index.ts index f7974af55d..62af5c18b1 100644 --- a/src/api/entities/Portfolio/index.ts +++ b/src/api/entities/Portfolio/index.ts @@ -4,7 +4,6 @@ import { PolymeshPrimitivesIdentityIdPortfolioId, } from '@polkadot/types/lookup'; import BigNumber from 'bignumber.js'; -import { values } from 'lodash'; import { HistoricSettlement, @@ -206,7 +205,7 @@ export abstract class Portfolio extends Entity return filteredBalances; } - return values(assetBalances); + return Object.values(assetBalances); } /** @@ -230,9 +229,8 @@ export abstract class Portfolio extends Entity const rawPortfolioId = portfolioIdToMeshPortfolioId({ did, number: portfolioId }, context); - // clean up v7 support - in v7 portfolioNFT uses key [portfolioId, [assetId, nftId]]; - // v8 changed it to [portfolioId, assetId, nftId]. Cast required to query with a single arg - // as Polkadot defaults to N-1 args. + // portfolioNFT uses key [portfolioId, assetId, nftId]. Cast required to query with a single + // arg as Polkadot defaults to N-1 args. const [exists, heldCollectionEntries, lockedCollectionEntries] = await Promise.all([ this.exists(), ( @@ -276,10 +274,7 @@ export abstract class Portfolio extends Entity }; for (const [{ args: entryArgs }] of heldCollectionEntries) { - // clean up v7 support - v7 key: [portfolioId, [assetId, nftId]], v8 key: [portfolioId, assetId, nftId] - const [rawAssetId, rawNftId] = context.isV7 - ? (entryArgs as unknown as [unknown, [PolymeshPrimitivesAssetAssetId, u64]])[1] - : [entryArgs[1], entryArgs[2]]; + const [, rawAssetId, rawNftId] = entryArgs; addNft(heldCollections, assetIdToString(rawAssetId), u64ToBigNumber(rawNftId)); } diff --git a/src/api/entities/Subsidies.ts b/src/api/entities/Subsidies.ts index 0dbad296de..fda269a3c0 100644 --- a/src/api/entities/Subsidies.ts +++ b/src/api/entities/Subsidies.ts @@ -1,5 +1,5 @@ -import { Account, Namespace, PolymeshError, Subsidy } from '~/internal'; -import { ErrorCode, SubCallback, SubsidyWithAllowance, UnsubCallback } from '~/types'; +import { Account, Namespace, Subsidy } from '~/internal'; +import { SubCallback, SubsidyWithAllowance, UnsubCallback } from '~/types'; import { accountIdToString, balanceToBigNumber, stringToAccountId } from '~/utils/conversion'; /** @@ -88,19 +88,10 @@ export class Subsidies extends Namespace { /** * Get pending subsidies (for which this Account is the beneficiary) that have been authorised but not yet accepted. - * - * @note this method is supported only with v8 chains */ public getPendingSubsidies(): Promise { const { context } = this; - if (context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'This method is only supported in chain v8', - }); - } - return context.getPendingSubsidies(); } } diff --git a/src/api/entities/__tests__/AuthorizationRequest.ts b/src/api/entities/__tests__/AuthorizationRequest.ts index d39681cc16..3ee9bc3dd3 100644 --- a/src/api/entities/__tests__/AuthorizationRequest.ts +++ b/src/api/entities/__tests__/AuthorizationRequest.ts @@ -45,7 +45,7 @@ describe('AuthorizationRequest class', () => { }); it('should extend Entity', () => { - expect(AuthorizationRequest.prototype instanceof Entity).toBe(true); + expect(AuthorizationRequest.prototype).toBeInstanceOf(Entity); }); describe('constructor', () => { @@ -212,7 +212,7 @@ describe('AuthorizationRequest class', () => { expect(tx).toBe(expectedTransaction); }); - it('should prepare the consumeAddRelayerPayingKeyAuthorization procedure with the correct arguments and context, and return the resulting transaction', async () => { + it('should throw an error when accepting an OldAddRelayerPayingKey Authorization Request', () => { const authorizationRequest = new AuthorizationRequest( { authId: new BigNumber(1), @@ -220,7 +220,7 @@ describe('AuthorizationRequest class', () => { target: new Identity({ did: 'someDid' }, context), issuer: new Identity({ did: 'otherDid' }, context), data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: { beneficiary: new Account({ address: 'beneficiary' }, context), subsidizer: new Account({ address: 'subsidizer' }, context), @@ -231,20 +231,9 @@ describe('AuthorizationRequest class', () => { context ); - const args = { - authRequest: authorizationRequest, - accept: true, - }; - - const expectedTransaction = 'someTransaction' as unknown as PolymeshTransaction; - - when(procedureMockUtils.getPrepareMock()) - .calledWith({ args, transformer: undefined }, context, {}) - .mockResolvedValue(expectedTransaction); - - const tx = await authorizationRequest.accept(); - - expect(tx).toBe(expectedTransaction); + expect(() => authorizationRequest.accept()).toThrow( + 'Accepting this type of Authorization Request is no longer supported. Use AccountManagement.approveSubsidy instead' + ); }); }); @@ -384,7 +373,7 @@ describe('AuthorizationRequest class', () => { expect(tx).toBe(expectedTransaction); }); - it('should prepare the consumeAddRelayerPayingKeyAuthorization procedure with the correct arguments and context, and return the resulting transaction', async () => { + it('should prepare the consumeAuthorizationRequests procedure with an OldAddRelayerPayingKey auth and return the resulting transaction', async () => { const authorizationRequest = new AuthorizationRequest( { authId: new BigNumber(1), @@ -392,7 +381,7 @@ describe('AuthorizationRequest class', () => { target: new Identity({ did: 'someDid' }, context), issuer: new Identity({ did: 'otherDid' }, context), data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: { beneficiary: new Account({ address: 'beneficiary' }, context), subsidizer: new Account({ address: 'subsidizer' }, context), @@ -404,8 +393,8 @@ describe('AuthorizationRequest class', () => { ); const args = { - authRequest: authorizationRequest, accept: false, + authRequests: [authorizationRequest], }; const expectedTransaction = 'someTransaction' as unknown as PolymeshTransaction; diff --git a/src/api/entities/__tests__/Subsidies.ts b/src/api/entities/__tests__/Subsidies.ts index e9cf6489ab..db51852fec 100644 --- a/src/api/entities/__tests__/Subsidies.ts +++ b/src/api/entities/__tests__/Subsidies.ts @@ -156,13 +156,5 @@ describe('Subsidies Class', () => { expect(result).toEqual(fakeResult); }); - - it('should throw error for v7 chain', () => { - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); - - expect(() => subsidies.getPendingSubsidies()).toThrow( - 'This method is only supported in chain v8' - ); - }); }); }); diff --git a/src/api/entities/common/namespaces/Authorizations.ts b/src/api/entities/common/namespaces/Authorizations.ts index 3f42a82d2f..8d94e27c19 100644 --- a/src/api/entities/common/namespaces/Authorizations.ts +++ b/src/api/entities/common/namespaces/Authorizations.ts @@ -60,15 +60,6 @@ export class Authorizations extends Namespace { let result: Vec; if (opts?.type) { - if (context.isV7 && opts.type === AuthorizationType.OldAddRelayerPayingKey) { - opts.type = AuthorizationType.AddRelayerPayingKey; // NOSONAR - } - if ( - !context.isV7 && - opts.type === AuthorizationType.AddRelayerPayingKey // NOSONAR - ) { - opts.type = AuthorizationType.OldAddRelayerPayingKey; - } result = await identityApi.getFilteredAuthorizations( signatory, rawBoolean, diff --git a/src/api/entities/common/namespaces/__tests__/Authorizations.ts b/src/api/entities/common/namespaces/__tests__/Authorizations.ts index 5bb233b00e..21c8c9aa0a 100644 --- a/src/api/entities/common/namespaces/__tests__/Authorizations.ts +++ b/src/api/entities/common/namespaces/__tests__/Authorizations.ts @@ -43,7 +43,7 @@ describe('Authorizations class', () => { }); it('should extend namespace', () => { - expect(Authorizations.prototype instanceof Namespace).toBe(true); + expect(Authorizations.prototype).toBeInstanceOf(Namespace); }); describe('method: getReceived', () => { @@ -152,9 +152,9 @@ describe('Authorizations class', () => { expect(JSON.stringify(result)).toBe(JSON.stringify(expectedAuthorizations)); }); - it('should map AddRelayerPayingKey to OldAddRelayerPayingKey', async () => { + it('should fetch authorizations of the OldAddRelayerPayingKey type', async () => { const did = 'someDid'; - const context = dsMockUtils.getContextInstance({ did, isV7: false }); + const context = dsMockUtils.getContextInstance({ did }); const identity = entityMockUtils.getIdentityInstance({ did }); const authsNamespace = new Authorizations(identity, context); const rawSignatory = dsMockUtils.createMockSignatory(); @@ -170,48 +170,16 @@ describe('Authorizations class', () => { dsMockUtils.createCallMock('identityApi', 'getFilteredAuthorizations').mockResolvedValue([]); - await authsNamespace.getReceived({ - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - }); - - expect(authorizationTypeToMeshAuthorizationTypeSpy).toHaveBeenCalledWith( - AuthorizationType.OldAddRelayerPayingKey, - context - ); - }); - - it('should map OldAddRelayerPayingKey to AddRelayerPayingKey on v7 chain', async () => { - const did = 'someDid'; - const context = dsMockUtils.getContextInstance({ did, isV7: true }); - const identity = entityMockUtils.getIdentityInstance({ did }); - const authsNamespace = new Authorizations(identity, context); - const rawSignatory = dsMockUtils.createMockSignatory(); - const rawAuthorizationType = dsMockUtils.createMockAuthorizationType(); - - when(signerValueToSignatorySpy).mockReturnValue(rawSignatory); - when(booleanToBoolSpy) - .calledWith(true, context) - .mockReturnValue(dsMockUtils.createMockBool(true)); - when(authorizationTypeToMeshAuthorizationTypeSpy) - .calledWith( - AuthorizationType.AddRelayerPayingKey, // NOSONAR - context - ) - .mockReturnValue(rawAuthorizationType); - - dsMockUtils.createCallMock('identityApi', 'getFilteredAuthorizations').mockResolvedValue([]); - await authsNamespace.getReceived({ type: AuthorizationType.OldAddRelayerPayingKey, }); expect(authorizationTypeToMeshAuthorizationTypeSpy).toHaveBeenCalledWith( - AuthorizationType.AddRelayerPayingKey, // NOSONAR + AuthorizationType.OldAddRelayerPayingKey, context ); }); }); - describe('method: getOne', () => { afterAll(() => { jest.restoreAllMocks(); diff --git a/src/api/entities/types.ts b/src/api/entities/types.ts index 5c30999862..a22e7e091b 100644 --- a/src/api/entities/types.ts +++ b/src/api/entities/types.ts @@ -7,7 +7,6 @@ import { BaseAsset, Checkpoint as CheckpointClass, CheckpointSchedule as CheckpointScheduleClass, - ChildIdentity as ChildIdentityClass, CorporateAction as CorporateActionClass, CorporateBallot, CustomPermissionGroup as CustomPermissionGroupClass, @@ -56,7 +55,6 @@ export type DefaultPortfolio = DefaultPortfolioClass; export type DefaultTrustedClaimIssuer = DefaultTrustedClaimIssuerClass; export type DividendDistribution = DividendDistributionClass; export type Identity = IdentityClass; -export type ChildIdentity = ChildIdentityClass; export type Instruction = InstructionClass; export type KnownPermissionGroup = KnownPermissionGroupClass; export type NumberedPortfolio = NumberedPortfolioClass; @@ -139,10 +137,6 @@ export enum AuthorizationType { JoinIdentity = 'JoinIdentity', PortfolioCustody = 'PortfolioCustody', BecomeAgent = 'BecomeAgent', - /** - * @deprecated in favour of OldRelayerPayingKey - */ - AddRelayerPayingKey = 'AddRelayerPayingKey', OldAddRelayerPayingKey = 'OldAddRelayerPayingKey', RotatePrimaryKeyToSecondary = 'RotatePrimaryKeyToSecondary', } @@ -477,14 +471,6 @@ export type BecomeAgentAuthorizationData = { value: KnownPermissionGroup | CustomPermissionGroup; }; -/** - * @deprecated in favour of OldAddRelayerPayingKeyAuthorizationData - */ -export type AddRelayerPayingKeyAuthorizationData = { - type: AuthorizationType.AddRelayerPayingKey; - value: SubsidyData; -}; - export type OldAddRelayerPayingKeyAuthorizationData = { type: AuthorizationType.OldAddRelayerPayingKey; value: SubsidyData; @@ -497,7 +483,6 @@ export type GenericAuthorizationData = { | AuthorizationType.JoinIdentity | AuthorizationType.PortfolioCustody | AuthorizationType.BecomeAgent - | AuthorizationType.AddRelayerPayingKey | AuthorizationType.OldAddRelayerPayingKey | AuthorizationType.RotatePrimaryKeyToSecondary | AuthorizationType.AttestPrimaryKeyRotation @@ -513,7 +498,6 @@ export type Authorization = | JoinIdentityAuthorizationData | PortfolioCustodyAuthorizationData | BecomeAgentAuthorizationData - | AddRelayerPayingKeyAuthorizationData | OldAddRelayerPayingKeyAuthorizationData | RotatePrimaryKeyToSecondaryData | GenericAuthorizationData; diff --git a/src/api/procedures/__tests__/acceptPrimaryKeyRotation.ts b/src/api/procedures/__tests__/acceptPrimaryKeyRotation.ts index 4f72240c30..7b4c654348 100644 --- a/src/api/procedures/__tests__/acceptPrimaryKeyRotation.ts +++ b/src/api/procedures/__tests__/acceptPrimaryKeyRotation.ts @@ -9,10 +9,10 @@ import { Storage, } from '~/api/procedures/acceptPrimaryKeyRotation'; import * as procedureUtilsModule from '~/api/procedures/utils'; -import { AuthorizationRequest, Context, PolymeshError } from '~/internal'; +import { AuthorizationRequest, Context } from '~/internal'; import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; import { Mocked } from '~/testUtils/types'; -import { AcceptPrimaryKeyRotationParams, Account, AuthorizationType, ErrorCode } from '~/types'; +import { AcceptPrimaryKeyRotationParams, Account, AuthorizationType } from '~/types'; import * as utilsConversionModule from '~/utils/conversion'; describe('acceptPrimaryKeyRotation procedure', () => { @@ -20,10 +20,7 @@ describe('acceptPrimaryKeyRotation procedure', () => { let bigNumberToU64Spy: jest.SpyInstance; let ownerAuthId: BigNumber; let rawOwnerAuthId: u64; - let cddAuthId: BigNumber; - let rawCddAuthId: u64; let ownerAuthRequest: AuthorizationRequest; - let cddAuthRequest: AuthorizationRequest; let targetAddress: string; let targetAccount: Account; let getOneMock: jest.Mock; @@ -44,16 +41,12 @@ describe('acceptPrimaryKeyRotation procedure', () => { ownerAuthId = new BigNumber(1); rawOwnerAuthId = dsMockUtils.createMockU64(ownerAuthId); - cddAuthId = new BigNumber(2); - rawCddAuthId = dsMockUtils.createMockU64(cddAuthId); - getOneMock = jest.fn(); }); beforeEach(() => { - mockContext = dsMockUtils.getContextInstance({ isV7: true }); + mockContext = dsMockUtils.getContextInstance(); when(bigNumberToU64Spy).calledWith(ownerAuthId, mockContext).mockReturnValue(rawOwnerAuthId); - when(bigNumberToU64Spy).calledWith(cddAuthId, mockContext).mockReturnValue(rawCddAuthId); mockContext.getSigningAccount().authorizations.getOne = getOneMock; targetAccount = entityMockUtils.getAccountInstance({ address: targetAddress, @@ -64,11 +57,6 @@ describe('acceptPrimaryKeyRotation procedure', () => { authId: ownerAuthId, target: targetAccount, }); - cddAuthRequest = entityMockUtils.getAuthorizationRequestInstance({ - authId: cddAuthId, - issuer: entityMockUtils.getIdentityInstance(), - target: targetAccount, - }); }); afterEach(() => { @@ -82,57 +70,14 @@ describe('acceptPrimaryKeyRotation procedure', () => { dsMockUtils.cleanup(); }); - it('should return an acceptPrimaryKey transaction spec for v7 chain', async () => { - const transaction = dsMockUtils.createTxMock('identity', 'acceptPrimaryKey'); - - let proc = procedureMockUtils.getInstance( - mockContext, - { - calledByTarget: true, - ownerAuthRequest, - cddAuthRequest: undefined, - } - ); - - let result = await prepareAcceptPrimaryKeyRotation.call(proc); - - expect(result).toEqual({ - transaction, - paidForBy: ownerAuthRequest.issuer, - args: [rawOwnerAuthId, null], - resolver: undefined, - }); - - proc = procedureMockUtils.getInstance( - mockContext, - { - calledByTarget: true, - ownerAuthRequest, - cddAuthRequest, - } - ); - - result = await prepareAcceptPrimaryKeyRotation.call(proc); - - expect(result).toEqual({ - transaction, - paidForBy: ownerAuthRequest.issuer, - args: [rawOwnerAuthId, rawCddAuthId], - resolver: undefined, - }); - }); - it('should return an acceptPrimaryKey transaction spec', async () => { const transaction = dsMockUtils.createTxMock('identity', 'acceptPrimaryKey'); - const v8MockContext = dsMockUtils.getContextInstance({ isV7: false }); - when(bigNumberToU64Spy).calledWith(ownerAuthId, v8MockContext).mockReturnValue(rawOwnerAuthId); const proc = procedureMockUtils.getInstance( - v8MockContext, + mockContext, { calledByTarget: true, ownerAuthRequest, - cddAuthRequest: undefined, } ); @@ -147,19 +92,16 @@ describe('acceptPrimaryKeyRotation procedure', () => { }); describe('prepareStorage', () => { - it('should return whether the target is the caller, owner AuthorizationRequest and the CDD AuthorizationRequest (if any)', async () => { + it('should return whether the target is the caller and the owner AuthorizationRequest', async () => { dsMockUtils.getContextInstance({ signingAddress: targetAddress, signingAccountIsEqual: true, - isV7: true, }); mockContext.getSigningAccount().authorizations.getOne = getOneMock; when(getOneMock).calledWith({ id: ownerAuthId }).mockResolvedValue(ownerAuthRequest); - when(getOneMock).calledWith({ id: cddAuthId }).mockResolvedValue(cddAuthRequest); - let proc = procedureMockUtils.getInstance( mockContext ); @@ -167,13 +109,11 @@ describe('acceptPrimaryKeyRotation procedure', () => { let result = await boundFunc({ ownerAuth: ownerAuthId, - cddAuth: cddAuthId, }); expect(result).toEqual({ calledByTarget: true, ownerAuthRequest, - cddAuthRequest, }); proc = procedureMockUtils.getInstance( @@ -194,33 +134,7 @@ describe('acceptPrimaryKeyRotation procedure', () => { expect(result).toEqual({ calledByTarget: false, ownerAuthRequest, - cddAuthRequest: undefined, - }); - }); - - it('should throw an error if cddAuth is provided on v8 chain', async () => { - const v8MockContext = dsMockUtils.getContextInstance({ - signingAddress: targetAddress, - signingAccountIsEqual: true, - isV7: false, }); - - const proc = procedureMockUtils.getInstance( - v8MockContext - ); - const boundFunc = prepareStorage.bind(proc); - - const expectedError = new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'CDD is discontinued since v8', - }); - - await expect( - boundFunc({ - ownerAuth: ownerAuthId, - cddAuth: cddAuthId, - }) - ).rejects.toThrow(expectedError); }); }); @@ -231,7 +145,6 @@ describe('acceptPrimaryKeyRotation procedure', () => { { calledByTarget: false, ownerAuthRequest: entityMockUtils.getAuthorizationRequestInstance(), - cddAuthRequest: undefined, } ); @@ -246,7 +159,6 @@ describe('acceptPrimaryKeyRotation procedure', () => { { calledByTarget: true, ownerAuthRequest: entityMockUtils.getAuthorizationRequestInstance(), - cddAuthRequest: undefined, } ); boundFunc = getAuthorization.bind(proc); diff --git a/src/api/procedures/__tests__/acceptSubsidy.ts b/src/api/procedures/__tests__/acceptSubsidy.ts index a123e3e009..2cd99e30e3 100644 --- a/src/api/procedures/__tests__/acceptSubsidy.ts +++ b/src/api/procedures/__tests__/acceptSubsidy.ts @@ -54,24 +54,9 @@ describe('acceptSubsidy procedure', () => { dsMockUtils.cleanup(); }); - it('should throw NotSupported when chain is v7', () => { - dsMockUtils.configureMocks({ - contextOptions: { - isV7: true, - }, - }); - - const proc = procedureMockUtils.getInstance(mockContext); - - return expect(prepareAcceptSubsidy.call(proc, args)).rejects.toThrow( - 'This method is not supported for chain 7.x.' - ); - }); - it('should throw an error if no pending subsidy exists', () => { dsMockUtils.configureMocks({ contextOptions: { - isV7: false, getPendingSubsidies: [], }, }); @@ -83,10 +68,9 @@ describe('acceptSubsidy procedure', () => { ); }); - it('should return an acceptSubsidy transaction spec when chain is v8 and subsidy is pending', async () => { + it('should return an acceptSubsidy transaction spec when a subsidy is pending', async () => { dsMockUtils.configureMocks({ contextOptions: { - isV7: false, getPendingSubsidies: [ { allowance: new BigNumber(100), diff --git a/src/api/procedures/__tests__/addInstruction.ts b/src/api/procedures/__tests__/addInstruction.ts index 3ba986424e..85ffe17a48 100644 --- a/src/api/procedures/__tests__/addInstruction.ts +++ b/src/api/procedures/__tests__/addInstruction.ts @@ -101,7 +101,6 @@ describe('addInstruction procedure', () => { let identityToBtreeSetSpy: jest.SpyInstance; let assetHolderIdsToBtreeSetSpy: jest.SpyInstance; let getAssetHolderDidSpy: jest.SpyInstance; - let assertValidCddSpy: jest.SpyInstance; let assertAssetHolderExistsSpy: jest.SpyInstance; let venueId: BigNumber; let amount: BigNumber; @@ -190,7 +189,6 @@ describe('addInstruction procedure', () => { identityToBtreeSetSpy = jest.spyOn(utilsConversionModule, 'identitiesToBtreeSet'); assetHolderIdsToBtreeSetSpy = jest.spyOn(utilsConversionModule, 'assetHolderIdsToBtreeSet'); getAssetHolderDidSpy = jest.spyOn(procedureUtilsModule, 'getAssetHolderDid'); - assertValidCddSpy = jest.spyOn(procedureUtilsModule, 'assertValidCdd'); assertAssetHolderExistsSpy = jest.spyOn(procedureUtilsModule, 'assertAssetHolderExists'); venueId = new BigNumber(1); @@ -311,7 +309,6 @@ describe('addInstruction procedure', () => { mockContext = dsMockUtils.getContextInstance(); - assertValidCddSpy.mockResolvedValue(undefined); assertAssetHolderExistsSpy.mockResolvedValue(undefined); when(assetHolderLikeToAssetHolderIdSpy).calledWith(from).mockReturnValue({ did: fromDid }); @@ -1001,80 +998,6 @@ describe('addInstruction procedure', () => { ).rejects.toThrow(expectedError); }); - it('should throw an error if from asset holder does not exist on v7 chain', async () => { - mockContext = dsMockUtils.getContextInstance({ isV7: true }); - - when(getAssetHolderDidSpy).calledWith(from, mockContext).mockResolvedValue(null); - - entityMockUtils.configureMocks({ - venueOptions: { exists: true }, - fungibleAssetOptions: { exists: true }, - nftCollectionOptions: { exists: false }, - }); - - const proc = procedureMockUtils.getInstance(mockContext, { - assetHoldersToAffirm: [[]], - }); - - let error; - try { - await prepareAddInstruction.call(proc, args); - } catch (err) { - error = err; - } - - expect(error.message).toBe('From Asset Holder does not exist'); - expect(error.code).toBe(ErrorCode.UnmetPrerequisite); - }); - - it('should throw an error if to asset holder does not exist on v7 chain', async () => { - mockContext = dsMockUtils.getContextInstance({ isV7: true }); - - when(getAssetHolderDidSpy).calledWith(to, mockContext).mockResolvedValue(null); - - entityMockUtils.configureMocks({ - venueOptions: { exists: true }, - fungibleAssetOptions: { exists: true }, - nftCollectionOptions: { exists: false }, - }); - - const proc = procedureMockUtils.getInstance(mockContext, { - assetHoldersToAffirm: [[]], - }); - - let error; - try { - await prepareAddInstruction.call(proc, args); - } catch (err) { - error = err; - } - - expect(error.message).toBe('To Asset Holder does not exist'); - expect(error.code).toBe(ErrorCode.UnmetPrerequisite); - }); - - it('should call assertValidCdd for both leg parties on v7 when holders exist', async () => { - dsMockUtils.configureMocks({ contextOptions: { did: fromDid } }); - (mockContext as { isV7: boolean }).isV7 = true; - entityMockUtils.configureMocks({ - venueOptions: { - exists: true, - }, - nftCollectionOptions: { - exists: false, - }, - }); - getCustodianMock.mockReturnValue({ did: fromDid }); - const proc = procedureMockUtils.getInstance(mockContext, { - assetHoldersToAffirm: [[fromPortfolio, toPortfolio]], - }); - - await prepareAddInstruction.call(proc, args); - - expect(assertValidCddSpy).toHaveBeenCalledWith(fromDid, mockContext); - expect(assertValidCddSpy).toHaveBeenCalledWith(toDid, mockContext); - }); - it('should handle NFT legs', async () => { entityMockUtils.configureMocks({ venueOptions: { @@ -1518,18 +1441,6 @@ describe('addInstruction procedure', () => { expect(result).toEqual({ assetHoldersToAffirm: [[fromPortfolio, signerAccount]] }); }); - - it('should skip auto-affirmation check on v7 and include the receiver', async () => { - const proc = procedureMockUtils.getInstance( - dsMockUtils.getContextInstance({ isV7: true }) - ); - const boundFunc = prepareStorage.bind(proc); - - // No call mock needed — v7 path returns false immediately - const result = await boundFunc(args); - - expect(result).toEqual({ assetHoldersToAffirm: [[fromPortfolio, signerAccount]] }); - }); }); }); }); diff --git a/src/api/procedures/__tests__/bondPolyx.ts b/src/api/procedures/__tests__/bondPolyx.ts index 553a9167be..0cf24272dd 100644 --- a/src/api/procedures/__tests__/bondPolyx.ts +++ b/src/api/procedures/__tests__/bondPolyx.ts @@ -185,40 +185,6 @@ describe('bondPolyx procedure', () => { }); }); - it('should return a v7 bond transaction spec with controller', async () => { - mockContext = dsMockUtils.getContextInstance({ isV7: true }); - bondTx = dsMockUtils.createTxMock('staking', 'bond'); - - when(bigNumberToBalanceSpy).calledWith(amount, mockContext).mockReturnValue(rawAmount); - when(stringToAccountIdSpy) - .calledWith(actingAccount.address, mockContext) - .mockReturnValue(rawAccountId); - when(stakingRewardDestinationToRawSpy) - .calledWith({ stash: true }, mockContext) - .mockReturnValue(rewardDestination); - - const proc = procedureMockUtils.getInstance(mockContext, { - actingBalance, - actingAccount, - }); - - const args = { - payee: actingAccount, - controller: actingAccount, - rewardDestination: actingAccount, - amount, - autoStake: false, - }; - - const result = await prepareBondPolyx.call(proc, args); - - expect(result).toEqual({ - transaction: bondTx, - args: [rawAccountId, rawAmount, rewardDestination], - resolver: undefined, - }); - }); - it('should handle auto stake', async () => { const proc = procedureMockUtils.getInstance(mockContext, { actingBalance, diff --git a/src/api/procedures/__tests__/consumeAddRelayerPayingKeyAuthorization.ts b/src/api/procedures/__tests__/consumeAddRelayerPayingKeyAuthorization.ts deleted file mode 100644 index 8fa6839fff..0000000000 --- a/src/api/procedures/__tests__/consumeAddRelayerPayingKeyAuthorization.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { bool, u64 } from '@polkadot/types'; -import BigNumber from 'bignumber.js'; -import { when } from 'jest-when'; - -import { - ConsumeAddRelayerPayingKeyAuthorizationParams, - getAuthorization, - prepareConsumeAddRelayerPayingKeyAuthorization, - prepareStorage, - Storage, -} from '~/api/procedures/consumeAddRelayerPayingKeyAuthorization'; -import * as utilsProcedureModule from '~/api/procedures/utils'; -import { - Account, - AuthorizationRequest, - Context, - Identity, - KnownPermissionGroup, - PolymeshError, -} from '~/internal'; -import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; -import { Mocked } from '~/testUtils/types'; -import { Authorization, AuthorizationType, ErrorCode, TxTags } from '~/types'; -import * as utilsConversionModule from '~/utils/conversion'; - -describe('consumeAddRelayerPayingKeyAuthorization procedure', () => { - let mockContext: Mocked; - let targetAddress: string; - let booleanToBoolSpy: jest.SpyInstance; - let bigNumberToU64Spy: jest.SpyInstance; - - let rawTrue: bool; - let rawFalse: bool; - let authId: BigNumber; - let rawAuthId: u64; - - let targetAccount: Account; - let issuerIdentity: Identity; - - beforeAll(() => { - targetAddress = 'someAddress'; - dsMockUtils.initMocks({ - contextOptions: { - signingAddress: targetAddress, - }, - }); - procedureMockUtils.initMocks(); - entityMockUtils.initMocks(); - - jest.spyOn(utilsProcedureModule, 'assertAuthorizationRequestValid').mockImplementation(); - - bigNumberToU64Spy = jest.spyOn(utilsConversionModule, 'bigNumberToU64'); - booleanToBoolSpy = jest.spyOn(utilsConversionModule, 'booleanToBool'); - - authId = new BigNumber(1); - rawAuthId = dsMockUtils.createMockU64(authId); - - rawFalse = dsMockUtils.createMockBool(false); - rawTrue = dsMockUtils.createMockBool(true); - - jest.spyOn(utilsConversionModule, 'addressToKey').mockImplementation(); - }); - - beforeEach(() => { - mockContext = dsMockUtils.getContextInstance({ - isV7: true, - }); - - when(bigNumberToU64Spy).calledWith(authId, mockContext).mockReturnValue(rawAuthId); - - when(booleanToBoolSpy).calledWith(false, mockContext).mockReturnValue(rawFalse); - when(booleanToBoolSpy).calledWith(true, mockContext).mockReturnValue(rawTrue); - - targetAccount = entityMockUtils.getAccountInstance({ address: targetAddress }); - - issuerIdentity = entityMockUtils.getIdentityInstance(); - }); - - afterEach(() => { - entityMockUtils.reset(); - procedureMockUtils.reset(); - dsMockUtils.reset(); - }); - - afterAll(() => { - procedureMockUtils.cleanup(); - dsMockUtils.cleanup(); - }); - - it('should throw if called with an Authorization other than AddRelayerPayingKey', () => { - const proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext, { - actingAccount: targetAccount, - calledByTarget: true, - }); - - return expect( - prepareConsumeAddRelayerPayingKeyAuthorization.call(proc, { - authRequest: new AuthorizationRequest( - { - target: targetAccount, - issuer: issuerIdentity, - authId, - expiry: null, - data: { - type: AuthorizationType.BecomeAgent, - value: {} as KnownPermissionGroup, - }, - }, - mockContext - ), - accept: true, - }) - ).rejects.toThrow( - 'Unrecognized auth type: "BecomeAgent" for consumeAddRelayerPayingKeyAuthorization method' - ); - }); - - it('should return an acceptPayingKey transaction spec if accept is set to true', async () => { - const proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext, { - actingAccount: targetAccount, - calledByTarget: true, - }); - - const transaction = dsMockUtils.createTxMock('relayer', 'acceptPayingKey'); - - const result = await prepareConsumeAddRelayerPayingKeyAuthorization.call(proc, { - authRequest: new AuthorizationRequest( - { - target: targetAccount, - issuer: issuerIdentity, - authId, - expiry: null, - data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - value: { - subsidizer: entityMockUtils.getAccountInstance(), - beneficiary: targetAccount, - allowance: new BigNumber(100), - }, - }, - }, - mockContext - ), - accept: true, - }); - - expect(result).toEqual({ - transaction, - paidForBy: issuerIdentity, - args: [rawAuthId], - resolver: undefined, - }); - }); - - it('should return a removeAuthorization transaction spec if accept is set to false', async () => { - let proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext, { - actingAccount: targetAccount, - calledByTarget: false, - }); - - const transaction = dsMockUtils.createTxMock('identity', 'removeAuthorization'); - - const rawSignatory = dsMockUtils.createMockSignatory({ - Account: dsMockUtils.createMockAccountId(targetAccount.address), - }); - - jest.spyOn(utilsConversionModule, 'signerValueToSignatory').mockReturnValue(rawSignatory); - - const params = { - authRequest: new AuthorizationRequest( - { - target: targetAccount, - issuer: issuerIdentity, - authId, - expiry: null, - data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - value: { - subsidizer: entityMockUtils.getAccountInstance(), - beneficiary: targetAccount, - allowance: new BigNumber(100), - }, - }, - }, - mockContext - ), - accept: false, - }; - - let result = await prepareConsumeAddRelayerPayingKeyAuthorization.call(proc, params); - - expect(result).toEqual({ - transaction, - args: [rawSignatory, rawAuthId, rawFalse], - resolver: undefined, - }); - - proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext, { - actingAccount: targetAccount, - calledByTarget: true, - }); - - result = await prepareConsumeAddRelayerPayingKeyAuthorization.call(proc, params); - - expect(result).toEqual({ - transaction, - paidForBy: issuerIdentity, - args: [rawSignatory, rawAuthId, rawTrue], - resolve: undefined, - }); - }); - - it('should throw an error if accept is set to true and chain is v8 (isV7 = false)', () => { - const v8MockContext = dsMockUtils.getContextInstance({ isV7: false }); - - const proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(v8MockContext, { - actingAccount: targetAccount, - calledByTarget: true, - }); - - const expectedError = new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'acceptPayingKey type authorization is not supported in chain 8.x', - }); - - return expect( - prepareConsumeAddRelayerPayingKeyAuthorization.call(proc, { - authRequest: new AuthorizationRequest( - { - target: targetAccount, - issuer: issuerIdentity, - authId, - expiry: null, - data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - value: { - subsidizer: entityMockUtils.getAccountInstance(), - beneficiary: targetAccount, - allowance: new BigNumber(100), - }, - }, - }, - v8MockContext - ), - accept: true, - }) - ).rejects.toThrow(expectedError); - }); - - describe('prepareStorage', () => { - it("should return the signing Account, whether the target is the caller and the target's Identity (if any)", async () => { - const proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext); - const boundFunc = prepareStorage.bind(proc); - - const result = await boundFunc({ - authRequest: { target: targetAccount }, - } as unknown as ConsumeAddRelayerPayingKeyAuthorizationParams); - - expect(result).toEqual({ - actingAccount: mockContext.getSigningAccount(), - calledByTarget: true, - }); - }); - }); - - describe('getAuthorization', () => { - it('should return the appropriate roles and permissions', async () => { - let proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext, { - actingAccount: targetAccount, - calledByTarget: true, - }); - const constructorParams = { - authId, - expiry: null, - target: targetAccount, - issuer: issuerIdentity, - data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - } as Authorization, - }; - const args = { - authRequest: new AuthorizationRequest(constructorParams, mockContext), - accept: true, - }; - - let boundFunc = getAuthorization.bind(proc); - let result = await boundFunc(args); - expect(result).toEqual({ - roles: true, - }); - - args.accept = false; - - result = await boundFunc(args); - expect(result).toEqual({ - roles: true, - permissions: { - transactions: [TxTags.identity.RemoveAuthorization], - }, - }); - - proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext, { - actingAccount: targetAccount, - calledByTarget: false, - }); - boundFunc = getAuthorization.bind(proc); - - result = await boundFunc(args); - expect(result).toEqual({ - roles: true, - permissions: { - transactions: [TxTags.identity.RemoveAuthorization], - }, - }); - - proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext, { - actingAccount: entityMockUtils.getAccountInstance({ - address: 'someOtherAddress', - getIdentity: entityMockUtils.getIdentityInstance({ did: 'someOtherDid', isEqual: false }), - }), - calledByTarget: false, - }); - boundFunc = getAuthorization.bind(proc); - - result = await boundFunc(args); - expect(result).toEqual({ - roles: - '"AddRelayerPayingKey" Authorization Requests can only be removed by the issuer Identity or the target Account', - permissions: { - transactions: [TxTags.identity.RemoveAuthorization], - }, - }); - - proc = procedureMockUtils.getInstance< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage - >(mockContext, { - actingAccount: entityMockUtils.getAccountInstance({ - address: 'someOtherAddress', - getIdentity: entityMockUtils.getIdentityInstance({ did: 'someOtherDid', isEqual: false }), - }), - calledByTarget: false, - }); - boundFunc = getAuthorization.bind(proc); - - result = await boundFunc(args); - expect(result).toEqual({ - roles: - '"AddRelayerPayingKey" Authorization Requests can only be removed by the issuer Identity or the target Account', - permissions: { - transactions: [TxTags.identity.RemoveAuthorization], - }, - }); - - result = await boundFunc({ ...args, accept: true }); - expect(result).toEqual({ - roles: - '"AddRelayerPayingKey" Authorization Requests must be accepted by the target Account', - }); - }); - }); -}); diff --git a/src/api/procedures/__tests__/consumeJoinOrRotateAuthorization.ts b/src/api/procedures/__tests__/consumeJoinOrRotateAuthorization.ts index 3297c54030..c2bb79c23e 100644 --- a/src/api/procedures/__tests__/consumeJoinOrRotateAuthorization.ts +++ b/src/api/procedures/__tests__/consumeJoinOrRotateAuthorization.ts @@ -298,57 +298,6 @@ describe('consumeJoinOrRotateAuthorization procedure', () => { }); }); - it('should return a rotatePrimaryKeyToSecondary transaction spec with v7 arguments if context.isV7 is true', async () => { - const v7MockContext = dsMockUtils.getContextInstance({ isV7: true }); - when(bigNumberToU64Spy).calledWith(authId, v7MockContext).mockReturnValue(rawAuthId); - - const proc = procedureMockUtils.getInstance< - ConsumeJoinOrRotateAuthorizationParams, - void, - Storage - >(v7MockContext, { - actingAccount: targetAccount, - calledByTarget: true, - }); - - const transaction = dsMockUtils.createTxMock('identity', 'rotatePrimaryKeyToSecondary'); - - const issuer = entityMockUtils.getIdentityInstance(); - const target = entityMockUtils.getAccountInstance({ - address: 'someAddress', - getIdentity: null, - }); - - const result = await prepareConsumeJoinOrRotateAuthorization.call(proc, { - authRequest: new AuthorizationRequest( - { - target, - issuer, - authId, - expiry: null, - data: { - type: AuthorizationType.RotatePrimaryKeyToSecondary, - value: { - assets: null, - transactions: null, - transactionGroups: [], - portfolios: null, - }, - }, - }, - v7MockContext - ), - accept: true, - }); - - expect(result).toEqual({ - transaction, - paidForBy: issuer, - args: [rawAuthId, null], - resolver: undefined, - }); - }); - it('should throw if called with an Authorization that is not JoinIdentity, RotatePrimaryKeyToSecondary or RotatePrimaryKey', async () => { const proc = procedureMockUtils.getInstance< ConsumeJoinOrRotateAuthorizationParams, diff --git a/src/api/procedures/__tests__/createChildIdentities.ts b/src/api/procedures/__tests__/createChildIdentities.ts deleted file mode 100644 index 13a2396b2c..0000000000 --- a/src/api/procedures/__tests__/createChildIdentities.ts +++ /dev/null @@ -1,299 +0,0 @@ -import { Vec } from '@polkadot/types/codec'; -import { Moment } from '@polkadot/types/interfaces/runtime'; -import { Codec, ISubmittableResult } from '@polkadot/types/types'; -import BigNumber from 'bignumber.js'; -import { when } from 'jest-when'; - -import { ChildIdentity } from '~/api/entities/Identity/ChildIdentity'; -import { - createChildIdentityResolver, - getAuthorization, - prepareCreateChildIdentities, - prepareStorage, - Storage, -} from '~/api/procedures/createChildIdentities'; -import { Account, Context, Identity } from '~/internal'; -import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; -import { Mocked } from '~/testUtils/types'; -import { CreateChildIdentitiesParams, TxTags } from '~/types'; -import * as utilsConversionModule from '~/utils/conversion'; -import * as utilsInternalModule from '~/utils/internal'; - -jest.mock( - '~/api/entities/Identity/ChildIdentity', - require('~/testUtils/mocks/entities').mockChildIdentityModule( - '~/api/entities/Identity/ChildIdentity' - ) -); - -describe('createChildIdentities procedure', () => { - let mockContext: Mocked; - let identity: Identity; - let actingAccount: Account; - let childAccount: Account; - let childKeysWithAuthToCreateChildIdentitiesWithAuthSpy: jest.SpyInstance; - - let rawChildKeyWithAuths: Vec; - let args: CreateChildIdentitiesParams; - let expiresAt: Date; - let rawExpiresAt: Moment; - let dateToMomentSpy: jest.SpyInstance; - - beforeAll(() => { - dsMockUtils.initMocks(); - procedureMockUtils.initMocks(); - entityMockUtils.initMocks(); - - childKeysWithAuthToCreateChildIdentitiesWithAuthSpy = jest.spyOn( - utilsConversionModule, - 'childKeysWithAuthToCreateChildIdentitiesWithAuth' - ); - dateToMomentSpy = jest.spyOn(utilsConversionModule, 'dateToMoment'); - }); - - beforeEach(() => { - entityMockUtils.configureMocks({ - childIdentityOptions: { - getParentDid: null, - }, - }); - - childAccount = entityMockUtils.getAccountInstance({ - address: 'childAddress', - getIdentity: null, - }); - - actingAccount = entityMockUtils.getAccountInstance({ - address: 'actingAccount', - }); - identity = entityMockUtils.getIdentityInstance({ - getPrimaryAccount: { - account: actingAccount, - }, - }); - - mockContext = dsMockUtils.getContextInstance({ - getIdentity: identity, - isV7: true, - }); - - expiresAt = new Date('2050/01/01'); - - args = { - childKeyAuths: [ - { - key: childAccount, - authSignature: '0xsignature', - }, - ], - expiresAt, - }; - - rawExpiresAt = dsMockUtils.createMockMoment(new BigNumber(expiresAt.getTime())); - when(dateToMomentSpy).calledWith(expiresAt, mockContext).mockReturnValue(rawExpiresAt); - - rawChildKeyWithAuths = 'someKeysWithAuth' as unknown as Vec; - - when(childKeysWithAuthToCreateChildIdentitiesWithAuthSpy) - .calledWith(args.childKeyAuths, mockContext) - .mockReturnValue(rawChildKeyWithAuths); - }); - - afterEach(() => { - entityMockUtils.reset(); - procedureMockUtils.reset(); - dsMockUtils.reset(); - }); - - afterAll(() => { - jest.resetAllMocks(); - procedureMockUtils.cleanup(); - dsMockUtils.cleanup(); - }); - - it('should throw an error if expiry date is not valid', () => { - const proc = procedureMockUtils.getInstance< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - return expect( - prepareCreateChildIdentities.call(proc, { - ...args, - expiresAt: new Date('2020/01/01'), - }) - ).rejects.toThrow('Expiry date must be in the future'); - }); - - it('should throw NotSupported when the chain is not v7', () => { - mockContext = dsMockUtils.getContextInstance({ isV7: false }); - - const proc = procedureMockUtils.getInstance< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - return expect(prepareCreateChildIdentities.call(proc, args)).rejects.toThrow( - 'Child identities are no longer supported in chain v8' - ); - }); - - it('should throw an error if the signing Identity is already a child Identity', () => { - entityMockUtils.configureMocks({ - childIdentityOptions: { - getParentDid: entityMockUtils.getIdentityInstance({ did: 'someParentDid' }), - }, - }); - - const proc = procedureMockUtils.getInstance< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - return expect(prepareCreateChildIdentities.call(proc, args)).rejects.toThrow( - 'The signing Identity is already a child Identity and cannot create further child identities' - ); - }); - - it('should throw an error if the one or more accounts are already linked to an Identity', () => { - const proc = procedureMockUtils.getInstance< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - return expect( - prepareCreateChildIdentities.call(proc, { - childKeyAuths: [ - { - key: entityMockUtils.getAccountInstance({ - address: 'secondaryAccount', - getIdentity: entityMockUtils.getIdentityInstance({ did: 'someRandomDid' }), - }), - authSignature: '0xsignature', - }, - ], - expiresAt, - }) - ).rejects.toThrow('One or more accounts are already linked to some Identity'); - }); - - it('should add a createChildIdentities transaction to the queue', async () => { - const proc = procedureMockUtils.getInstance< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - const createChildIdentitiesTransaction = dsMockUtils.createTxMock( - 'identity', - 'createChildIdentities' - ); - - const result = await prepareCreateChildIdentities.call(proc, args); - - expect(result).toEqual({ - transaction: createChildIdentitiesTransaction, - resolver: expect.any(Function), - args: [rawChildKeyWithAuths, rawExpiresAt], - }); - }); - - describe('getAuthorization', () => { - it('should return the appropriate roles and permissions', async () => { - let proc = procedureMockUtils.getInstance< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - let boundFunc = getAuthorization.bind(proc); - - let result = await boundFunc(); - expect(result).toEqual({ - permissions: { - transactions: [TxTags.identity.CreateChildIdentities], - assets: [], - portfolios: [], - }, - }); - - identity = entityMockUtils.getIdentityInstance({ - getPrimaryAccount: { - account: entityMockUtils.getAccountInstance({ - address: 'differentAddress', - }), - }, - }); - - proc = procedureMockUtils.getInstance< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage - >( - dsMockUtils.getContextInstance({ - signingAccountIsEqual: false, - }), - { identity, actingAccount } - ); - - boundFunc = getAuthorization.bind(proc); - - result = await boundFunc(); - expect(result).toEqual({ - signerPermissions: "Child Identities can only be created by an Identity's primary Account", - }); - }); - }); - - describe('prepareStorage', () => { - it('should return the signing Identity', async () => { - const proc = procedureMockUtils.getInstance< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage - >(mockContext); - const boundFunc = prepareStorage.bind(proc); - - const result = await boundFunc(); - - expect(result).toEqual({ - identity: expect.objectContaining({ - did: 'someDid', - }), - actingAccount: expect.objectContaining({ - address: '0xdummy', - }), - }); - }); - }); - - describe('createChildIdentityResolver', () => { - const filterEventRecordsSpy = jest.spyOn(utilsInternalModule, 'filterEventRecords'); - const did = 'someDid'; - const rawIdentityId = dsMockUtils.createMockIdentityId(did); - const childDid = 'someChildDid'; - const rawChildIdentity = dsMockUtils.createMockIdentityId(childDid); - - beforeEach(() => { - filterEventRecordsSpy.mockReturnValue([ - dsMockUtils.createMockIEvent([rawIdentityId, rawChildIdentity]), - ]); - }); - - afterEach(() => { - jest.resetAllMocks(); - filterEventRecordsSpy.mockReset(); - }); - - it('should return the new ChildIdentity', () => { - const fakeContext = {} as Context; - - const result = createChildIdentityResolver(fakeContext)({} as ISubmittableResult); - - expect(result[0]!.did).toEqual(childDid); - }); - }); -}); diff --git a/src/api/procedures/__tests__/createChildIdentity.ts b/src/api/procedures/__tests__/createChildIdentity.ts deleted file mode 100644 index 22133ddfa2..0000000000 --- a/src/api/procedures/__tests__/createChildIdentity.ts +++ /dev/null @@ -1,296 +0,0 @@ -import { AccountId } from '@polkadot/types/interfaces'; -import { PolymeshPrimitivesIdentityId } from '@polkadot/types/lookup'; -import { ISubmittableResult } from '@polkadot/types/types'; -import BigNumber from 'bignumber.js'; -import { when } from 'jest-when'; - -import { ChildIdentity } from '~/api/entities/Identity/ChildIdentity'; -import { - createChildIdentityResolver, - getAuthorization, - prepareCreateChildIdentity, - prepareStorage, - Storage, -} from '~/api/procedures/createChildIdentity'; -import { Account, Context, Identity } from '~/internal'; -import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; -import { Mocked } from '~/testUtils/types'; -import { CreateChildIdentityParams, TxTags } from '~/types'; -import * as utilsConversionModule from '~/utils/conversion'; -import * as utilsInternalModule from '~/utils/internal'; - -jest.mock( - '~/api/entities/Identity/ChildIdentity', - require('~/testUtils/mocks/entities').mockChildIdentityModule( - '~/api/entities/Identity/ChildIdentity' - ) -); - -describe('createChildIdentity procedure', () => { - let mockContext: Mocked; - let identity: Identity; - let actingAccount: Account; - let rawIdentity: PolymeshPrimitivesIdentityId; - let childAccount: Account; - let rawChildAccount: AccountId; - let stringToIdentityIdSpy: jest.SpyInstance; - let stringToAccountIdSpy: jest.SpyInstance; - let boolToBooleanSpy: jest.SpyInstance; - - let didKeysQueryMock: jest.Mock; - - beforeAll(() => { - dsMockUtils.initMocks(); - procedureMockUtils.initMocks(); - entityMockUtils.initMocks(); - - stringToIdentityIdSpy = jest.spyOn(utilsConversionModule, 'stringToIdentityId'); - stringToAccountIdSpy = jest.spyOn(utilsConversionModule, 'stringToAccountId'); - boolToBooleanSpy = jest.spyOn(utilsConversionModule, 'boolToBoolean'); - }); - - beforeEach(() => { - entityMockUtils.configureMocks({ - childIdentityOptions: { - getParentDid: null, - }, - }); - childAccount = entityMockUtils.getAccountInstance(); - rawChildAccount = dsMockUtils.createMockAccountId(childAccount.address); - - actingAccount = entityMockUtils.getAccountInstance({ - address: 'actingAccount', - }); - identity = entityMockUtils.getIdentityInstance({ - getPrimaryAccount: { - account: actingAccount, - }, - }); - rawIdentity = dsMockUtils.createMockIdentityId(identity.did); - - mockContext = dsMockUtils.getContextInstance({ - getIdentity: identity, - isV7: true, - }); - - when(stringToIdentityIdSpy).calledWith(identity.did, mockContext).mockReturnValue(rawIdentity); - when(stringToAccountIdSpy) - .calledWith(childAccount.address, mockContext) - .mockReturnValue(rawChildAccount); - - const rawTrue = dsMockUtils.createMockBool(true); - didKeysQueryMock = dsMockUtils.createQueryMock('identity', 'didKeys'); - when(didKeysQueryMock).calledWith(rawIdentity, rawChildAccount).mockResolvedValue(rawTrue); - - when(boolToBooleanSpy).calledWith(rawTrue).mockReturnValue(true); - }); - - afterEach(() => { - entityMockUtils.reset(); - procedureMockUtils.reset(); - dsMockUtils.reset(); - }); - - afterAll(() => { - jest.resetAllMocks(); - procedureMockUtils.cleanup(); - dsMockUtils.cleanup(); - }); - - it('should throw an error if the `secondaryKey` provided is not a secondary account of the signing Identity', () => { - const mockAccount = entityMockUtils.getAccountInstance({ address: 'someOtherAddress' }); - - const rawOtherAccount = dsMockUtils.createMockAccountId(mockAccount.address); - when(stringToAccountIdSpy) - .calledWith(mockAccount.address, mockContext) - .mockReturnValue(rawOtherAccount); - - const rawFalse = dsMockUtils.createMockBool(false); - when(didKeysQueryMock).calledWith(rawIdentity, rawOtherAccount).mockResolvedValue(rawFalse); - - when(boolToBooleanSpy).calledWith(rawFalse).mockReturnValue(false); - - const proc = procedureMockUtils.getInstance< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - return expect( - prepareCreateChildIdentity.call(proc, { - secondaryKey: mockAccount, - }) - ).rejects.toThrow('The `secondaryKey` provided is not a secondary key of the signing Identity'); - }); - - it('should throw NotSupported when the chain is not v7', () => { - mockContext = dsMockUtils.getContextInstance({ isV7: false }); - - const proc = procedureMockUtils.getInstance< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - return expect( - prepareCreateChildIdentity.call(proc, { secondaryKey: childAccount }) - ).rejects.toThrow('Child identities are no longer supported in v8'); - }); - - it('should throw an error if the account provided is a part of multisig with some POLYX balance', () => { - childAccount.getMultiSig = jest.fn().mockResolvedValue( - entityMockUtils.getMultiSigInstance({ - getBalance: { - total: new BigNumber(100), - }, - }) - ); - - const proc = procedureMockUtils.getInstance< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - return expect( - prepareCreateChildIdentity.call(proc, { - secondaryKey: childAccount, - }) - ).rejects.toThrow("The `secondaryKey` can't be unlinked from the signing Identity"); - }); - - it('should throw an error if the signing Identity is already a child Identity', () => { - entityMockUtils.configureMocks({ - childIdentityOptions: { - getParentDid: entityMockUtils.getIdentityInstance({ did: 'someParentDid' }), - }, - }); - - const proc = procedureMockUtils.getInstance< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - return expect( - prepareCreateChildIdentity.call(proc, { - secondaryKey: childAccount, - }) - ).rejects.toThrow( - 'The signing Identity is already a child Identity and cannot create further child identities' - ); - }); - - it('should add a create ChildIdentity transaction to the queue', async () => { - const proc = procedureMockUtils.getInstance< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage - >(mockContext, { identity, actingAccount }); - - const createChildIdentityTransaction = dsMockUtils.createTxMock( - 'identity', - 'createChildIdentity' - ); - - const result = await prepareCreateChildIdentity.call(proc, { - secondaryKey: childAccount, - }); - - expect(result).toEqual({ - transaction: createChildIdentityTransaction, - resolver: expect.any(Function), - args: [rawChildAccount], - }); - }); - - describe('getAuthorization', () => { - it('should return the appropriate roles and permissions', async () => { - let proc = procedureMockUtils.getInstance( - mockContext, - { identity, actingAccount } - ); - let boundFunc = getAuthorization.bind(proc); - - let result = await boundFunc(); - expect(result).toEqual({ - permissions: { - transactions: [TxTags.identity.CreateChildIdentity], - assets: [], - portfolios: [], - }, - }); - - identity = entityMockUtils.getIdentityInstance({ - getPrimaryAccount: { - account: entityMockUtils.getAccountInstance({ - address: 'differentAddress', - }), - }, - }); - - proc = procedureMockUtils.getInstance( - dsMockUtils.getContextInstance({ - signingAccountIsEqual: false, - }), - { identity, actingAccount } - ); - - boundFunc = getAuthorization.bind(proc); - - result = await boundFunc(); - expect(result).toEqual({ - signerPermissions: "A child Identity can only be created by an Identity's primary Account", - }); - }); - }); - - describe('prepareStorage', () => { - it('should return the signing Identity', async () => { - const proc = procedureMockUtils.getInstance< - CreateChildIdentityParams, - ChildIdentity, - Storage - >(mockContext); - const boundFunc = prepareStorage.bind(proc); - - const result = await boundFunc(); - - expect(result).toEqual({ - identity: expect.objectContaining({ - did: 'someDid', - }), - actingAccount: expect.objectContaining({ - address: '0xdummy', - }), - }); - }); - }); - - describe('createChildIdentityResolver', () => { - const filterEventRecordsSpy = jest.spyOn(utilsInternalModule, 'filterEventRecords'); - const did = 'someDid'; - const rawIdentityId = dsMockUtils.createMockIdentityId(did); - const childDid = 'someChildDid'; - const rawChildIdentity = dsMockUtils.createMockIdentityId(childDid); - - beforeEach(() => { - filterEventRecordsSpy.mockReturnValue([ - dsMockUtils.createMockIEvent([rawIdentityId, rawChildIdentity]), - ]); - }); - - afterEach(() => { - jest.resetAllMocks(); - filterEventRecordsSpy.mockReset(); - }); - - it('should return the new ChildIdentity', () => { - const fakeContext = {} as Context; - - const result = createChildIdentityResolver(fakeContext)({} as ISubmittableResult); - - expect(result.did).toEqual(childDid); - }); - }); -}); diff --git a/src/api/procedures/__tests__/createVenue.ts b/src/api/procedures/__tests__/createVenue.ts index b53ee1ddb3..58d83bef32 100644 --- a/src/api/procedures/__tests__/createVenue.ts +++ b/src/api/procedures/__tests__/createVenue.ts @@ -117,29 +117,7 @@ describe('createVenue procedure', () => { resolver: expect.any(Function), }); }); - - it('should use stringToAccountId per signer when chain is v7', async () => { - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); - - const proc = procedureMockUtils.getInstance(mockContext); - - const rawSigner = dsMockUtils.createMockAccountId('newSigner'); - const stringToAccountIdSpy = jest.spyOn(utilsConversionModule, 'stringToAccountId'); - stringToAccountIdSpy.mockReturnValue(rawSigner); - - when(stringToBytes).calledWith(description, mockContext).mockReturnValue(rawDetails); - when(venueTypeToMeshVenueTypeSpy).calledWith(type, mockContext).mockReturnValue(rawType); - - const result = await prepareCreateVenue.call(proc, { ...args, signers: ['newSigner'] }); - - expect(result).toEqual({ - transaction: createVenueTransaction, - args: [rawDetails, [rawSigner], rawType], - resolver: expect.any(Function), - }); - }); }); - describe('createCreateVenueResolver', () => { const filterEventRecordsSpy = jest.spyOn(utilsInternalModule, 'filterEventRecords'); const id = new BigNumber(10); diff --git a/src/api/procedures/__tests__/issueNft.ts b/src/api/procedures/__tests__/issueNft.ts index b23c681d24..f5ebe35c61 100644 --- a/src/api/procedures/__tests__/issueNft.ts +++ b/src/api/procedures/__tests__/issueNft.ts @@ -320,13 +320,5 @@ describe('issueNft procedure', () => { expect(result[0]!.collection).toEqual(expect.objectContaining({ id: assetId })); expect(result[0]!.id).toEqual(id); }); - - it('should use NFTPortfolioUpdated event when chain is v7', () => { - const context = dsMockUtils.getContextInstance({ isV7: true }); - const result = issuedNftsResolver(context)({} as ISubmittableResult); - - expect(result[0]!.collection).toEqual(expect.objectContaining({ id: assetId })); - expect(result[0]!.id).toEqual(id); - }); }); }); diff --git a/src/api/procedures/__tests__/modifyClaims.ts b/src/api/procedures/__tests__/modifyClaims.ts index cb8465ea84..07a8b3b8fd 100644 --- a/src/api/procedures/__tests__/modifyClaims.ts +++ b/src/api/procedures/__tests__/modifyClaims.ts @@ -562,7 +562,7 @@ describe('modifyClaims procedure', () => { } as ModifyClaimsParams; expect(getAuthorization(args)).toEqual({ - roles: [{ type: RoleType.CddProvider }], + roles: [{ type: RoleType.DidRegistrar }], permissions: { assets: [], portfolios: [], diff --git a/src/api/procedures/__tests__/modifyInstructionAffirmation.ts b/src/api/procedures/__tests__/modifyInstructionAffirmation.ts index fde11720f4..60a73450cc 100644 --- a/src/api/procedures/__tests__/modifyInstructionAffirmation.ts +++ b/src/api/procedures/__tests__/modifyInstructionAffirmation.ts @@ -142,12 +142,8 @@ describe('modifyInstructionAffirmation procedure', () => { beforeEach(() => { rawLegAmount = dsMockUtils.createMockU32(new BigNumber(2)); dsMockUtils.createTxMock('settlement', 'affirmInstructionWithCount'); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - dsMockUtils.createTxMock('settlement' as any, 'withdrawAffirmationWithCount'); dsMockUtils.createTxMock('settlement', 'rejectInstructionWithCount'); dsMockUtils.createTxMock('settlement', 'affirmInstructionAsMediator'); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - dsMockUtils.createTxMock('settlement' as any, 'withdrawAffirmationAsMediator'); dsMockUtils.createTxMock('settlement', 'rejectInstructionAsMediator'); dsMockUtils.createCallMock('settlementApi', 'getExecuteInstructionInfo', { returnValue: dsMockUtils.createMockOption(mockExecuteInfo), @@ -212,64 +208,6 @@ describe('modifyInstructionAffirmation procedure', () => { ).rejects.toThrow('Some of the asset holders are not a involved in this instruction'); }); - it('should throw an error if the operation is Withdraw and the chain is v8 (isV7 = false)', () => { - const v8MockContext = dsMockUtils.getContextInstance({ isV7: false }); - const proc = procedureMockUtils.getInstance< - ModifyInstructionAffirmationParams, - Instruction, - Storage - >(v8MockContext, { - allowedAssetHolders: [portfolio], - assetHolderParams: [], - senderLegCount: legAmount, - totalLegCount: legAmount, - signer, - offChainLegIndices: [], - instructionInfo: mockExecuteInfo, - }); - - const expectedError = new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'Withdrawal of affirmed instructions has been discontinued from v8 chain', - }); - - return expect( - prepareModifyInstructionAffirmation.call(proc, { - id, - operation: InstructionAffirmationOperation.Withdraw, // NOSONAR - }) - ).rejects.toThrow(expectedError); - }); - - it('should throw an error if the operation is WithdrawAsMediator and the chain is v8 (isV7 = false)', () => { - const v8MockContext = dsMockUtils.getContextInstance({ isV7: false }); - const proc = procedureMockUtils.getInstance< - ModifyInstructionAffirmationParams, - Instruction, - Storage - >(v8MockContext, { - allowedAssetHolders: [portfolio], - assetHolderParams: [], - senderLegCount: legAmount, - totalLegCount: legAmount, - signer, - offChainLegIndices: [], - instructionInfo: mockExecuteInfo, - }); - - const expectedError = new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'Withdrawal of affirmed instructions has been discontinued from v8 chain', - }); - - return expect( - prepareModifyInstructionAffirmation.call(proc, { - id, - operation: InstructionAffirmationOperation.WithdrawAsMediator, // NOSONAR - }) - ).rejects.toThrow(expectedError); - }); - it('should throw an error if the signing Identity is not the custodian of any of the involved portfolios', () => { const rawAffirmationStatus = dsMockUtils.createMockAffirmationStatus('Affirmed'); dsMockUtils.createQueryMock('settlement', 'affirmsReceived', { @@ -756,52 +694,7 @@ describe('modifyInstructionAffirmation procedure', () => { }); }); - it('should throw an error if operation is Withdraw and the current status of the instruction is pending', () => { - dsMockUtils.configureMocks({ - contextOptions: { isV7: true }, - }); - const rawAffirmationStatus = dsMockUtils.createMockAffirmationStatus('Pending'); - dsMockUtils.createQueryMock('settlement', 'affirmsReceived', { - multi: [rawAffirmationStatus, rawAffirmationStatus], - }); - when(meshAffirmationStatusToAffirmationStatusSpy) - .calledWith(rawAffirmationStatus) - .mockReturnValue(AffirmationStatus.Pending); - - const proc = procedureMockUtils.getInstance< - ModifyInstructionAffirmationParams, - Instruction, - Storage - >(mockContext, { - allowedAssetHolders: [portfolio, portfolio], - assetHolderParams: [], - senderLegCount: legAmount, - totalLegCount: legAmount, - signer, - offChainLegIndices: [], - instructionInfo: mockExecuteInfo, - }); - - return expect( - prepareModifyInstructionAffirmation.call(proc, { - id, - operation: InstructionAffirmationOperation.Withdraw, // NOSONAR - }) - ).rejects.toThrow('The instruction is not affirmed'); - }); - - it('should throw an error if operation is Withdraw/Reject and the current status of the instruction is LockedForExecution', async () => { - dsMockUtils.configureMocks({ - contextOptions: { isV7: true }, - }); - const rawAffirmationStatus = dsMockUtils.createMockAffirmationStatus('Affirmed'); - dsMockUtils.createQueryMock('settlement', 'affirmsReceived', { - multi: [rawAffirmationStatus, rawAffirmationStatus], - }); - when(meshAffirmationStatusToAffirmationStatusSpy) - .calledWith(rawAffirmationStatus) - .mockReturnValue(AffirmationStatus.Affirmed); - + it('should throw an error if operation is Reject and the current status of the instruction is LockedForExecution', async () => { const lockedAt = new Date(); const unlocksAt = new Date(lockedAt.getTime() + 84400000); @@ -830,13 +723,6 @@ describe('modifyInstructionAffirmation procedure', () => { instructionInfo: mockExecuteInfo, }); - await expect( - prepareModifyInstructionAffirmation.call(proc, { - id, - operation: InstructionAffirmationOperation.Withdraw, // NOSONAR - }) - ).rejects.toThrow('The instruction is locked for execution'); - await expect( prepareModifyInstructionAffirmation.call(proc, { id, @@ -845,142 +731,6 @@ describe('modifyInstructionAffirmation procedure', () => { ).rejects.toThrow('The instruction is locked for execution'); }); - it('should return a withdraw instruction transaction spec', async () => { - dsMockUtils.configureMocks({ - contextOptions: { - isV7: true, - }, - }); - const rawAffirmationStatus = dsMockUtils.createMockAffirmationStatus('Affirmed'); - dsMockUtils.createQueryMock('settlement', 'affirmsReceived', { - multi: [rawAffirmationStatus, rawAffirmationStatus], - }); - when(meshAffirmationStatusToAffirmationStatusSpy) - .calledWith(rawAffirmationStatus) - .mockReturnValue(AffirmationStatus.Affirmed); - - const proc = procedureMockUtils.getInstance< - ModifyInstructionAffirmationParams, - Instruction, - Storage - >(mockContext, { - allowedAssetHolders: [portfolio, portfolio], - assetHolderParams: [], - senderLegCount: legAmount, - totalLegCount: legAmount, - signer, - offChainLegIndices: [], - instructionInfo: mockExecuteInfo, - }); - - const transaction = dsMockUtils.createTxMock( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - 'settlement' as any, - 'withdrawAffirmationWithCount' - ); - - const result = await prepareModifyInstructionAffirmation.call(proc, { - id, - operation: InstructionAffirmationOperation.Withdraw, // NOSONAR - }); - - expect(result).toEqual({ - transaction, - feeMultiplier: new BigNumber(2), - args: [rawInstructionId, new Set([rawPortfolioId, rawPortfolioId]), mockAffirmCount], - resolver: expect.objectContaining({ id }), - }); - }); - - it('should throw an error if a mediator attempts to withdraw a non affirmed transaction', () => { - dsMockUtils.configureMocks({ - contextOptions: { - isV7: true, - }, - }); - const rawAffirmationStatus = createMockMediatorAffirmationStatus(AffirmationStatus.Pending); - dsMockUtils.createQueryMock('settlement', 'instructionMediatorsAffirmations', { - returnValue: rawAffirmationStatus, - }); - when(mediatorAffirmationStatusToStatusSpy) - .calledWith(rawAffirmationStatus) - .mockReturnValue({ status: AffirmationStatus.Pending }); - - const proc = procedureMockUtils.getInstance< - ModifyInstructionAffirmationParams, - Instruction, - Storage - >(mockContext, { - allowedAssetHolders: [portfolio, portfolio], - assetHolderParams: [], - senderLegCount: legAmount, - totalLegCount: legAmount, - signer, - offChainLegIndices: [], - instructionInfo: mockExecuteInfo, - }); - - const expectedError = new PolymeshError({ - code: ErrorCode.ValidationError, - message: 'The signer is not a mediator that has already affirmed the instruction', - }); - - return expect( - prepareModifyInstructionAffirmation.call(proc, { - id, - operation: InstructionAffirmationOperation.WithdrawAsMediator, // NOSONAR - }) - ).rejects.toThrow(expectedError); - }); - - it('should return a withdraw as mediator instruction transaction spec', async () => { - dsMockUtils.configureMocks({ - contextOptions: { - isV7: true, - }, - }); - const rawAffirmationStatus = createMockMediatorAffirmationStatus({ - Affirmed: dsMockUtils.createMockOption(), - }); - dsMockUtils.createQueryMock('settlement', 'instructionMediatorsAffirmations', { - returnValue: rawAffirmationStatus, - }); - when(mediatorAffirmationStatusToStatusSpy) - .calledWith(rawAffirmationStatus) - .mockReturnValue({ status: AffirmationStatus.Affirmed }); - - const proc = procedureMockUtils.getInstance< - ModifyInstructionAffirmationParams, - Instruction, - Storage - >(mockContext, { - allowedAssetHolders: [portfolio, portfolio], - assetHolderParams: [], - senderLegCount: legAmount, - totalLegCount: legAmount, - signer, - offChainLegIndices: [], - instructionInfo: mockExecuteInfo, - }); - - const transaction = dsMockUtils.createTxMock( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - 'settlement' as any, - 'withdrawAffirmationAsMediator' - ); - - const result = await prepareModifyInstructionAffirmation.call(proc, { - id, - operation: InstructionAffirmationOperation.WithdrawAsMediator, // NOSONAR - }); - - expect(result).toEqual({ - transaction, - args: [rawInstructionId], - resolver: expect.objectContaining({ id }), - }); - }); - it('should return a reject instruction transaction spec', async () => { const rawAffirmationStatus = dsMockUtils.createMockAffirmationStatus('Pending'); dsMockUtils.createQueryMock('settlement', 'affirmsReceived', { @@ -1193,16 +943,6 @@ describe('modifyInstructionAffirmation procedure', () => { }, }); - result = boundFunc({ ...args, operation: InstructionAffirmationOperation.Withdraw }); - - expect(result).toEqual({ - permissions: { - assets: [], - portfolios: [], - transactions: [TxTags.settlement.WithdrawAffirmationWithCount], - }, - }); - result = boundFunc({ ...args, operation: InstructionAffirmationOperation.AffirmAsMediator, @@ -1216,19 +956,6 @@ describe('modifyInstructionAffirmation procedure', () => { }, }); - result = boundFunc({ - ...args, - operation: InstructionAffirmationOperation.WithdrawAsMediator, // NOSONAR - }); - - expect(result).toEqual({ - permissions: { - assets: [], - portfolios: [], - transactions: [TxTags.settlement.WithdrawAffirmationAsMediator], - }, - }); - result = boundFunc({ ...args, operation: InstructionAffirmationOperation.RejectAsMediator, @@ -1345,22 +1072,6 @@ describe('modifyInstructionAffirmation procedure', () => { instructionInfo: mockExecuteInfo, }); - result = await boundFunc({ - id: new BigNumber(1), - operation: InstructionAffirmationOperation.Withdraw, // NOSONAR - holders: [fromDid], - }); - - expect(result).toEqual({ - allowedAssetHolders: [], - assetHolderParams: [fromDid], - senderLegCount: new BigNumber(0), - totalLegCount: new BigNumber(3), - signer: expect.objectContaining({ did: signer.did }), - offChainLegIndices: [2], - instructionInfo: mockExecuteInfo, - }); - result = await boundFunc({ id: new BigNumber(1), operation: InstructionAffirmationOperation.Reject, diff --git a/src/api/procedures/__tests__/modifyMultiSig.ts b/src/api/procedures/__tests__/modifyMultiSig.ts index 48093016d3..5e795ca303 100644 --- a/src/api/procedures/__tests__/modifyMultiSig.ts +++ b/src/api/procedures/__tests__/modifyMultiSig.ts @@ -75,7 +75,6 @@ describe('modifyMultiSig procedure', () => { when(signerToSignatorySpy).calledWith(newSigner1, mockContext).mockReturnValue('newOne'); when(signerToSignatorySpy).calledWith(newSigner2, mockContext).mockReturnValue('newTwo'); - // for v7 tests when(stringToAccountIdSpy) .calledWith(oldSigner1.address, mockContext) .mockReturnValue(rawOldSigner1); diff --git a/src/api/procedures/__tests__/nftControllerTransfer.ts b/src/api/procedures/__tests__/nftControllerTransfer.ts index bebd1b9407..809d4edc23 100644 --- a/src/api/procedures/__tests__/nftControllerTransfer.ts +++ b/src/api/procedures/__tests__/nftControllerTransfer.ts @@ -315,30 +315,7 @@ describe('nftControllerTransfer procedure', () => { ); }); - it('should give preference to destination when both destination and destinationPortfolio are provided', async () => { - const proc = procedureMockUtils.getInstance(mockContext); - const boundFunc = prepareStorage.bind(proc); - - when(assetHolderLikeToAssetHolderSpy) - .calledWith(destinationAccount, mockContext) - .mockReturnValue(destinationAccount); - const result = await boundFunc({ - collection, - originPortfolio, - nfts, - destinationPortfolio, - destination: destinationAccount, - }); - - expect(JSON.stringify(result)).toEqual( - JSON.stringify({ - did: 'someDid', - destinationAssetHolder: destinationAccount, - }) - ); - }); - - it('should return the default portfolio if destinationPortfolio is not provided', async () => { + it('should return the default portfolio if destination is not provided', async () => { mockContext.getSigningIdentity.mockResolvedValue( entityMockUtils.getIdentityInstance({ did: signerDid }) ); diff --git a/src/api/procedures/__tests__/quitSubsidy.ts b/src/api/procedures/__tests__/quitSubsidy.ts index 1e18d69026..448ce8dcdf 100644 --- a/src/api/procedures/__tests__/quitSubsidy.ts +++ b/src/api/procedures/__tests__/quitSubsidy.ts @@ -89,31 +89,6 @@ describe('quitSubsidy procedure', () => { }); }); - it('should return a removePayingKey transaction spec when chain is v7', async () => { - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); - - const rawBeneficiaryAccountId = dsMockUtils.createMockAccountId('beneficiary'); - const rawSubsidizerAccountId = dsMockUtils.createMockAccountId('subsidizer'); - when(stringToAccountIdSpy) - .calledWith('beneficiary', mockContext) - .mockReturnValue(rawBeneficiaryAccountId); - when(stringToAccountIdSpy) - .calledWith('subsidizer', mockContext) - .mockReturnValue(rawSubsidizerAccountId); - - const removePayingKeyTransaction = dsMockUtils.createTxMock('relayer', 'removePayingKey'); - - const proc = procedureMockUtils.getInstance(mockContext); - - const result = await prepareQuitSubsidy.call(proc, args); - - expect(result).toEqual({ - transaction: removePayingKeyTransaction, - args: [rawBeneficiaryAccountId, rawSubsidizerAccountId], - resolver: undefined, - }); - }); - describe('getAuthorization', () => { it('should return the appropriate roles and permissions', async () => { const proc = procedureMockUtils.getInstance(mockContext); diff --git a/src/api/procedures/__tests__/revokeSubsidy.ts b/src/api/procedures/__tests__/revokeSubsidy.ts index 5bf2ea8f1b..04443d4d02 100644 --- a/src/api/procedures/__tests__/revokeSubsidy.ts +++ b/src/api/procedures/__tests__/revokeSubsidy.ts @@ -54,24 +54,9 @@ describe('revokeSubsidy procedure', () => { dsMockUtils.cleanup(); }); - it('should throw NotSupported when chain is v7', () => { - dsMockUtils.configureMocks({ - contextOptions: { - isV7: true, - }, - }); - - const proc = procedureMockUtils.getInstance(mockContext); - - return expect(prepareRevokeSubsidy.call(proc, args)).rejects.toThrow( - 'This method is not supported for chain 7.x.' - ); - }); - it('should throw an error if no pending subsidy exists', () => { dsMockUtils.configureMocks({ contextOptions: { - isV7: false, getPendingSubsidies: [], }, }); @@ -83,10 +68,9 @@ describe('revokeSubsidy procedure', () => { ); }); - it('should return a revokeSubsidy transaction spec when chain is v8 and subsidy is pending', async () => { + it('should return a revokeSubsidy transaction spec when a subsidy is pending', async () => { dsMockUtils.configureMocks({ contextOptions: { - isV7: false, getPendingSubsidies: [ { allowance: new BigNumber(100), diff --git a/src/api/procedures/__tests__/selfRegisterDid.ts b/src/api/procedures/__tests__/selfRegisterDid.ts index 2741c9a078..6e6aab1d57 100644 --- a/src/api/procedures/__tests__/selfRegisterDid.ts +++ b/src/api/procedures/__tests__/selfRegisterDid.ts @@ -24,7 +24,7 @@ describe('selfRegisterDid procedure', () => { }); beforeEach(() => { - mockContext = dsMockUtils.getContextInstance({ isV7: false }); + mockContext = dsMockUtils.getContextInstance(); selfRegisterDidTransaction = dsMockUtils.createTxMock('identity', 'selfRegisterDid'); proc = procedureMockUtils.getInstance(mockContext); }); @@ -53,18 +53,6 @@ describe('selfRegisterDid procedure', () => { }); }); - it('should throw if called for chain v7', () => { - mockContext = dsMockUtils.getContextInstance({ isV7: true }); - proc = procedureMockUtils.getInstance(mockContext); - - const expectedError = new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'selfRegisterDid is only supported in chain v8', - }); - - return expect(prepareSelfRegisterDid.call(proc)).rejects.toThrow(expectedError); - }); - it('should throw if the signing Account already has an Identity', () => { const actingAccount = entityMockUtils.getAccountInstance({ getIdentity: entityMockUtils.getIdentityInstance(), diff --git a/src/api/procedures/__tests__/setMandatoryReceiverAffirmation.ts b/src/api/procedures/__tests__/setMandatoryReceiverAffirmation.ts index 1a3de43005..723bec8777 100644 --- a/src/api/procedures/__tests__/setMandatoryReceiverAffirmation.ts +++ b/src/api/procedures/__tests__/setMandatoryReceiverAffirmation.ts @@ -37,7 +37,7 @@ describe('setMandatoryReceiverAffirmation procedure', () => { }); beforeEach(() => { - mockContext = dsMockUtils.getContextInstance({ isV7: false }); + mockContext = dsMockUtils.getContextInstance(); mockSigningIdentity = entityMockUtils.getIdentityInstance({ did: 'someDid' }); mockContext.getSigningIdentity.mockResolvedValue(mockSigningIdentity); @@ -63,20 +63,6 @@ describe('setMandatoryReceiverAffirmation procedure', () => { dsMockUtils.cleanup(); }); - it('should throw a NotSupported error when called on a v7 chain', () => { - const proc = procedureMockUtils.getInstance(mockContext, { - identity: mockSigningIdentity, - }); - mockContext.isV7 = true; - - return expect( - prepareSetMandatoryReceiverAffirmation.call(proc, { - did: 'someDid', - requirement: ReceiverAffirmationRequirement.Required, - }) - ).rejects.toThrow('setMandatoryReceiverAffirmation is not supported on v7 chains'); - }); - it('should throw a NoDataChange error when setting Required and it is already Required', () => { const proc = procedureMockUtils.getInstance(mockContext, { identity: mockSigningIdentity, diff --git a/src/api/procedures/__tests__/setStakingController.ts b/src/api/procedures/__tests__/setStakingController.ts index 6a41de33ed..816edacef9 100644 --- a/src/api/procedures/__tests__/setStakingController.ts +++ b/src/api/procedures/__tests__/setStakingController.ts @@ -1,10 +1,8 @@ import { AccountId } from '@polkadot/types/interfaces'; import BigNumber from 'bignumber.js'; -import { when } from 'jest-when'; import { getAuthorization, - Params, prepareSetStakingController, prepareStorage, Storage, @@ -12,10 +10,9 @@ import { import { Account, Context, PolymeshError } from '~/internal'; import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; import { Mocked } from '~/testUtils/types'; -import { ErrorCode, StakingLedger } from '~/types'; +import { ErrorCode } from '~/types'; import { PolymeshTx } from '~/types/internal'; import { DUMMY_ACCOUNT_ID } from '~/utils/constants'; -import * as utilsConversionModule from '~/utils/conversion'; describe('setStakingController procedure', () => { beforeAll(() => { @@ -25,15 +22,10 @@ describe('setStakingController procedure', () => { }); let currentController: Account; - let newControllerLedger: StakingLedger; let mockContext: Mocked; let setControllerTx: PolymeshTx<[AccountId]>; let actingAccount: Account; - let newController: Account; - let rawAccountId: AccountId; - - let stringToAccountIdSpy: jest.SpyInstance; let storage: Storage; @@ -41,29 +33,11 @@ describe('setStakingController procedure', () => { setControllerTx = dsMockUtils.createTxMock('staking', 'setController'); mockContext = dsMockUtils.getContextInstance(); actingAccount = entityMockUtils.getAccountInstance({ address: DUMMY_ACCOUNT_ID }); - newController = entityMockUtils.getAccountInstance({ - address: '5FvreMigHtY1c6XTzDccjn8SVLiAeHz58z4MV4reJYyrdmj3', - }); - rawAccountId = dsMockUtils.createMockAccountId(newController.address); - - stringToAccountIdSpy = jest.spyOn(utilsConversionModule, 'stringToAccountId'); - - when(stringToAccountIdSpy) - .calledWith(newController.address, mockContext) - .mockReturnValue(rawAccountId); currentController = entityMockUtils.getAccountInstance(); - newControllerLedger = { - stash: entityMockUtils.getAccountInstance(), - total: new BigNumber(0), - active: new BigNumber(0), - unlocking: [], - claimedRewards: [], - }; storage = { actingAccount, currentController, - newControllerLedger: null, }; }); @@ -78,26 +52,8 @@ describe('setStakingController procedure', () => { dsMockUtils.cleanup(); }); - it('should throw an error if the target is already a controller', () => { - const proc = procedureMockUtils.getInstance(mockContext, { - ...storage, - newControllerLedger, - }); - - const expectedError = new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'The given controller is already paired with a stash', - }); - - expect(() => - prepareSetStakingController.call(proc, { - controller: newController, - }) - ).toThrow(expectedError); - }); - it('should throw an error if the the acting account is not a stash', () => { - const proc = procedureMockUtils.getInstance(mockContext, { + const proc = procedureMockUtils.getInstance(mockContext, { ...storage, currentController: null, }); @@ -107,25 +63,16 @@ describe('setStakingController procedure', () => { message: 'Current controller not found. The acting account must be a stash account', }); - expect(() => - prepareSetStakingController.call(proc, { - controller: newController, - }) - ).toThrow(expectedError); + expect(() => prepareSetStakingController.call(proc)).toThrow(expectedError); }); it('should return a setController transaction spec', async () => { - const proc = procedureMockUtils.getInstance(mockContext, { + const proc = procedureMockUtils.getInstance(mockContext, { actingAccount, currentController, - newControllerLedger: null, }); - const args = { - controller: newController, - }; - - const result = await prepareSetStakingController.call(proc, args); + const result = await prepareSetStakingController.call(proc); expect(result).toEqual({ transaction: setControllerTx, @@ -134,36 +81,9 @@ describe('setStakingController procedure', () => { }); }); - it('should return a v7 setController transaction spec with controller arg', async () => { - mockContext = dsMockUtils.getContextInstance({ isV7: true }); - setControllerTx = dsMockUtils.createTxMock('staking', 'setController'); - - when(stringToAccountIdSpy) - .calledWith(newController.address, mockContext) - .mockReturnValue(rawAccountId); - - const proc = procedureMockUtils.getInstance(mockContext, { - actingAccount, - currentController, - newControllerLedger: null, - }); - - const args = { - controller: newController, - }; - - const result = await prepareSetStakingController.call(proc, args); - - expect(result).toEqual({ - transaction: setControllerTx, - args: [rawAccountId], - resolver: undefined, - }); - }); - describe('getAuthorization', () => { it('should return the appropriate roles and permissions', () => { - const proc = procedureMockUtils.getInstance(mockContext, storage); + const proc = procedureMockUtils.getInstance(mockContext, storage); const boundFunc = getAuthorization.bind(proc); expect(boundFunc()).toEqual({ @@ -184,18 +104,13 @@ describe('setStakingController procedure', () => { }); mockContext.getActingAccount.mockResolvedValue(actingAccount); - const proc = procedureMockUtils.getInstance(mockContext); + const proc = procedureMockUtils.getInstance(mockContext); const boundFunc = prepareStorage.bind(proc); - return expect( - boundFunc({ - controller: entityMockUtils.getAccountInstance(), - }) - ).resolves.toEqual( + return expect(boundFunc()).resolves.toEqual( expect.objectContaining({ actingAccount: expect.objectContaining({ address: 'someAddress' }), currentController: expect.objectContaining({ address: 'currentController' }), - newControllerLedger: null, }) ); }); diff --git a/src/api/procedures/__tests__/subsidizeAccount.ts b/src/api/procedures/__tests__/subsidizeAccount.ts index 02e0a1a171..4bfc7e2d8b 100644 --- a/src/api/procedures/__tests__/subsidizeAccount.ts +++ b/src/api/procedures/__tests__/subsidizeAccount.ts @@ -7,10 +7,10 @@ import { prepareSubsidizeAccount, subsidizeAccount, } from '~/api/procedures/subsidizeAccount'; -import { Account, AuthorizationRequest, Context, Procedure } from '~/internal'; +import { Account, Context, Procedure } from '~/internal'; import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; import { Mocked } from '~/testUtils/types'; -import { AuthorizationType, Identity, ResultSet, SubsidyWithAllowance } from '~/types'; +import { SubsidyWithAllowance } from '~/types'; import * as utilsConversionModule from '~/utils/conversion'; jest.mock( @@ -21,12 +21,10 @@ jest.mock( describe('subsidizeAccount procedure', () => { let mockContext: Mocked; - let signerToStringSpy: jest.SpyInstance; let stringToAccountIdSpy: jest.SpyInstance; let bigNumberToBalanceSpy: jest.SpyInstance; let args: Params; - const authId = new BigNumber(1); const address = 'beneficiary'; const allowance = new BigNumber(1000); let beneficiary: Account; @@ -38,7 +36,6 @@ describe('subsidizeAccount procedure', () => { procedureMockUtils.initMocks(); entityMockUtils.initMocks(); - signerToStringSpy = jest.spyOn(utilsConversionModule, 'signerToString'); stringToAccountIdSpy = jest.spyOn(utilsConversionModule, 'stringToAccountId'); // @ts-expect-error - mock bigNumberToBalanceSpy = jest.spyOn(utilsConversionModule, 'bigNumberToBalance'); @@ -46,7 +43,7 @@ describe('subsidizeAccount procedure', () => { beforeEach(() => { mockContext = dsMockUtils.getContextInstance(); - args = { beneficiary: address, allowance, isV7Method: false }; + args = { beneficiary: address, allowance }; beneficiary = entityMockUtils.getAccountInstance({ address }); when(stringToAccountIdSpy) @@ -73,185 +70,9 @@ describe('subsidizeAccount procedure', () => { dsMockUtils.cleanup(); }); - it('should throw an error if the subsidizer has already sent a pending authorization to beneficiary Account with the same allowance to accept in v7', () => { - const sentAuthorizations: ResultSet = { - data: [ - new AuthorizationRequest( - { - target: beneficiary, - issuer: entityMockUtils.getIdentityInstance(), - authId, - expiry: null, - data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - value: { - beneficiary, - subsidizer: entityMockUtils.getAccountInstance(), - allowance: new BigNumber(1000), - }, - }, - }, - mockContext - ), - ], - next: null, - count: new BigNumber(1), - }; - - dsMockUtils.configureMocks({ - contextOptions: { - sentAuthorizations, - isV7: true, - }, - }); - - when(signerToStringSpy).calledWith(beneficiary).mockReturnValue(address); - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const proc = procedureMockUtils.getInstance(mockContext); - - return expect( - prepareSubsidizeAccount.call(proc, { ...args, isV7Method: true }) - ).rejects.toThrow( - 'The Beneficiary Account already has a pending invitation to add this account as a subsidizer' - ); - }); - - it('should return an add authorization transaction spec for v7 chain', async () => { - const mockBeneficiary = entityMockUtils.getAccountInstance({ address: 'mockAddress' }); - const issuer = entityMockUtils.getIdentityInstance(); - const subsidizer = entityMockUtils.getAccountInstance(); - - const sentAuthorizations: ResultSet = { - data: [ - new AuthorizationRequest( - { - target: mockBeneficiary, - issuer, - authId, - expiry: null, - data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - value: { - beneficiary: mockBeneficiary, - subsidizer, - allowance: new BigNumber(100), - }, - }, - }, - mockContext - ), - new AuthorizationRequest( - { - target: beneficiary, - issuer: entityMockUtils.getIdentityInstance(), - authId, - expiry: null, - data: { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - value: { - beneficiary, - subsidizer, - allowance: new BigNumber(100), - }, - }, - }, - mockContext - ), - ], - next: null, - count: new BigNumber(2), - }; - - dsMockUtils.configureMocks({ - contextOptions: { - sentAuthorizations, - isV7: true, - }, - }); - - rawBeneficiaryAccount = dsMockUtils.createMockAccountId(address); - - rawAllowance = dsMockUtils.createMockBalance(allowance); - - when(stringToAccountIdSpy) - .calledWith(address, mockContext) - .mockReturnValue(rawBeneficiaryAccount); - - when(bigNumberToBalanceSpy).calledWith(allowance, mockContext).mockReturnValue(rawAllowance); - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const proc = procedureMockUtils.getInstance(mockContext); - - const transaction = dsMockUtils.createTxMock('relayer', 'setPayingKey'); - - const result = await prepareSubsidizeAccount.call(proc, { - ...args, - beneficiary, - isV7Method: true, - }); - - expect(result).toEqual({ - transaction, - args: [rawBeneficiaryAccount, rawAllowance], - resolver: expect.any(Function), - }); - }); - - it('should throw NotSupported when isV7Method is true but chain is v8', () => { - dsMockUtils.configureMocks({ - contextOptions: { - isV7: false, - sentAuthorizations: { data: [], next: null, count: new BigNumber(0) }, - }, - }); - - rawBeneficiaryAccount = dsMockUtils.createMockAccountId(address); - rawAllowance = dsMockUtils.createMockBalance(allowance); - - when(stringToAccountIdSpy) - .calledWith(address, mockContext) - .mockReturnValue(rawBeneficiaryAccount); - when(bigNumberToBalanceSpy).calledWith(allowance, mockContext).mockReturnValue(rawAllowance); - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const proc = procedureMockUtils.getInstance(mockContext); - - return expect( - prepareSubsidizeAccount.call(proc, { ...args, beneficiary, isV7Method: true }) - ).rejects.toThrow( - 'This method is no longer supported for chain 8.x. Use approveSubsidy instead' - ); - }); - - it('should throw NotSupported when isV7Method is false but chain is v7', () => { - dsMockUtils.configureMocks({ - contextOptions: { - isV7: true, - sentAuthorizations: { data: [], next: null, count: new BigNumber(0) }, - }, - }); - - rawBeneficiaryAccount = dsMockUtils.createMockAccountId(address); - rawAllowance = dsMockUtils.createMockBalance(allowance); - - when(stringToAccountIdSpy) - .calledWith(address, mockContext) - .mockReturnValue(rawBeneficiaryAccount); - when(bigNumberToBalanceSpy).calledWith(allowance, mockContext).mockReturnValue(rawAllowance); - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const proc = procedureMockUtils.getInstance(mockContext); - - return expect( - prepareSubsidizeAccount.call(proc, { ...args, beneficiary, isV7Method: false }) - ).rejects.toThrow('This method is not supported for chain 7.x. Use subsidizeAccount instead'); - }); - it('should throw an error if a pending subsidy already exists with same amount', () => { dsMockUtils.configureMocks({ contextOptions: { - isV7: false, getPendingSubsidies: [ { allowance: new BigNumber(1000), @@ -263,17 +84,14 @@ describe('subsidizeAccount procedure', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const proc = procedureMockUtils.getInstance(mockContext); - return expect( - prepareSubsidizeAccount.call(proc, { ...args, isV7Method: false }) - ).rejects.toThrow( + return expect(prepareSubsidizeAccount.call(proc, args)).rejects.toThrow( 'The Beneficiary Account already has a pending subsidy for acceptance with the same allowance' ); }); - it('should return an approveSubsidy transaction spec when chain is v8', async () => { + it('should return an approveSubsidy transaction spec', async () => { dsMockUtils.configureMocks({ contextOptions: { - isV7: false, getPendingSubsidies: [ { allowance: new BigNumber(0), @@ -298,7 +116,6 @@ describe('subsidizeAccount procedure', () => { const result = await prepareSubsidizeAccount.call(proc, { ...args, beneficiary, - isV7Method: false, }); expect(result).toEqual({ diff --git a/src/api/procedures/__tests__/transferPolyx.ts b/src/api/procedures/__tests__/transferPolyx.ts index e06d5754e2..36d16b3c6d 100644 --- a/src/api/procedures/__tests__/transferPolyx.ts +++ b/src/api/procedures/__tests__/transferPolyx.ts @@ -88,37 +88,6 @@ describe('transferPolyx procedure', () => { expect(result.preRunValidation).toBeDefined(); }); - it('should return a v7 transferWithMemo transaction spec when isV7 and memo is provided', async () => { - mockContext = dsMockUtils.getContextInstance({ isV7: true }); - const to = entityMockUtils.getAccountInstance({ address: 'someAccount' }); - const amount = new BigNumber(99); - const memo = 'someMessage'; - const rawAccount = dsMockUtils.createMockAccountId(to.address); - const rawAmount = dsMockUtils.createMockBalance(amount); - const rawMemo = 'memo' as unknown as PolymeshPrimitivesMemo; - - jest.spyOn(utilsConversionModule, 'stringToAccountId').mockReturnValue(rawAccount); - jest.spyOn(utilsConversionModule, 'bigNumberToBalance').mockReturnValue(rawAmount); - jest.spyOn(utilsConversionModule, 'stringToMemo').mockReturnValue(rawMemo); - - const proc = procedureMockUtils.getInstance(mockContext); - - const tx = dsMockUtils.createTxMock('balances', 'transferWithMemo'); - - const result = await prepareTransferPolyx.call(proc, { - to, - amount, - memo, - }); - - expect(result).toMatchObject({ - transaction: tx, - args: [rawAccount, rawAmount, rawMemo], - resolver: undefined, - }); - expect(result.preRunValidation).toBeDefined(); - }); - describe('preRunValidation', () => { it('should check signing account balance when asProposal is false', async () => { const amount = new BigNumber(101); diff --git a/src/api/procedures/__tests__/unlinkChildIdentity.ts b/src/api/procedures/__tests__/unlinkChildIdentity.ts deleted file mode 100644 index f7a62d51c5..0000000000 --- a/src/api/procedures/__tests__/unlinkChildIdentity.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { PolymeshPrimitivesIdentityId } from '@polkadot/types/lookup'; -import { when } from 'jest-when'; - -import { ChildIdentity } from '~/api/entities/Identity/ChildIdentity'; -import { - getAuthorization, - prepareStorage, - prepareUnlinkChildIdentity, - Storage, -} from '~/api/procedures/unlinkChildIdentity'; -import { Context, Identity } from '~/internal'; -import { dsMockUtils, entityMockUtils, procedureMockUtils } from '~/testUtils/mocks'; -import { Mocked } from '~/testUtils/types'; -import { Account, TxTags, UnlinkChildParams } from '~/types'; -import * as utilsConversionModule from '~/utils/conversion'; - -jest.mock( - '~/api/entities/Identity/ChildIdentity', - require('~/testUtils/mocks/entities').mockChildIdentityModule( - '~/api/entities/Identity/ChildIdentity' - ) -); - -describe('unlinkChildIdentity procedure', () => { - let mockContext: Mocked; - let identity: Identity; - let actingAccount: Account; - let childIdentity: ChildIdentity; - let rawChildIdentity: PolymeshPrimitivesIdentityId; - let stringToIdentityIdSpy: jest.SpyInstance; - - beforeAll(() => { - dsMockUtils.initMocks(); - procedureMockUtils.initMocks(); - entityMockUtils.initMocks(); - - stringToIdentityIdSpy = jest.spyOn(utilsConversionModule, 'stringToIdentityId'); - }); - - beforeEach(() => { - actingAccount = entityMockUtils.getAccountInstance({ - address: 'actingAccount', - }); - identity = entityMockUtils.getIdentityInstance({ - getPrimaryAccount: { - account: actingAccount, - }, - }); - - childIdentity = entityMockUtils.getChildIdentityInstance({ - did: 'someChild', - getParentDid: identity, - }); - rawChildIdentity = dsMockUtils.createMockIdentityId(childIdentity.did); - - mockContext = dsMockUtils.getContextInstance({ - getIdentity: identity, - isV7: true, - }); - - when(stringToIdentityIdSpy) - .calledWith(childIdentity.did, mockContext) - .mockReturnValue(rawChildIdentity); - }); - - afterEach(() => { - entityMockUtils.reset(); - procedureMockUtils.reset(); - dsMockUtils.reset(); - }); - - afterAll(() => { - jest.resetAllMocks(); - procedureMockUtils.cleanup(); - dsMockUtils.cleanup(); - }); - - it("should throw an error if the child Identity doesn't exists ", () => { - const child = entityMockUtils.getChildIdentityInstance({ - did: 'randomDid', - getParentDid: null, - }); - - const proc = procedureMockUtils.getInstance(mockContext, { - identity, - actingAccount, - }); - - return expect( - prepareUnlinkChildIdentity.call(proc, { - child, - }) - ).rejects.toThrow("The `child` doesn't have a parent identity"); - }); - - it('should throw NotSupported when the chain is not v7', () => { - mockContext = dsMockUtils.getContextInstance({ isV7: false }); - - const proc = procedureMockUtils.getInstance(mockContext, { - identity, - actingAccount, - }); - - return expect(prepareUnlinkChildIdentity.call(proc, { child: childIdentity })).rejects.toThrow( - 'Child identities are no longer supported in chain v8' - ); - }); - - it('should throw an error if the signing Identity is neither the parent nor child', () => { - const child = entityMockUtils.getChildIdentityInstance({ - did: 'randomChild', - getParentDid: entityMockUtils.getIdentityInstance({ did: 'randomParent' }), - }); - - const proc = procedureMockUtils.getInstance(mockContext, { - identity, - actingAccount, - }); - - return expect( - prepareUnlinkChildIdentity.call(proc, { - child, - }) - ).rejects.toThrow( - 'Only the parent or the child identity is authorized to unlink a child identity' - ); - }); - - it('should add a create unlinkChildIdentity transaction to the queue', async () => { - const proc = procedureMockUtils.getInstance(mockContext, { - identity, - actingAccount, - }); - - const unlinkChildIdentityTransaction = dsMockUtils.createTxMock( - 'identity', - 'unlinkChildIdentity' - ); - - const result = await prepareUnlinkChildIdentity.call(proc, { - child: childIdentity, - }); - - expect(result).toEqual({ - transaction: unlinkChildIdentityTransaction, - args: [rawChildIdentity], - resolver: undefined, - }); - }); - - describe('getAuthorization', () => { - it('should return the appropriate roles and permissions', async () => { - let proc = procedureMockUtils.getInstance(mockContext, { - identity, - actingAccount, - }); - let boundFunc = getAuthorization.bind(proc); - - let result = await boundFunc(); - expect(result).toEqual({ - permissions: { - transactions: [TxTags.identity.UnlinkChildIdentity], - assets: [], - portfolios: [], - }, - }); - - identity = entityMockUtils.getIdentityInstance({ - getPrimaryAccount: { - account: entityMockUtils.getAccountInstance({ - address: 'differentAddress', - }), - }, - }); - - proc = procedureMockUtils.getInstance( - dsMockUtils.getContextInstance(), - { identity, actingAccount } - ); - - boundFunc = getAuthorization.bind(proc); - - result = await boundFunc(); - expect(result).toEqual({ - signerPermissions: - 'Child identity can only be unlinked by primary key of either the child Identity or parent Identity', - }); - }); - }); - - describe('prepareStorage', () => { - it('should return the signing Identity', async () => { - const proc = procedureMockUtils.getInstance(mockContext); - const boundFunc = prepareStorage.bind(proc); - - const result = await boundFunc(); - - expect(result).toEqual({ - identity: expect.objectContaining({ - did: 'someDid', - }), - actingAccount: expect.objectContaining({ - address: '0xdummy', - }), - }); - }); - }); -}); diff --git a/src/api/procedures/__tests__/updateVenueSigners.ts b/src/api/procedures/__tests__/updateVenueSigners.ts index b19d2d56e7..c667925fae 100644 --- a/src/api/procedures/__tests__/updateVenueSigners.ts +++ b/src/api/procedures/__tests__/updateVenueSigners.ts @@ -137,33 +137,6 @@ describe('updateVenueSigners procedure', () => { }); }); - it('should use stringToAccountId per signer when chain is v7', async () => { - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); - - const rawId = dsMockUtils.createMockU64(venueId); - const rawAddSigners = dsMockUtils.createMockBool(args.addSigners); - const rawSigner = dsMockUtils.createMockAccountId(args.signers[0] as string); - - jest.spyOn(utilsConversionModule, 'bigNumberToU64').mockReturnValue(rawId); - jest.spyOn(utilsConversionModule, 'stringToAccountId').mockReturnValue(rawSigner); - jest.spyOn(utilsConversionModule, 'booleanToBool').mockReturnValue(rawAddSigners); - - const updateVenueSignersTransaction = dsMockUtils.createTxMock( - 'settlement', - 'updateVenueSigners' - ); - - const proc = procedureMockUtils.getInstance(mockContext); - - const result = await prepareUpdateVenueSigners.call(proc, args); - - expect(result).toEqual({ - transaction: updateVenueSignersTransaction, - args: [rawId, [rawSigner], rawAddSigners], - resolver: undefined, - }); - }); - describe('getAuthorization', () => { it('should return the appropriate roles and permissions', () => { const proc = procedureMockUtils.getInstance(mockContext); diff --git a/src/api/procedures/__tests__/utils.ts b/src/api/procedures/__tests__/utils.ts index e4c6236d96..4504eb3ff6 100644 --- a/src/api/procedures/__tests__/utils.ts +++ b/src/api/procedures/__tests__/utils.ts @@ -1113,7 +1113,7 @@ describe('authorization request validations', () => { }); it('should throw when the issuer lacks a valid CDD', () => { - const mockIssuer = entityMockUtils.getIdentityInstance({ hasValidCdd: false }); + const mockIssuer = entityMockUtils.getIdentityInstance({ exists: false }); const auth = new AuthorizationRequest( { authId: new BigNumber(1), @@ -1136,7 +1136,7 @@ describe('authorization request validations', () => { }); it('should throw when the target is an Identity', () => { - const mockIssuer = entityMockUtils.getIdentityInstance({ hasValidCdd: true }); + const mockIssuer = entityMockUtils.getIdentityInstance({ exists: true }); const mockTarget = entityMockUtils.getIdentityInstance(); const auth = new AuthorizationRequest( { @@ -1160,7 +1160,7 @@ describe('authorization request validations', () => { }); it('should throw if the target already has an Identity', () => { - const mockIssuer = entityMockUtils.getIdentityInstance({ hasValidCdd: true }); + const mockIssuer = entityMockUtils.getIdentityInstance({ exists: true }); const mockTarget = entityMockUtils.getAccountInstance({ getIdentity: entityMockUtils.getIdentityInstance({ isEqual: false }), }); @@ -1186,7 +1186,7 @@ describe('authorization request validations', () => { }); it('should not throw if the target is already associated to the identity', () => { - const mockIssuer = entityMockUtils.getIdentityInstance({ hasValidCdd: true }); + const mockIssuer = entityMockUtils.getIdentityInstance({ exists: true }); const mockTarget = entityMockUtils.getAccountInstance({ getIdentity: entityMockUtils.getIdentityInstance({ isEqual: true }), }); @@ -1205,11 +1205,11 @@ describe('authorization request validations', () => { }); }); - describe('assertAddRelayerPayingKeyAuthorizationValid', () => { + describe('assertOldAddRelayerPayingKeyAuthorizationValid', () => { const allowance = new BigNumber(100); it('should not throw with a valid request', () => { const subsidizer = entityMockUtils.getAccountInstance({ - getIdentity: entityMockUtils.getIdentityInstance({ hasValidCdd: true }), + getIdentity: entityMockUtils.getIdentityInstance({ exists: true }), }); const beneficiary = entityMockUtils.getAccountInstance({ getIdentity: target }); @@ -1239,12 +1239,11 @@ describe('authorization request validations', () => { }); it('should throw with a beneficiary that does not have a CDD Claim', () => { - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); const subsidizer = entityMockUtils.getAccountInstance({ getIdentity: entityMockUtils.getIdentityInstance(), }); const beneficiary = entityMockUtils.getAccountInstance({ - getIdentity: entityMockUtils.getIdentityInstance({ hasValidCdd: false }), + getIdentity: entityMockUtils.getIdentityInstance({ exists: false }), }); const subsidy = { @@ -1254,7 +1253,7 @@ describe('authorization request validations', () => { remaining: allowance, }; const data: Authorization = { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: subsidy, }; const auth = new AuthorizationRequest( @@ -1279,14 +1278,13 @@ describe('authorization request validations', () => { }); it('should throw with a Subsidizer that does not have a CDD Claim', () => { - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); const beneficiary = entityMockUtils.getAccountInstance({ - getIdentity: entityMockUtils.getIdentityInstance({ hasValidCdd: true }), + getIdentity: entityMockUtils.getIdentityInstance({ exists: true }), }); // getIdentityInstance modifies the prototype, which prevents two mocks from returning different values const subsidizer = { getIdentity: () => { - return { hasValidCdd: (): boolean => false }; + return { exists: (): boolean => false }; }, } as unknown as Account; @@ -1297,7 +1295,7 @@ describe('authorization request validations', () => { remaining: allowance, }; const data: Authorization = { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: subsidy, }; const auth = new AuthorizationRequest( @@ -1322,9 +1320,8 @@ describe('authorization request validations', () => { }); it('should throw with a beneficiary that does not have an Identity', () => { - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); const subsidizer = entityMockUtils.getAccountInstance({ - getIdentity: entityMockUtils.getIdentityInstance({ hasValidCdd: false }), + getIdentity: entityMockUtils.getIdentityInstance({ exists: false }), }); const beneficiary = entityMockUtils.getAccountInstance({ getIdentity: null }); @@ -1335,7 +1332,7 @@ describe('authorization request validations', () => { remaining: allowance, }; const data: Authorization = { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: subsidy, }; const auth = new AuthorizationRequest( @@ -1359,9 +1356,8 @@ describe('authorization request validations', () => { }); it('should throw with a Subsidizer that does not have an Identity', () => { - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); const beneficiary = entityMockUtils.getAccountInstance({ - getIdentity: entityMockUtils.getIdentityInstance({ hasValidCdd: true }), + getIdentity: entityMockUtils.getIdentityInstance({ exists: true }), }); // getIdentityInstance modifies the prototype, which prevents two mocks from returning different values const subsidizer = { @@ -1375,7 +1371,7 @@ describe('authorization request validations', () => { remaining: allowance, }; const data: Authorization = { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: subsidy, }; const auth = new AuthorizationRequest( @@ -1562,7 +1558,7 @@ describe('authorization request validations', () => { }); it('should throw when the issuer lacks a valid CDD', () => { - const noCddIssuer = entityMockUtils.getIdentityInstance({ hasValidCdd: false }); + const noCddIssuer = entityMockUtils.getIdentityInstance({ exists: false }); const auth = new AuthorizationRequest( { authId: new BigNumber(1), @@ -1585,7 +1581,7 @@ describe('authorization request validations', () => { }); it('should throw when the target is an Identity', () => { - const mockIssuer = entityMockUtils.getIdentityInstance({ hasValidCdd: true }); + const mockIssuer = entityMockUtils.getIdentityInstance({ exists: true }); const identityTarget = entityMockUtils.getIdentityInstance(); const auth = new AuthorizationRequest( { @@ -1609,7 +1605,7 @@ describe('authorization request validations', () => { }); it('should throw if the target already has an Identity', () => { - const mockIssuer = entityMockUtils.getIdentityInstance({ hasValidCdd: true }); + const mockIssuer = entityMockUtils.getIdentityInstance({ exists: true }); const unavailableTarget = entityMockUtils.getAccountInstance({ getIdentity: entityMockUtils.getIdentityInstance({ isEqual: false }), }); @@ -1655,14 +1651,14 @@ describe('authorization request validations', () => { describe('assertValidCdd', () => { it('should resolve if the identity has a valid CDD claim', () => { const context = dsMockUtils.getContextInstance(); - const identity = entityMockUtils.getIdentityInstance({ hasValidCdd: true }); + const identity = entityMockUtils.getIdentityInstance({ exists: true }); return expect(assertValidCdd(identity, context)).resolves.not.toThrow(); }); it('should throw an error if the identity does not have a valid CDD claim', () => { const context = dsMockUtils.getContextInstance(); - const identity = entityMockUtils.getIdentityInstance({ hasValidCdd: false }); + const identity = entityMockUtils.getIdentityInstance({ exists: false }); const expectedError = new PolymeshError({ code: ErrorCode.UnmetPrerequisite, diff --git a/src/api/procedures/acceptPrimaryKeyRotation.ts b/src/api/procedures/acceptPrimaryKeyRotation.ts index 44aa66c4fc..5eefda2df7 100644 --- a/src/api/procedures/acceptPrimaryKeyRotation.ts +++ b/src/api/procedures/acceptPrimaryKeyRotation.ts @@ -1,11 +1,10 @@ import BigNumber from 'bignumber.js'; import { assertAuthorizationRequestValid } from '~/api/procedures/utils'; -import { AuthorizationRequest, PolymeshError, Procedure } from '~/internal'; -import { AcceptPrimaryKeyRotationParams, AuthorizationType, ErrorCode } from '~/types'; +import { AuthorizationRequest, Procedure } from '~/internal'; +import { AcceptPrimaryKeyRotationParams, AuthorizationType } from '~/types'; import { ExtrinsicParams, ProcedureAuthorization, TransactionSpec } from '~/types/internal'; import { bigNumberToU64 } from '~/utils/conversion'; -import { optionize } from '~/utils/internal'; /** * @hidden @@ -13,7 +12,6 @@ import { optionize } from '~/utils/internal'; export interface Storage { calledByTarget: boolean; ownerAuthRequest: AuthorizationRequest; - cddAuthRequest: AuthorizationRequest | undefined; } /** @@ -28,32 +26,14 @@ export async function prepareAcceptPrimaryKeyRotation( tx: { identity }, }, }, - storage: { ownerAuthRequest, cddAuthRequest }, + storage: { ownerAuthRequest }, context, } = this; - const validationPromises = [assertAuthorizationRequestValid(ownerAuthRequest, context)]; - if (cddAuthRequest) { - validationPromises.push(assertAuthorizationRequestValid(cddAuthRequest, context)); - } - - await Promise.all(validationPromises); + await assertAuthorizationRequestValid(ownerAuthRequest, context); const { authId: ownerAuthId, issuer } = ownerAuthRequest; - if (context.isV7) { - return { - transaction: identity.acceptPrimaryKey, - paidForBy: issuer, - args: [ - bigNumberToU64(ownerAuthId, context), - optionize(bigNumberToU64)(cddAuthRequest?.authId, context), - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ] as any, - resolver: undefined, - }; - } - return { transaction: identity.acceptPrimaryKey, paidForBy: issuer, @@ -84,19 +64,12 @@ export function getAuthorization( */ export async function prepareStorage( this: Procedure, - { ownerAuth, cddAuth }: AcceptPrimaryKeyRotationParams + { ownerAuth }: AcceptPrimaryKeyRotationParams ): Promise { const { context } = this; const actingAccount = await context.getActingAccount(); - if (!context.isV7 && cddAuth) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'CDD is discontinued since v8', - }); - } - const getAuthRequest = ( auth: BigNumber | AuthorizationRequest ): Promise => { @@ -108,18 +81,11 @@ export async function prepareStorage( const ownerAuthRequest = await getAuthRequest(ownerAuth); - let calledByTarget = actingAccount.isEqual(ownerAuthRequest.target); - - let cddAuthRequest; - if (cddAuth) { - cddAuthRequest = await getAuthRequest(cddAuth); - calledByTarget = calledByTarget && actingAccount.isEqual(cddAuthRequest.target); - } + const calledByTarget = actingAccount.isEqual(ownerAuthRequest.target); return { calledByTarget, ownerAuthRequest, - cddAuthRequest, }; } diff --git a/src/api/procedures/acceptSubsidy.ts b/src/api/procedures/acceptSubsidy.ts index 8d200b5cd6..106a69e25e 100644 --- a/src/api/procedures/acceptSubsidy.ts +++ b/src/api/procedures/acceptSubsidy.ts @@ -20,13 +20,6 @@ export async function prepareAcceptSubsidy( const { subsidizer } = args; - if (context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'This method is not supported for chain 7.x.', - }); - } - const subsidizerAccount = asAccount(subsidizer, context); const { address: subsidizerAddress } = subsidizerAccount; diff --git a/src/api/procedures/addInstruction.ts b/src/api/procedures/addInstruction.ts index 3055366f2a..bef7c5f5b3 100644 --- a/src/api/procedures/addInstruction.ts +++ b/src/api/procedures/addInstruction.ts @@ -9,11 +9,10 @@ import { } from '@polkadot/types/lookup'; import { ISubmittableResult } from '@polkadot/types/types'; import BigNumber from 'bignumber.js'; -import { flatten, isEqual, union, unionWith } from 'lodash'; +import { isEqual, union, unionWith } from 'lodash'; import { assertAssetHolderExists, - assertValidCdd, assertVenueExists, getAssetHolderDid, } from '~/api/procedures/utils'; @@ -187,26 +186,6 @@ export async function getRawLegDetails( assertAssetHolderExists(toId, context), ]; - if (context.isV7) { - const [fromDid, toDid] = await Promise.all([ - getAssetHolderDid(from, context), - getAssetHolderDid(to, context), - ]); - - if (!fromDid) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'From Asset Holder does not exist', - }); - } - if (!toDid) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'To Asset Holder does not exist', - }); - } - assertPromises.push(assertValidCdd(fromDid, context), assertValidCdd(toDid, context)); - } await Promise.all(assertPromises); const sender = await assetHolderIdToMeshAssetHolder(fromId, context); @@ -921,8 +900,6 @@ export async function prepareStorage( rawToHolder: PolymeshPrimitivesAssetAssetHolder, rawAssetId: ReturnType ): Promise => { - if (context.isV7) return false; - const requirement = await context.polymeshApi.call.settlementApi.getReceiverAffirmationRequirement( rawToHolder, @@ -964,7 +941,7 @@ export async function prepareStorage( return result; }) ); - return flatten(portfolios); + return portfolios.flat(); }) ); diff --git a/src/api/procedures/attestPrimaryKeyRotation.ts b/src/api/procedures/attestPrimaryKeyRotation.ts index de0eaa600a..677468e1e2 100644 --- a/src/api/procedures/attestPrimaryKeyRotation.ts +++ b/src/api/procedures/attestPrimaryKeyRotation.ts @@ -84,7 +84,7 @@ export const attestPrimaryKeyRotation = (): Procedure< AuthorizationRequest > => new Procedure(prepareAttestPrimaryKeyRotation, { - roles: [{ type: RoleType.CddProvider }], + roles: [{ type: RoleType.DidRegistrar }], permissions: { assets: [], portfolios: [], diff --git a/src/api/procedures/bondPolyx.ts b/src/api/procedures/bondPolyx.ts index dfc5701dcc..04d08d73be 100644 --- a/src/api/procedures/bondPolyx.ts +++ b/src/api/procedures/bondPolyx.ts @@ -1,7 +1,7 @@ import { PolymeshError, Procedure } from '~/internal'; import { Account, Balance, BondPolyxParams, ErrorCode } from '~/types'; import { ExtrinsicParams, ProcedureAuthorization, TransactionSpec } from '~/types/internal'; -import { bigNumberToBalance, stringToAccountId } from '~/utils/conversion'; +import { bigNumberToBalance } from '~/utils/conversion'; import { asAccount, calculateRawStakingPayee } from '~/utils/internal'; export interface Storage { @@ -63,7 +63,6 @@ export async function prepareBondPolyx( } const rawAmount = bigNumberToBalance(amount, context); - const rawController = stringToAccountId(controller.address, context); const rawPayee = await calculateRawStakingPayee( payee, actingAccount, @@ -72,21 +71,11 @@ export async function prepareBondPolyx( context ); - if (context.isV7) { - return { - transaction: bond, - args: [rawController, rawAmount, rawPayee], - resolver: undefined, - // v8 no longer allows controllers to be specified - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any; - } else { - return { - transaction: bond, - args: [rawAmount, rawPayee], - resolver: undefined, - }; - } + return { + transaction: bond, + args: [rawAmount, rawPayee], + resolver: undefined, + }; } /** diff --git a/src/api/procedures/consumeAddRelayerPayingKeyAuthorization.ts b/src/api/procedures/consumeAddRelayerPayingKeyAuthorization.ts deleted file mode 100644 index 479bad0c2f..0000000000 --- a/src/api/procedures/consumeAddRelayerPayingKeyAuthorization.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { assertAuthorizationRequestValid } from '~/api/procedures/utils'; -import { Account, AuthorizationRequest, Identity, PolymeshError, Procedure } from '~/internal'; -import { AuthorizationType, ErrorCode, TxTags } from '~/types'; -import { ExtrinsicParams, ProcedureAuthorization, TransactionSpec } from '~/types/internal'; -import { - bigNumberToU64, - booleanToBool, - signerToSignerValue, - signerValueToSignatory, -} from '~/utils/conversion'; - -/** - * @hidden - */ -export interface ConsumeAddRelayerPayingKeyAuthorizationParams { - authRequest: AuthorizationRequest; - accept: boolean; -} - -export interface Storage { - actingAccount: Account; - calledByTarget: boolean; -} - -/** - * @hidden - * - * Consumes AddRelayerPayingKey Authorizations - */ -export async function prepareConsumeAddRelayerPayingKeyAuthorization( - this: Procedure, - args: ConsumeAddRelayerPayingKeyAuthorizationParams -): Promise< - | TransactionSpec> - // eslint-disable-next-line @typescript-eslint/no-explicit-any - | TransactionSpec -> { - const { - context: { - polymeshApi: { - tx: { relayer, identity }, - }, - }, - storage: { calledByTarget }, - context, - } = this; - const { authRequest, accept } = args; - - const { - target, - authId, - issuer, - data: { type }, - } = authRequest; - - if ( - ![ - AuthorizationType.AddRelayerPayingKey, // NOSONAR - AuthorizationType.OldAddRelayerPayingKey, - ].includes(type) - ) { - throw new PolymeshError({ - code: ErrorCode.UnexpectedError, - message: `Unrecognized auth type: "${type}" for consumeAddRelayerPayingKeyAuthorization method`, - }); - } - - const rawAuthId = bigNumberToU64(authId, context); - - if (!accept) { - const baseArgs: { paidForBy?: Identity } = {}; - - if (calledByTarget) { - baseArgs.paidForBy = issuer; - } - - return { - transaction: identity.removeAuthorization, - ...baseArgs, - args: [ - signerValueToSignatory(signerToSignerValue(target), context), - rawAuthId, - booleanToBool(calledByTarget, context), - ], - resolver: undefined, - }; - } - - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'acceptPayingKey type authorization is not supported in chain 8.x', - }); - } - - await assertAuthorizationRequestValid(authRequest, context); - - return { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction: (relayer as any).acceptPayingKey, - paidForBy: issuer, - args: [rawAuthId], - resolver: undefined, - }; -} - -/** - * @hidden - * - * - If the auth is being accepted, we check that the caller is the target - * - If the auth is being rejected, we check that the caller is either the target or the issuer - */ -export async function getAuthorization( - this: Procedure, - { authRequest, accept }: ConsumeAddRelayerPayingKeyAuthorizationParams -): Promise { - const { issuer } = authRequest; - const { - storage: { actingAccount, calledByTarget }, - } = this; - let hasRoles = calledByTarget; - - if (accept) { - return { - roles: - hasRoles || - `"${AuthorizationType.AddRelayerPayingKey}" Authorization Requests must be accepted by the target Account`, - }; - } - - const identity = await actingAccount.getIdentity(); - - hasRoles = hasRoles || !!identity?.isEqual(issuer); - - return { - roles: - hasRoles || - `"${AuthorizationType.AddRelayerPayingKey}" Authorization Requests can only be removed by the issuer Identity or the target Account`, - permissions: { - transactions: [TxTags.identity.RemoveAuthorization], - }, - }; -} - -/** - * @hidden - */ -export async function prepareStorage( - this: Procedure, - { authRequest: { target } }: ConsumeAddRelayerPayingKeyAuthorizationParams -): Promise { - const { context } = this; - - // AddRelayerPayingKey Authorizations always target an Account - const targetAccount = target as Account; - const actingAccount = await context.getActingAccount(); - const calledByTarget = targetAccount.isEqual(actingAccount); - - return { - actingAccount, - calledByTarget, - }; -} - -/** - * @hidden - */ -export const consumeAddRelayerPayingKeyAuthorization = (): Procedure< - ConsumeAddRelayerPayingKeyAuthorizationParams, - void, - Storage -> => - new Procedure(prepareConsumeAddRelayerPayingKeyAuthorization, getAuthorization, prepareStorage); diff --git a/src/api/procedures/consumeJoinOrRotateAuthorization.ts b/src/api/procedures/consumeJoinOrRotateAuthorization.ts index 417c5c3e5e..efc2760783 100644 --- a/src/api/procedures/consumeJoinOrRotateAuthorization.ts +++ b/src/api/procedures/consumeJoinOrRotateAuthorization.ts @@ -103,16 +103,6 @@ export async function prepareConsumeJoinOrRotateAuthorization( ? identity.acceptPrimaryKey : identity.rotatePrimaryKeyToSecondary; - if (context.isV7) { - return { - transaction, - paidForBy: issuer, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - args: [rawAuthId, null] as any, - resolver: undefined, - }; - } - return { transaction, paidForBy: issuer, diff --git a/src/api/procedures/createChildIdentities.ts b/src/api/procedures/createChildIdentities.ts deleted file mode 100644 index d3015cd5cd..0000000000 --- a/src/api/procedures/createChildIdentities.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { ISubmittableResult } from '@polkadot/types/types'; - -import { ChildIdentity, Context, Identity, PolymeshError, Procedure } from '~/internal'; -import { Account, CreateChildIdentitiesParams, ErrorCode, TxTags } from '~/types'; -import { ExtrinsicParams, ProcedureAuthorization, TransactionSpec } from '~/types/internal'; -import { - childKeysWithAuthToCreateChildIdentitiesWithAuth, - dateToMoment, - identityIdToString, -} from '~/utils/conversion'; -import { areSameAccounts, asAccount, filterEventRecords } from '~/utils/internal'; - -/** - * @hidden - */ -export interface Storage { - identity: Identity; - actingAccount: Account; -} - -/** - * @hidden - */ -export const createChildIdentityResolver = - (context: Context) => - (receipt: ISubmittableResult): ChildIdentity[] => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const childDids = filterEventRecords(receipt, 'identity' as any, 'ChildDidCreated'); - - return childDids.map( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ({ data }) => new ChildIdentity({ did: identityIdToString(data[1] as any) }, context) // NOSONAR - ); - }; - -/** - * @hidden - */ -export async function prepareCreateChildIdentities( - this: Procedure, // NOSONAR - args: CreateChildIdentitiesParams -): Promise< - TransactionSpec< - ChildIdentity[], // NOSONAR - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ExtrinsicParams<'identity', any> - > -> { - const { - context: { - polymeshApi: { tx }, - }, - context, - storage: { - identity: { did: signingDid }, - }, - } = this; - - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'Child identities are no longer supported in chain v8', - }); - } - - const { childKeyAuths, expiresAt } = args; - - if (expiresAt <= new Date()) { - throw new PolymeshError({ - code: ErrorCode.ValidationError, - message: 'Expiry date must be in the future', - }); - } - - const childIdentity = new ChildIdentity({ did: signingDid }, context); - - const [parentDid, ...identities] = await Promise.all([ - childIdentity.getParentDid(), - ...childKeyAuths.map(({ key }) => asAccount(key, context).getIdentity()), - ]); - - if (parentDid) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: - 'The signing Identity is already a child Identity and cannot create further child identities', - data: { - parentDid, - }, - }); - } - - if (identities.some(identityValue => identityValue !== null)) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'One or more accounts are already linked to some Identity', - }); - } - - const rawExpiry = dateToMoment(expiresAt, context); - - return { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction: (tx.identity as any).createChildIdentities, - args: [childKeysWithAuthToCreateChildIdentitiesWithAuth(childKeyAuths, context), rawExpiry], - resolver: createChildIdentityResolver(context), - }; -} - -/** - * @hidden - */ -export async function getAuthorization( - this: Procedure // NOSONAR -): Promise { - const { - storage: { identity, actingAccount }, - } = this; - - const { account: primaryAccount } = await identity.getPrimaryAccount(); - - if (!areSameAccounts(actingAccount, primaryAccount)) { - return { - signerPermissions: "Child Identities can only be created by an Identity's primary Account", - }; - } - - return { - permissions: { - transactions: [TxTags.identity.CreateChildIdentities], - assets: [], - portfolios: [], - }, - }; -} - -/** - * @hidden - */ -export async function prepareStorage( - this: Procedure // NOSONAR -): Promise { - const { context } = this; - - const [identity, actingAccount] = await Promise.all([ - context.getSigningIdentity(), - context.getActingAccount(), - ]); - - return { - identity, - actingAccount, - }; -} - -/** - * @hidden - */ -export const createChildIdentities = (): Procedure< - CreateChildIdentitiesParams, - ChildIdentity[], // NOSONAR - Storage -> => new Procedure(prepareCreateChildIdentities, getAuthorization, prepareStorage); diff --git a/src/api/procedures/createChildIdentity.ts b/src/api/procedures/createChildIdentity.ts deleted file mode 100644 index eeb93989e7..0000000000 --- a/src/api/procedures/createChildIdentity.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { ISubmittableResult } from '@polkadot/types/types'; - -import { ChildIdentity, Context, Identity, PolymeshError, Procedure } from '~/internal'; -import { Account, CreateChildIdentityParams, ErrorCode, TxTags } from '~/types'; -import { ExtrinsicParams, ProcedureAuthorization, TransactionSpec } from '~/types/internal'; -import { - boolToBoolean, - identityIdToString, - stringToAccountId, - stringToIdentityId, -} from '~/utils/conversion'; -import { areSameAccounts, asAccount, filterEventRecords } from '~/utils/internal'; - -/** - * @hidden - */ -export interface Storage { - identity: Identity; - actingAccount: Account; -} - -/** - * @hidden - */ -export const createChildIdentityResolver = - (context: Context) => - (receipt: ISubmittableResult): ChildIdentity => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const [record] = filterEventRecords(receipt, 'identity' as any, 'ChildDidCreated'); - - const { data } = record!; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const did = identityIdToString(data[1] as any); - - return new ChildIdentity({ did }, context); // NOSONAR - }; - -/** - * @hidden - */ -export async function prepareCreateChildIdentity( - this: Procedure< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage - >, - args: CreateChildIdentityParams -): Promise< - TransactionSpec< - ChildIdentity, // NOSONAR - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ExtrinsicParams<'identity', any> - > -> { - const { - context: { - polymeshApi: { tx, query }, - }, - context, - storage: { - identity: { did: signingDid }, - }, - } = this; - - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'Child identities are no longer supported in v8', - }); - } - - const { secondaryKey } = args; - - const childAccount = asAccount(secondaryKey, context); - - const rawIdentity = stringToIdentityId(signingDid, context); - const rawChildAccount = stringToAccountId(childAccount.address, context); - - const childIdentity = new ChildIdentity({ did: signingDid }, context); // NOSONAR - - const [isSecondaryKey, multiSig, parentDid] = await Promise.all([ - query.identity.didKeys(rawIdentity, rawChildAccount), - childAccount.getMultiSig(), - childIdentity.getParentDid(), // NOSONAR - ]); - - if (!boolToBoolean(isSecondaryKey)) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'The `secondaryKey` provided is not a secondary key of the signing Identity', - }); - } - - if (multiSig) { - const { total } = await multiSig.getBalance(); - - if (total.gt(0)) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: "The `secondaryKey` can't be unlinked from the signing Identity", - }); - } - } - - if (parentDid) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: - 'The signing Identity is already a child Identity and cannot create further child identities', - data: { - parentDid, - }, - }); - } - - return { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction: (tx.identity as any).createChildIdentity, - args: [rawChildAccount], - resolver: createChildIdentityResolver(context), - }; -} - -/** - * @hidden - */ -export async function getAuthorization( - this: Procedure< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage - > -): Promise { - const { - storage: { identity, actingAccount }, - } = this; - - const { account: primaryAccount } = await identity.getPrimaryAccount(); - - if (!areSameAccounts(actingAccount, primaryAccount)) { - return { - signerPermissions: "A child Identity can only be created by an Identity's primary Account", - }; - } - - return { - permissions: { - transactions: [TxTags.identity.CreateChildIdentity], - assets: [], - portfolios: [], - }, - }; -} - -/** - * @hidden - */ -export async function prepareStorage( - this: Procedure< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage - > -): Promise { - const { context } = this; - - const [identity, actingAccount] = await Promise.all([ - context.getSigningIdentity(), - context.getActingAccount(), - ]); - - return { - identity, - actingAccount, - }; -} - -/** - * @hidden - */ -export const createChildIdentity = (): Procedure< - CreateChildIdentityParams, - ChildIdentity, // NOSONAR - Storage -> => new Procedure(prepareCreateChildIdentity, getAuthorization, prepareStorage); diff --git a/src/api/procedures/createVenue.ts b/src/api/procedures/createVenue.ts index d3fd0a0383..56dafec4f8 100644 --- a/src/api/procedures/createVenue.ts +++ b/src/api/procedures/createVenue.ts @@ -5,7 +5,6 @@ import { CreateVenueParams, ErrorCode, TxTags } from '~/types'; import { ExtrinsicParams, TransactionSpec } from '~/types/internal'; import { addressesToBtreeSet, - stringToAccountId, stringToBytes, u32ToBigNumber, u64ToBigNumber, @@ -61,11 +60,7 @@ export function prepareCreateVenue( } const signerAddresses = signers.map(signer => asAccount(signer, context).address); - let accountArgs = addressesToBtreeSet(signerAddresses, context); - if (context.isV7) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - accountArgs = signerAddresses.map(address => stringToAccountId(address, context)) as any; - } + const accountArgs = addressesToBtreeSet(signerAddresses, context); return Promise.resolve({ transaction: settlement.createVenue, diff --git a/src/api/procedures/issueNft.ts b/src/api/procedures/issueNft.ts index f0bb966fe2..80988a23d7 100644 --- a/src/api/procedures/issueNft.ts +++ b/src/api/procedures/issueNft.ts @@ -26,13 +26,7 @@ export type Params = { export const issuedNftsResolver = (context: Context) => (receipt: ISubmittableResult): Nft[] => { - let records; - if (context.isV7) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - records = filterEventRecords(receipt, 'nft' as any, 'NFTPortfolioUpdated'); - } else { - records = filterEventRecords(receipt, 'nft', 'NFTHoldingsUpdated'); - } + const records = filterEventRecords(receipt, 'nft', 'NFTHoldingsUpdated'); return records.map(({ data }) => { const { assetId, ids } = meshNftToNftId(data[1] as PolymeshPrimitivesNftNfTs); diff --git a/src/api/procedures/modifyClaims.ts b/src/api/procedures/modifyClaims.ts index cc36e79939..acd1803b1b 100644 --- a/src/api/procedures/modifyClaims.ts +++ b/src/api/procedures/modifyClaims.ts @@ -3,7 +3,7 @@ import { PolymeshPrimitivesIdentityClaimClaim, PolymeshPrimitivesIdentityId, } from '@polkadot/types/lookup'; -import { groupBy, uniq } from 'lodash'; +import { groupBy } from 'lodash'; import { Context, Identity, PolymeshError, Procedure } from '~/internal'; import { claimsQuery } from '~/middleware/queries/claims'; @@ -141,7 +141,7 @@ export async function prepareModifyClaims( ); } - allTargets = uniq(allTargets); + allTargets = [...new Set(allTargets)]; const [nonExistentDids, middlewareAvailable] = await Promise.all([ context.getInvalidDids(allTargets), @@ -247,7 +247,7 @@ export function getAuthorization({ }; if (claims.some(({ claim: { type } }) => type === ClaimType.CustomerDueDiligence)) { return { - roles: [{ type: RoleType.CddProvider }], + roles: [{ type: RoleType.DidRegistrar }], permissions, }; } diff --git a/src/api/procedures/modifyInstructionAffirmation.ts b/src/api/procedures/modifyInstructionAffirmation.ts index c8e153f662..498da82f5c 100644 --- a/src/api/procedures/modifyInstructionAffirmation.ts +++ b/src/api/procedures/modifyInstructionAffirmation.ts @@ -93,8 +93,7 @@ const assertAssetHoldersAreValid = ( ): void => { if ( operation === InstructionAffirmationOperation.AffirmAsMediator || - operation === InstructionAffirmationOperation.RejectAsMediator || - operation === InstructionAffirmationOperation.WithdrawAsMediator + operation === InstructionAffirmationOperation.RejectAsMediator ) { // since no asset holders are involved in these operations, consider them as valid return; @@ -261,23 +260,6 @@ function validateMediatorStatusForAffirmation( } } -/** - * @hidden - */ -function validateMediatorStatusForWithdrawal( - mediatorStatus: AffirmationStatus, - signer: Identity, - id: BigNumber -): void { - if (mediatorStatus !== AffirmationStatus.Affirmed) { - throw new PolymeshError({ - code: ErrorCode.ValidationError, - message: 'The signer is not a mediator that has already affirmed the instruction', - data: { signer: signer.did, instructionId: id.toString() }, - }); - } -} - /** * */ @@ -410,10 +392,8 @@ export async function prepareModifyInstructionAffirmation( ): Promise< | TransactionSpec> | TransactionSpec> - | TransactionSpec> | TransactionSpec> | TransactionSpec> - | TransactionSpec> | TransactionSpec> > { const { @@ -479,24 +459,6 @@ export async function prepareModifyInstructionAffirmation( return affirmAsMediator(mediatorStatus, signer, context, instruction, args.expiry); } - case InstructionAffirmationOperation.WithdrawAsMediator: { - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'Withdrawal of affirmed instructions has been discontinued from v8 chain', - }); - } - - validateMediatorStatusForWithdrawal(mediatorStatus, signer, id); - - return { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction: (settlementTx as any).withdrawAffirmationAsMediator, - resolver: instruction, - args: [rawInstructionId], - }; - } - case InstructionAffirmationOperation.RejectAsMediator: { return rejectAsMediator(mediatorStatus, signer, context, instruction, instructionInfo); } @@ -519,23 +481,6 @@ export async function prepareModifyInstructionAffirmation( } break; } - - case InstructionAffirmationOperation.Withdraw: { - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'Withdrawal of affirmed instructions has been discontinued from v8 chain', - }); - } - await validateInstructionNotLocked(instruction); - - excludeCriteria.push(AffirmationStatus.Pending); - errorMessage = 'The instruction is not affirmed'; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction = (settlementTx as any).withdrawAffirmationWithCount; - - break; - } } const validAssetHolders = rawAllowedAssetHolders.filter( @@ -598,11 +543,6 @@ export function getAuthorization( break; } - case InstructionAffirmationOperation.Withdraw: { - transactions = [TxTags.settlement.WithdrawAffirmationWithCount]; - - break; - } case InstructionAffirmationOperation.Reject: { transactions = [TxTags.settlement.RejectInstructionWithCount]; @@ -613,11 +553,6 @@ export function getAuthorization( break; } - case InstructionAffirmationOperation.WithdrawAsMediator: { - transactions = [TxTags.settlement.WithdrawAffirmationAsMediator]; - - break; - } case InstructionAffirmationOperation.RejectAsMediator: { transactions = [TxTags.settlement.RejectInstructionAsMediator]; @@ -645,10 +580,7 @@ function extractAssetHolderParams(params: ModifyInstructionAffirmationParams): A if (portfolio) { assetHolderParams.push(portfolio); } - } else if ( - operation === InstructionAffirmationOperation.Affirm || - operation === InstructionAffirmationOperation.Withdraw - ) { + } else if (operation === InstructionAffirmationOperation.Affirm) { const { holders } = params; if (holders) { assetHolderParams = [...assetHolderParams, ...holders]; diff --git a/src/api/procedures/nftControllerTransfer.ts b/src/api/procedures/nftControllerTransfer.ts index fbdb629690..e01148a77f 100644 --- a/src/api/procedures/nftControllerTransfer.ts +++ b/src/api/procedures/nftControllerTransfer.ts @@ -129,21 +129,13 @@ export function getAuthorization( */ export async function prepareStorage( this: Procedure, - { - destinationPortfolio, // NOSONAR - destination, - }: Params + { destination }: Params ): Promise { const { context } = this; - let givenAssetHolder = destination; - if (!destination) { - givenAssetHolder = destinationPortfolio; - } - const { did } = await context.getSigningIdentity(); - const destinationAssetHolder = givenAssetHolder - ? assetHolderLikeToAssetHolder(givenAssetHolder, context) + const destinationAssetHolder = destination + ? assetHolderLikeToAssetHolder(destination, context) : new DefaultPortfolio({ did }, context); return { diff --git a/src/api/procedures/quitSubsidy.ts b/src/api/procedures/quitSubsidy.ts index bea602439d..37992bdab3 100644 --- a/src/api/procedures/quitSubsidy.ts +++ b/src/api/procedures/quitSubsidy.ts @@ -42,15 +42,6 @@ export async function prepareQuitSubsidy( const rawSubsidizerAccount = stringToAccountId(subsidizerAddress, context); - if (context.isV7) { - return { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction: (tx.relayer as any).removePayingKey, - args: [rawBeneficiaryAccount, rawSubsidizerAccount], - resolver: undefined, - }; - } - return { transaction: tx.relayer.removeSubsidy, args: [rawBeneficiaryAccount, rawSubsidizerAccount], diff --git a/src/api/procedures/registerIdentity.ts b/src/api/procedures/registerIdentity.ts index 040f5c7785..ce69285cbc 100644 --- a/src/api/procedures/registerIdentity.ts +++ b/src/api/procedures/registerIdentity.ts @@ -95,7 +95,7 @@ export async function prepareRegisterIdentity( */ export const registerIdentity = (): Procedure => new Procedure(prepareRegisterIdentity, { - roles: [{ type: RoleType.CddProvider }], + roles: [{ type: RoleType.DidRegistrar }], permissions: { assets: [], portfolios: [], diff --git a/src/api/procedures/revokeSubsidy.ts b/src/api/procedures/revokeSubsidy.ts index 6d80a01ced..8e99f326c1 100644 --- a/src/api/procedures/revokeSubsidy.ts +++ b/src/api/procedures/revokeSubsidy.ts @@ -20,13 +20,6 @@ export async function prepareRevokeSubsidy( const { beneficiary } = args; - if (context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'This method is not supported for chain 7.x.', - }); - } - const beneficiaryAccount = asAccount(beneficiary, context); const { address: beneficiaryAddress } = beneficiaryAccount; diff --git a/src/api/procedures/selfRegisterDid.ts b/src/api/procedures/selfRegisterDid.ts index 3b0398cdd4..95062c8eea 100644 --- a/src/api/procedures/selfRegisterDid.ts +++ b/src/api/procedures/selfRegisterDid.ts @@ -34,13 +34,6 @@ export async function prepareSelfRegisterDid( context, } = this; - if (context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'selfRegisterDid is only supported in chain v8', - }); - } - const actingAccount = await context.getActingAccount(); const identityExists = await actingAccount.getIdentity(); diff --git a/src/api/procedures/setMandatoryReceiverAffirmation.ts b/src/api/procedures/setMandatoryReceiverAffirmation.ts index 38c2fa3900..159caae360 100644 --- a/src/api/procedures/setMandatoryReceiverAffirmation.ts +++ b/src/api/procedures/setMandatoryReceiverAffirmation.ts @@ -35,13 +35,6 @@ export async function prepareSetMandatoryReceiverAffirmation( } = this; const { did, requirement } = args; - if (context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'setMandatoryReceiverAffirmation is not supported on v7 chains', - }); - } - const rawDid = stringToIdentityId(did, context); const rawCurrentValue = await query.settlement.mandatoryReceiverAffirmation(rawDid); diff --git a/src/api/procedures/setStakingController.ts b/src/api/procedures/setStakingController.ts index cbd7748506..b9064eaf3e 100644 --- a/src/api/procedures/setStakingController.ts +++ b/src/api/procedures/setStakingController.ts @@ -1,27 +1,18 @@ import { PolymeshError, Procedure } from '~/internal'; -import { Account, ErrorCode, SetStakingControllerParams, StakingLedger } from '~/types'; +import { Account, ErrorCode } from '~/types'; import { ExtrinsicParams, ProcedureAuthorization, TransactionSpec } from '~/types/internal'; -import { stringToAccountId } from '~/utils/conversion'; -import { asAccount } from '~/utils/internal'; export interface Storage { actingAccount: Account; currentController: Account | null; - newControllerLedger: StakingLedger | null; } -/** - * @hidden - */ -export type Params = SetStakingControllerParams; - /** * @hidden */ export function prepareSetStakingController( - this: Procedure, - args: Params + this: Procedure ): Promise>> { const { context: { @@ -31,23 +22,8 @@ export function prepareSetStakingController( }, }, }, - context, - storage: { actingAccount, currentController, newControllerLedger: targetLedger }, + storage: { actingAccount, currentController }, } = this; - const { controller: controllerInput } = args; - - const controller = asAccount(controllerInput, context); - - if (targetLedger) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'The given controller is already paired with a stash', - data: { - givenController: controller.address, - givenControllerStash: targetLedger.stash.address, - }, - }); - } if (!currentController) { throw new PolymeshError({ @@ -57,31 +33,19 @@ export function prepareSetStakingController( }); } - const rawController = stringToAccountId(controller.address, context); - - if (context.isV7) { - return Promise.resolve({ - transaction: setController, - args: [rawController], - resolver: undefined, - // v8 no longer allows for a controller to be specified - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any); - } else { - // This is now a no arg extrinsic - return Promise.resolve({ - transaction: setController, - args: undefined, - resolver: undefined, - }); - } + // This is a no arg extrinsic + return Promise.resolve({ + transaction: setController, + args: undefined, + resolver: undefined, + }); } /** * @hidden * @note the staking module is exempt from permission checks */ -export function getAuthorization(this: Procedure): ProcedureAuthorization { +export function getAuthorization(this: Procedure): ProcedureAuthorization { return { permissions: { assets: [], @@ -94,30 +58,21 @@ export function getAuthorization(this: Procedure): Proced /** * @hidden */ -export async function prepareStorage( - this: Procedure, - args: Params -): Promise { +export async function prepareStorage(this: Procedure): Promise { const { context } = this; - const targetController = asAccount(args.controller, context); - const actingAccount = await context.getActingAccount(); - const [currentController, newControllerLedger] = await Promise.all([ - actingAccount.staking.getController(), - targetController.staking.getLedger(), - ]); + const currentController = await actingAccount.staking.getController(); return { actingAccount, currentController, - newControllerLedger, }; } /** * @hidden */ -export const setStakingController = (): Procedure => +export const setStakingController = (): Procedure => new Procedure(prepareSetStakingController, getAuthorization, prepareStorage); diff --git a/src/api/procedures/subsidizeAccount.ts b/src/api/procedures/subsidizeAccount.ts index 17d34b0da9..1144832401 100644 --- a/src/api/procedures/subsidizeAccount.ts +++ b/src/api/procedures/subsidizeAccount.ts @@ -1,27 +1,18 @@ -import { createAuthorizationResolver } from '~/api/procedures/utils'; -import { AuthorizationRequest, PolymeshError, Procedure } from '~/internal'; -import { - AddRelayerPayingKeyAuthorizationData, - AuthorizationType, - ErrorCode, - SubsidizeAccountParams, -} from '~/types'; -import { TransactionSpec } from '~/types/internal'; -import { bigNumberToBalance, signerToString, stringToAccountId } from '~/utils/conversion'; +import { PolymeshError, Procedure } from '~/internal'; +import { ErrorCode, SubsidizeAccountParams } from '~/types'; +import { ExtrinsicParams, TransactionSpec } from '~/types/internal'; +import { bigNumberToBalance, stringToAccountId } from '~/utils/conversion'; import { asAccount } from '~/utils/internal'; -export type Params = SubsidizeAccountParams & { - isV7Method: boolean; -}; +export type Params = SubsidizeAccountParams; /** * @hidden */ export async function prepareSubsidizeAccount( - this: Procedure, + this: Procedure, args: Params - // eslint-disable-next-line @typescript-eslint/no-explicit-any -): Promise> { +): Promise>> { const { context: { polymeshApi: { tx }, @@ -35,73 +26,12 @@ export async function prepareSubsidizeAccount( const { address: beneficiaryAddress } = beneficiaryAccount; - const [identity, subsidizer] = await Promise.all([ - context.getSigningIdentity(), - context.getActingAccount(), - ]); + const subsidizer = await context.getActingAccount(); + const rawBeneficiary = stringToAccountId(beneficiaryAddress, context); const rawAllowance = bigNumberToBalance(allowance, context); - if (args.isV7Method) { - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'This method is no longer supported for chain 8.x. Use approveSubsidy instead', - }); - } - - const authorizationRequests = await identity.authorizations.getSent(); - - const hasPendingAuth = !!authorizationRequests.data.some(authorizationRequest => { - const { target, data } = authorizationRequest; - - return ( - signerToString(target) === beneficiaryAddress && - !authorizationRequest.isExpired() && - data.type === AuthorizationType.AddRelayerPayingKey && - data.value.allowance.isEqualTo(allowance) - ); - }); - - if (hasPendingAuth) { - throw new PolymeshError({ - code: ErrorCode.NoDataChange, - message: - 'The Beneficiary Account already has a pending invitation to add this account as a subsidizer with the same allowance', - }); - } - - const authRequest = { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - value: { - beneficiary: beneficiaryAccount, - subsidizer, - allowance, - }, - } as AddRelayerPayingKeyAuthorizationData; // NOSONAR - - return { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction: (tx.relayer as any).setPayingKey, - resolver: createAuthorizationResolver( - authRequest, - identity, - beneficiaryAccount, - null, - context - ), - args: [rawBeneficiary, rawAllowance], - }; - } - - if (context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'This method is not supported for chain 7.x. Use subsidizeAccount instead', - }); - } - const [existingPendingSubsidy] = await context.getPendingSubsidies(beneficiary, [subsidizer]); if (existingPendingSubsidy!.allowance.eq(allowance)) { @@ -122,8 +52,7 @@ export async function prepareSubsidizeAccount( /** * @hidden */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const subsidizeAccount = (): Procedure => +export const subsidizeAccount = (): Procedure => new Procedure(prepareSubsidizeAccount, { signerPermissions: true, }); diff --git a/src/api/procedures/transferPolyx.ts b/src/api/procedures/transferPolyx.ts index 3bc2a84811..57458cb077 100644 --- a/src/api/procedures/transferPolyx.ts +++ b/src/api/procedures/transferPolyx.ts @@ -54,34 +54,12 @@ export function prepareTransferPolyx( } }; - // istanbul ignore next: will be removed with v7 support - if (context.isV7) { - if (memo) { - return Promise.resolve({ - transaction: tx.balances.transferWithMemo, - args: [rawAccountId, rawAmount, stringToMemo(memo, context)], - resolver: undefined, - preRunValidation, - }); - } else { - return Promise.resolve({ - // a type cast is needed for v7 since v8 transfers always have a memo argument - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction: (tx.balances as any).transfer, - args: [rawAccountId, rawAmount], - resolver: undefined, - preRunValidation, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } as any); - } - } else { - return Promise.resolve({ - transaction: tx.balances.transferWithMemo, - args: [rawAccountId, rawAmount, optionize(stringToMemo)(memo, context)], - resolver: undefined, - preRunValidation, - }); - } + return Promise.resolve({ + transaction: tx.balances.transferWithMemo, + args: [rawAccountId, rawAmount, optionize(stringToMemo)(memo, context)], + resolver: undefined, + preRunValidation, + }); } /** diff --git a/src/api/procedures/types.ts b/src/api/procedures/types.ts index c14ca4692a..737e3cb083 100644 --- a/src/api/procedures/types.ts +++ b/src/api/procedures/types.ts @@ -5,7 +5,6 @@ import { Account, AuthorizationRequest, CheckpointSchedule, - ChildIdentity, CorporateActionBase, CorporateBallot, CustomPermissionGroup, @@ -272,10 +271,6 @@ export interface TxData { export enum RoleType { TickerOwner = 'TickerOwner', - /** - * @deprecated `CddProvider` role has been deprecated in favor of `DidRegistrar` role for chain v8 - */ - CddProvider = 'CddProvider', VenueOwner = 'VenueOwner', PortfolioCustodian = 'PortfolioCustodian', CorporateActionsAgent = 'CorporateActionsAgent', @@ -289,10 +284,6 @@ export interface TickerOwnerRole { ticker: string; } -export interface CddProviderRole { - type: RoleType.CddProvider; -} - export interface DidRegistrarRole { type: RoleType.DidRegistrar; } @@ -321,7 +312,6 @@ export interface IdentityRole { export type Role = | TickerOwnerRole - | CddProviderRole | VenueOwnerRole | PortfolioCustodianRole | IdentityRole @@ -708,11 +698,6 @@ export interface AcceptPrimaryKeyRotationParams { * Authorization from the owner who initiated the change */ ownerAuth: BigNumber | AuthorizationRequest; - /** - * (optional) Authorization from a CDD service provider attesting the rotation of primary key - * @deprecated this value will be ignored from chain v8 - */ - cddAuth?: BigNumber | AuthorizationRequest; } export interface ModifySignerPermissionsParams { @@ -1145,16 +1130,8 @@ export interface InstructionIdParams { export enum InstructionAffirmationOperation { Affirm = 'Affirm', - /** - * @deprecated withdrawing an affirmation is no longer supported in chain v8 - */ - Withdraw = 'Withdraw', Reject = 'Reject', AffirmAsMediator = 'AffirmAsMediator', - /** - * @deprecated withdrawing an affirmation as a mediator is no longer supported in chain v8 - */ - WithdrawAsMediator = 'WithdrawAsMediator', RejectAsMediator = 'RejectAsMediator', } @@ -1165,18 +1142,6 @@ export type RejectInstructionParams = { assetHolder?: AssetHolderLike; }; -/** - * @deprecated withdrawing affirmation is no longer supported in chain v8 - */ -export type WithdrawInstructionParams = { - /** - * (optional) Asset holders that the signer controls and wants to affirm the instruction or withdraw affirmation - * - * @note if empty, all the legs containing any custodied Asset Holders of the signer will be affirmed/affirmation will be withdrawn, based on the operation. - */ - holders?: AssetHolderLike[]; -}; - export enum SignerKeyRingType { Ed25519 = 'Ed25519', Sr25519 = 'Sr25519', @@ -1240,9 +1205,6 @@ export type ModifyInstructionAffirmationParams = InstructionIdParams & | ({ operation: InstructionAffirmationOperation.Affirm; } & AffirmInstructionParams) - | ({ - operation: InstructionAffirmationOperation.Withdraw; - } & WithdrawInstructionParams) | ({ operation: InstructionAffirmationOperation.Reject; } & RejectInstructionParams) @@ -1250,9 +1212,7 @@ export type ModifyInstructionAffirmationParams = InstructionIdParams & operation: InstructionAffirmationOperation.AffirmAsMediator; } & AffirmAsMediatorParams) | { - operation: - | InstructionAffirmationOperation.WithdrawAsMediator - | InstructionAffirmationOperation.RejectAsMediator; + operation: InstructionAffirmationOperation.RejectAsMediator; } ); @@ -1302,17 +1262,8 @@ export interface NftControllerTransferParams { */ nfts: (Nft | BigNumber)[]; - /** - * Optional portfolio (or portfolio ID) to which NFTs will be transferred to. Defaults to default portfolio. If specified it must be one of the callers own portfolios - * - * @deprecated in favour of `destination`. If both are passed `destination` will take precedence - */ - destinationPortfolio?: PortfolioLike; - /** * (optional) portfolio (or portfolio ID) or account to which Assets will be transferred to. Defaults to default portfolio. If specified it must be one of the callers own portfolios or accounts - * - * @note this takes precedence over `destinationPortfolio` */ destination?: AssetHolderLike; } @@ -1872,7 +1823,7 @@ export interface CreateTransactionBatchParams, - args: UnlinkChildParams - // eslint-disable-next-line @typescript-eslint/no-explicit-any -): Promise>> { - const { - context: { - polymeshApi: { tx }, - }, - context, - storage: { - identity: { did: signingDid }, - }, - } = this; - - if (!context.isV7) { - throw new PolymeshError({ - code: ErrorCode.NotSupported, - message: 'Child identities are no longer supported in chain v8', - }); - } - - const { child } = args; - - const childIdentity = asChildIdentity(child, context); - - const parentIdentity = await childIdentity.getParentDid(); - - if (!parentIdentity) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: "The `child` doesn't have a parent identity", - }); - } - - const { did: parentDid } = parentIdentity; - const { did: childDid } = childIdentity; - - if (![parentDid, childDid].includes(signingDid)) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'Only the parent or the child identity is authorized to unlink a child identity', - }); - } - - return { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - transaction: (tx.identity as any).unlinkChildIdentity, - args: [stringToIdentityId(childDid, context)], - resolver: undefined, - }; -} - -/** - * @hidden - */ -export async function getAuthorization( - this: Procedure -): Promise { - const { - storage: { identity, actingAccount }, - } = this; - - const { account: primaryAccount } = await identity.getPrimaryAccount(); - - if (!areSameAccounts(actingAccount, primaryAccount)) { - return { - signerPermissions: - 'Child identity can only be unlinked by primary key of either the child Identity or parent Identity', - }; - } - - return { - permissions: { - transactions: [TxTags.identity.UnlinkChildIdentity], - assets: [], - portfolios: [], - }, - }; -} - -/** - * @hidden - */ -export async function prepareStorage( - this: Procedure -): Promise { - const { context } = this; - - const [identity, actingAccount] = await Promise.all([ - context.getSigningIdentity(), - context.getActingAccount(), - ]); - - return { - identity, - actingAccount, - }; -} - -/** - * @hidden - */ -export const unlinkChildIdentity = (): Procedure => - new Procedure(prepareUnlinkChildIdentity, getAuthorization, prepareStorage); diff --git a/src/api/procedures/updateVenueSigners.ts b/src/api/procedures/updateVenueSigners.ts index 2a209419e5..104d0489b8 100644 --- a/src/api/procedures/updateVenueSigners.ts +++ b/src/api/procedures/updateVenueSigners.ts @@ -7,7 +7,6 @@ import { addressesToBtreeSet, bigNumberToU64, booleanToBool, - stringToAccountId, u32ToBigNumber, } from '~/utils/conversion'; import { asAccount } from '~/utils/internal'; @@ -77,11 +76,7 @@ export async function prepareUpdateVenueSigners( } } - let accountArgs = addressesToBtreeSet(signerParams, context); - if (context.isV7) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - accountArgs = signerParams.map(signer => stringToAccountId(signer, context)) as any; - } + const accountArgs = addressesToBtreeSet(signerParams, context); return { transaction: settlement.updateVenueSigners, diff --git a/src/api/procedures/utils.ts b/src/api/procedures/utils.ts index 9aace1ae4f..01629ea959 100644 --- a/src/api/procedures/utils.ts +++ b/src/api/procedures/utils.ts @@ -515,13 +515,8 @@ export async function assertMultiSigSignerAuthorizationValid( * Asserts valid add relayer paying key authorization */ export async function assertOldAddRelayerPayingKeyAuthorizationValid( - subsidy: SubsidyData, - context: Context + subsidy: SubsidyData ): Promise { - if (!context.isV7) { - return; - } - const [beneficiaryIdentity, subsidizerIdentity] = await Promise.all([ subsidy.beneficiary.getIdentity(), subsidy.subsidizer.getIdentity(), @@ -541,19 +536,19 @@ export async function assertOldAddRelayerPayingKeyAuthorizationValid( }); } - const [isBeneficiaryCddValid, isSubsidizerCddValid] = await Promise.all([ - beneficiaryIdentity.hasValidCdd(), - subsidizerIdentity.hasValidCdd(), + const [beneficiaryExists, subsidizerExists] = await Promise.all([ + beneficiaryIdentity.exists(), + subsidizerIdentity.exists(), ]); - if (!isBeneficiaryCddValid) { + if (!beneficiaryExists) { throw new PolymeshError({ code: ErrorCode.UnmetPrerequisite, message: 'Beneficiary Account does not have a valid CDD Claim', }); } - if (!isSubsidizerCddValid) { + if (!subsidizerExists) { throw new PolymeshError({ code: ErrorCode.UnmetPrerequisite, message: 'Subsidizer Account does not have a valid CDD Claim', @@ -584,8 +579,8 @@ async function assertJoinOrRotateAuthorizationValid( authRequest: AuthorizationRequest ): Promise { const { issuer, target } = authRequest; - const hasValidCdd = await issuer.hasValidCdd(); - if (!hasValidCdd) { + const issuerExists = await issuer.exists(); + if (!issuerExists) { throw new PolymeshError({ code: ErrorCode.UnmetPrerequisite, message: 'Issuing Identity does not have a valid CDD claim', @@ -662,9 +657,8 @@ export async function assertAuthorizationRequestValid( return; case AuthorizationType.JoinIdentity: return assertJoinOrRotateAuthorizationValid(authRequest); - case AuthorizationType.AddRelayerPayingKey: case AuthorizationType.OldAddRelayerPayingKey: - return assertOldAddRelayerPayingKeyAuthorizationValid(data.value, context); + return assertOldAddRelayerPayingKeyAuthorizationValid(data.value); case AuthorizationType.RotatePrimaryKeyToSecondary: return assertJoinOrRotateAuthorizationValid(authRequest); default: @@ -677,9 +671,9 @@ export async function assertAuthorizationRequestValid( */ export async function assertValidCdd(identity: string | Identity, context: Context): Promise { const id = asIdentity(identity, context); - const validCdd = await id.hasValidCdd(); + const identityExists = await id.exists(); - if (!validCdd) { + if (!identityExists) { throw new PolymeshError({ code: ErrorCode.UnmetPrerequisite, message: 'The identity does not have a valid CDD claim', diff --git a/src/base/Context.ts b/src/base/Context.ts index b9e16fc90f..b85cdf0d39 100644 --- a/src/base/Context.ts +++ b/src/base/Context.ts @@ -8,7 +8,7 @@ import { import { ApiPromise } from '@polkadot/api'; import { UnsubscribePromise } from '@polkadot/api/types'; import { getTypeDef, Option } from '@polkadot/types'; -import { AccountInfo, Header } from '@polkadot/types/interfaces'; +import { Header } from '@polkadot/types/interfaces'; import { FrameSystemAccountInfo, PalletCorporateActionsCaId, @@ -19,14 +19,13 @@ import { import { CallFunction, Codec, DetectCodec, Signer as PolkadotSigner } from '@polkadot/types/types'; import { SigningManager } from '@polymeshassociation/signing-manager-types'; import BigNumber from 'bignumber.js'; -import { chunk, clone, flatten, flattenDeep } from 'lodash'; +import { chunk, clone, flattenDeep } from 'lodash'; import { gte } from 'semver'; import { HistoricPolyxTransaction } from '~/api/entities/Account/types'; import { processType } from '~/base/utils'; import { Account, - ChildIdentity, DividendDistribution, FungibleAsset, Identity, @@ -99,7 +98,6 @@ import { delay, getApiAtBlock, getLatestSqVersion, - isV7Spec, } from '~/utils/internal'; interface ConstructorParams { @@ -136,8 +134,6 @@ export class Context { private _isArchiveNodeResult?: boolean; - public isV7 = false; - public isSqIdPadded = false; public specVersion: number; @@ -158,13 +154,10 @@ export class Context { this.specVersion = polymeshApi.runtimeVersion.specVersion.toNumber(); this.specName = polymeshApi.runtimeVersion.specName.toString(); - this.isV7 = isV7Spec(this.specVersion); this.unsubChainVersion = polymeshApi.query.system.lastRuntimeUpgrade(upgrade => { - /* istanbul ignore next: this will be removed after dual version support for v7-v8 */ if (upgrade.isSome) { this.specVersion = upgrade.unwrap().specVersion.toNumber(); - this.isV7 = isV7Spec(this.specVersion); } }); } @@ -328,11 +321,11 @@ export class Context { const accounts = await signingManager.getAccounts(); - const newSigningAddress = accounts.find(account => { + const hasSigningAddress = accounts.some(account => { return account === address; }); - if (!newSigningAddress) { + if (!hasSigningAddress) { throw new PolymeshError({ code: ErrorCode.General, message: 'The Account is not part of the Signing Manager attached to the SDK', @@ -374,28 +367,7 @@ export class Context { const rawAddress = stringToAccountId(address, this); - // istanbul ignore next: will be removed with v7 support - const legacyAssembleResult = ({ - data: { free: rawFree, miscFrozen, feeFrozen, reserved: rawReserved }, - }: AccountInfo): AccountBalance => { - /* - * On v7 chains, frozen funds are carved out of the chain's "free" balance, so the spendable - * balance is the free balance minus the largest freeze, minus anything reserved - */ - const reserved = balanceToBigNumber(rawReserved); - const total = balanceToBigNumber(rawFree).plus(reserved); - const frozen = BigNumber.max(balanceToBigNumber(miscFrozen), balanceToBigNumber(feeFrozen)); - const free = total.minus(frozen).minus(reserved); - return { - total, - locked: total.minus(free), - free, - reserved, - frozen, - }; - }; - - const v8AssembleResult = ({ data }: FrameSystemAccountInfo): AccountBalance => { + const assembleResult = ({ data }: FrameSystemAccountInfo): AccountBalance => { const { free: rawFree, frozen: rawFrozen, reserved: rawReserved } = data; const { consts: { @@ -426,11 +398,6 @@ export class Context { }; }; - // istanbul ignore next: will be removed with v7 support - const assembleResult = this.isV7 - ? (legacyAssembleResult as unknown as typeof v8AssembleResult) - : v8AssembleResult; - if (callback) { this.assertSupportsSubscription(); @@ -724,30 +691,6 @@ export class Context { return id; } - /** - * @hidden - * - * Returns an Child Identity when given a DID string - * - * @throws if the Child Identity does not exist - */ - public async getChildIdentity(child: ChildIdentity | string): Promise { - if (child instanceof ChildIdentity) { - return child; - } - const childIdentity = new ChildIdentity({ did: child }, this); - const exists = await childIdentity.exists(); - - if (!exists) { - throw new PolymeshError({ - code: ErrorCode.DataUnavailable, - message: 'The passed DID does not correspond to an on-chain child Identity', - }); - } - - return childIdentity; - } - /** * @hidden * @@ -903,7 +846,7 @@ export class Context { corporateActionQuery.corporateActions.entries(assetToMeshAssetId(assetValue, this)) ) ); - const eligibleCas = flatten(corporateActions).filter(([, action]) => { + const eligibleCas = corporateActions.flat().filter(([, action]) => { const kind = action.unwrap().kind; return kind.isUnpredictableBenefit || kind.isPredictableBenefit; diff --git a/src/base/__tests__/Context.ts b/src/base/__tests__/Context.ts index 9386371a62..97bc3a3321 100644 --- a/src/base/__tests__/Context.ts +++ b/src/base/__tests__/Context.ts @@ -40,12 +40,6 @@ jest.mock( '~/api/entities/Identity', require('~/testUtils/mocks/entities').mockIdentityModule('~/api/entities/Identity') ); -jest.mock( - '~/api/entities/Identity/ChildIdentity', - require('~/testUtils/mocks/entities').mockChildIdentityModule( - '~/api/entities/Identity/ChildIdentity' - ) -); jest.mock( '~/api/entities/Account', require('~/testUtils/mocks/entities').mockAccountModule('~/api/entities/Account') @@ -84,7 +78,7 @@ describe('Context class', () => { beforeEach(() => { polymeshApi = dsMockUtils.getApiInstance(); - // These `any` casts can be removed with v7 support + // These `any` casts allow mocking runtimeVersion fields /* eslint-disable @typescript-eslint/no-explicit-any */ (polymeshApi as any).runtimeVersion.specVersion = dsMockUtils.createMockU64(); (polymeshApi as any).runtimeVersion.specName = dsMockUtils.createMockText(); @@ -215,8 +209,8 @@ describe('Context class', () => { const result = await context.getSigningAccounts(); expect(result[0]!.address).toBe(addresses[0]); expect(result[1]!.address).toBe(addresses[1]); - expect(result[0] instanceof Account).toBe(true); - expect(result[1] instanceof Account).toBe(true); + expect(result[0]).toBeInstanceOf(Account); + expect(result[1]).toBeInstanceOf(Account); }); it('should return an empty array if signing manager is not set', async () => { @@ -1065,76 +1059,6 @@ describe('Context class', () => { }); }); - describe('method: getChildIdentity', () => { - beforeAll(() => { - jest.spyOn(utilsInternalModule, 'assertAddressValid').mockImplementation(); - }); - - afterAll(() => { - jest.restoreAllMocks(); - }); - - const childDid = 'someChild'; - - it('should return an ChildIdentity if given an ChildIdentity', async () => { - entityMockUtils.configureMocks({ - childIdentityOptions: { - did: childDid, - }, - }); - const context = await Context.create({ - polymeshApi, - middlewareApiV2: dsMockUtils.getMiddlewareApi(), - }); - - const childIdentity = entityMockUtils.getChildIdentityInstance(); - const result = await context.getChildIdentity(childIdentity); - expect(result).toEqual(expect.objectContaining({ did: childDid })); - }); - - it('should return an ChildIdentity if given a valid child DID', async () => { - entityMockUtils.configureMocks({ - childIdentityOptions: { - did: childDid, - exists: true, - }, - }); - const context = await Context.create({ - polymeshApi, - middlewareApiV2: dsMockUtils.getMiddlewareApi(), - }); - - const result = await context.getChildIdentity(childDid); - expect(result).toEqual(expect.objectContaining({ did: childDid })); - }); - - it('should throw if the ChildIdentity does not exist', async () => { - const context = await Context.create({ - polymeshApi, - middlewareApiV2: dsMockUtils.getMiddlewareApi(), - }); - - entityMockUtils.configureMocks({ - childIdentityOptions: { - did: childDid, - exists: false, - }, - }); - - let error; - try { - await context.getChildIdentity(childDid); - } catch (err) { - error = err; - } - const expectedError = new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'The passed DID does not correspond to an on-chain child Identity', - }); - expect(error).toEqual(expectedError); - }); - }); - describe('method: getPolymeshApi', () => { it('should return the polkadot.js promise client', async () => { const context = await Context.create({ @@ -1765,7 +1689,7 @@ describe('Context class', () => { includeExpired: false, }); - expect(data.length).toEqual(2); + expect(data).toHaveLength(2); expect(data[0]).toEqual(fakeClaims[1]); expect(data[1]).toEqual(fakeClaims[2]); @@ -1777,7 +1701,7 @@ describe('Context class', () => { trustedClaimIssuers: [targetDid], }); - expect(result.data.length).toEqual(0); + expect(result.data).toHaveLength(0); const customClaimTypeId = new BigNumber(1); @@ -1795,7 +1719,7 @@ describe('Context class', () => { trustedClaimIssuers: [targetDid], }); - expect(result.data.length).toEqual(0); + expect(result.data).toHaveLength(0); }); it('should throw if the middleware V2 is not available and targets or claimTypes are not set', async () => { @@ -2271,7 +2195,7 @@ describe('Context class', () => { assets: assetIds.map(assetId => entityMockUtils.getFungibleAssetInstance({ assetId })), }); - expect(result.length).toBe(2); + expect(result).toHaveLength(2); expect(result[0]!.details.fundsReclaimed).toBe(false); expect(result[0]!.details.remainingFunds).toEqual(new BigNumber(400000)); expect(result[0]!.distribution.origin).toEqual( @@ -2280,7 +2204,7 @@ describe('Context class', () => { expect(result[0]!.distribution.currency).toBe('00000000-0000-8000-8000-000000000001'); expect(result[0]!.distribution.perShare).toEqual(new BigNumber(10)); expect(result[0]!.distribution.maxAmount).toEqual(new BigNumber(500000)); - expect(result[0]!.distribution.expiryDate).toBe(null); + expect(result[0]!.distribution.expiryDate).toBeNull(); expect(result[0]!.distribution.paymentDate).toEqual(new Date('10/14/1987')); expect(result[1]!.details.fundsReclaimed).toBe(false); @@ -2294,7 +2218,7 @@ describe('Context class', () => { expect(result[1]!.distribution.currency).toBe('00000000-0000-8000-8000-000000000002'); expect(result[1]!.distribution.perShare).toEqual(new BigNumber(20)); expect(result[1]!.distribution.maxAmount).toEqual(new BigNumber(300000)); - expect(result[1]!.distribution.expiryDate).toBe(null); + expect(result[1]!.distribution.expiryDate).toBeNull(); expect(result[1]!.distribution.paymentDate).toEqual(new Date('11/26/1989')); }); }); @@ -2624,7 +2548,7 @@ describe('Context class', () => { expect(result.data[0]).toEqual(fakeTxs[0]); expect(result.data[1]).toEqual(fakeTxs[1]); expect(result.count).toEqual(new BigNumber(2)); - expect(result.next).toEqual(null); + expect(result.next).toBeNull(); dsMockUtils.createApolloQueryMock( polyxTransactionsQuery(false, {}, new BigNumber(25), new BigNumber(0)), diff --git a/src/internal.ts b/src/internal.ts index 6231c76d50..1e79965f40 100644 --- a/src/internal.ts +++ b/src/internal.ts @@ -13,10 +13,6 @@ export { consumeAddMultiSigSignerAuthorization, ConsumeAddMultiSigSignerAuthorizationParams, } from '~/api/procedures/consumeAddMultiSigSignerAuthorization'; -export { - consumeAddRelayerPayingKeyAuthorization, - ConsumeAddRelayerPayingKeyAuthorizationParams, -} from '~/api/procedures/consumeAddRelayerPayingKeyAuthorization'; export { consumeJoinOrRotateAuthorization, ConsumeJoinOrRotateAuthorizationParams, @@ -48,8 +44,6 @@ export { } from '~/api/procedures/modifyAssetTrustedClaimIssuers'; export { registerIdentity } from '~/api/procedures/registerIdentity'; export { selfRegisterDid } from '~/api/procedures/selfRegisterDid'; -export { createChildIdentity } from '~/api/procedures/createChildIdentity'; -export { createChildIdentities } from '~/api/procedures/createChildIdentities'; export { attestPrimaryKeyRotation } from '~/api/procedures/attestPrimaryKeyRotation'; export { rotatePrimaryKey } from '~/api/procedures/rotatePrimaryKey'; export { addSecondaryAccounts } from '~/api/procedures/addSecondaryAccountsWithAuth'; @@ -112,7 +106,6 @@ export { linkCaDocs } from '~/api/procedures/linkCaDocs'; export { linkTickerToAsset } from '~/api/procedures/linkTickerToAsset'; export { unlinkTickerFromAsset } from '~/api/procedures/unlinkTickerFromAsset'; export { Identity } from '~/api/entities/Identity'; -export { ChildIdentity } from '~/api/entities/Identity/ChildIdentity'; export { Account } from '~/api/entities/Account'; export { MultiSig } from '~/api/entities/Account/MultiSig'; export { MultiSigProposal } from '~/api/entities/MultiSigProposal'; diff --git a/src/testUtils/mocks/dataSources.ts b/src/testUtils/mocks/dataSources.ts index 3fe07586b7..c9cd2cd7ed 100644 --- a/src/testUtils/mocks/dataSources.ts +++ b/src/testUtils/mocks/dataSources.ts @@ -191,7 +191,7 @@ import { cloneDeep, map, merge, upperFirst } from 'lodash'; import { HistoricPolyxTransaction } from '~/api/entities/Account/types'; import { BallotMotion } from '~/api/entities/CorporateBallot/types'; -import { Account, AuthorizationRequest, ChildIdentity, Context, Identity } from '~/internal'; +import { Account, AuthorizationRequest, Context, Identity } from '~/internal'; import { BalanceTypeEnum, CallIdEnum, EventIdEnum, ModuleIdEnum } from '~/middleware/types'; import { dsMockUtils } from '~/testUtils/mocks'; import { Mocked } from '~/testUtils/types'; @@ -458,7 +458,6 @@ interface ContextOptions { checkPermissions?: CheckPermissionsResult; hasAssetPermissions?: boolean; checkAssetPermissions?: CheckPermissionsResult; - validCdd?: boolean; assetBalance?: BigNumber; invalidDids?: string[]; transactionFees?: ProtocolFees[]; @@ -466,7 +465,6 @@ interface ContextOptions { nonce?: BigNumber; issuedClaims?: ResultSet; getIdentity?: Identity; - getChildIdentity?: ChildIdentity; getIdentityClaimsFromChain?: ClaimData[]; getIdentityClaimsFromMiddleware?: ResultSet; getExternalSigner?: PolkadotSigner; @@ -494,7 +492,6 @@ interface ContextOptions { supportsSubscription?: boolean; getSignature?: `0x${string}`; getNextAssetId?: string; - isV7?: boolean; getPendingSubsidies?: SubsidyWithAllowance[]; } @@ -720,7 +717,6 @@ const defaultContextOptions: ContextOptions = { result: true, }, getExternalSigner: 'signer' as PolkadotSigner, - validCdd: true, assetBalance: new BigNumber(1000), invalidDids: [], transactionFees: [ @@ -859,7 +855,6 @@ function configureContext(opts: ContextOptions): void { did: opts.did, hasRoles: jest.fn().mockResolvedValue(opts.hasRoles), checkRoles: jest.fn().mockResolvedValue(opts.checkRoles), - hasValidCdd: jest.fn().mockResolvedValue(opts.validCdd), getAssetBalance: jest.fn().mockResolvedValue(opts.assetBalance), getPrimaryAccount: jest.fn().mockResolvedValue({ account: { @@ -958,7 +953,6 @@ function configureContext(opts: ContextOptions): void { getSecondaryAccounts: jest.fn().mockReturnValue({ data: opts.secondaryAccounts, next: null }), issuedClaims: jest.fn().mockResolvedValue(opts.issuedClaims), getIdentity: jest.fn().mockResolvedValue(opts.getIdentity), - getChildIdentity: jest.fn().mockResolvedValue(opts.getChildIdentity), getIdentityClaimsFromChain: jest.fn().mockResolvedValue(opts.getIdentityClaimsFromChain), getIdentityClaimsFromMiddleware: jest .fn() @@ -981,7 +975,6 @@ function configureContext(opts: ContextOptions): void { assertHasSigningAddress: jest.fn(), assertSupportsSubscription: jest.fn(), getSignature: jest.fn().mockReturnValue(opts.getSignature), - isV7: opts.isV7, getPendingSubsidies: jest.fn().mockResolvedValue(opts.getPendingSubsidies), } as unknown as MockContext; @@ -1587,7 +1580,7 @@ export function createQueryMock< */ export function createCallMock< ModuleName extends keyof Calls, - CallName extends keyof Calls[ModuleName] | string // string type has been added to support dual compatibility mocking of runtime APIs + CallName extends keyof Calls[ModuleName] | string // string allows broader mocking of runtime API call names >( mod: ModuleName, query: CallName, diff --git a/src/testUtils/mocks/entities.ts b/src/testUtils/mocks/entities.ts index 859b7f2e27..d591c76c29 100644 --- a/src/testUtils/mocks/entities.ts +++ b/src/testUtils/mocks/entities.ts @@ -14,7 +14,6 @@ import { BaseAsset, Checkpoint, CheckpointSchedule, - ChildIdentity, CorporateAction, CustomPermissionGroup, DefaultPortfolio, @@ -104,7 +103,6 @@ import { } from '~/types'; export type MockIdentity = Mocked; -export type MockChildIdentity = Mocked; export type MockAccount = Mocked; export type MockSubsidy = Mocked; export type MockTickerReservation = Mocked; @@ -144,7 +142,6 @@ interface IdentityOptions extends EntityOptions { checkRoles?: EntityGetter; assetPermissionsHasPermissions?: EntityGetter; assetPermissionsCheckPermissions?: EntityGetter>; - hasValidCdd?: EntityGetter; isCddProvider?: EntityGetter; getPrimaryAccount?: EntityGetter; portfoliosGetPortfolio?: EntityGetter; @@ -163,10 +160,6 @@ interface IdentityOptions extends EntityOptions { getOffChainAuthorizationNonce?: EntityGetter; } -interface ChildIdentityOptions extends IdentityOptions { - getParentDid?: EntityGetter; -} - interface TickerReservationOptions extends EntityOptions { ticker?: string; details?: EntityGetter; @@ -396,7 +389,6 @@ interface MultiSigProposalOptions extends EntityOptions { type MockOptions = { identityOptions?: IdentityOptions; - childIdentityOptions?: ChildIdentityOptions; accountOptions?: AccountOptions; subsidyOptions?: SubsidyOptions; tickerReservationOptions?: TickerReservationOptions; @@ -470,7 +462,7 @@ function createMockEntityClass( toHuman = jest.fn(); details = jest.fn(); - private static constructorMock = jest.fn(); // NOSONAR + private static readonly constructorMock = jest.fn(); // NOSONAR private static options = {} as Required; @@ -605,7 +597,6 @@ const MockIdentityClass = createMockEntityClass( hasRoles!: jest.Mock; checkRoles!: jest.Mock; hasRole!: jest.Mock; - hasValidCdd!: jest.Mock; getPrimaryAccount!: jest.Mock; portfolios = {} as { getPortfolio: jest.Mock; @@ -650,7 +641,6 @@ const MockIdentityClass = createMockEntityClass( this.hasRoles = createEntityGetterMock(opts.hasRoles); this.checkRoles = createEntityGetterMock(opts.checkRoles); this.hasRole = createEntityGetterMock(opts.hasRole); - this.hasValidCdd = createEntityGetterMock(opts.hasValidCdd); this.getPrimaryAccount = createEntityGetterMock(opts.getPrimaryAccount); this.portfolios.getPortfolio = createEntityGetterMock(opts.portfoliosGetPortfolio); this.authorizations.getReceived = createEntityGetterMock(opts.authorizationsGetReceived); @@ -679,7 +669,6 @@ const MockIdentityClass = createMockEntityClass( }, () => ({ did: 'someDid', - hasValidCdd: true, isCddProvider: false, authorizationsGetReceived: [], authorizationsGetSent: { data: [], next: null, count: new BigNumber(0) }, @@ -718,137 +707,6 @@ const MockIdentityClass = createMockEntityClass( ['Identity'] ); -const MockChildIdentityClass = createMockEntityClass( - class { - uuid!: string; - did!: string; - hasValidCdd!: jest.Mock; - - getVenues!: jest.Mock; - getScopeId!: jest.Mock; - getAssetBalance!: jest.Mock; - getSecondaryAccounts!: jest.Mock; - - getPrimaryAccount!: jest.Mock; - authorizations = {} as { - getReceived: jest.Mock; - getSent: jest.Mock; - getOne: jest.Mock; - }; - - portfolios = {} as { - getPortfolio: jest.Mock; - }; - - assetPermissions = {} as { - get: jest.Mock; - getGroup: jest.Mock; - hasPermissions: jest.Mock; - checkPermissions: jest.Mock; - }; - - hasRoles!: jest.Mock; - checkRoles!: jest.Mock; - hasRole!: jest.Mock; - - areSecondaryAccountsFrozen!: jest.Mock; - isCddProvider!: jest.Mock; - - getParentDid!: jest.Mock; - getChildIdentities!: Promise; - preApproveAssets!: jest.Mock; - isAssetPreApproved!: jest.Mock; - - /** - * @hidden - */ - public argsToOpts(...args: ConstructorParameters) { - return extractFromArgs(args, ['did']); - } - - /** - * @hidden - */ - public configure(opts: Required) { - this.uuid = 'childIdentity'; - this.did = opts.did; - this.hasValidCdd = createEntityGetterMock(opts.hasValidCdd); - this.getPrimaryAccount = createEntityGetterMock(opts.getPrimaryAccount); - this.portfolios.getPortfolio = createEntityGetterMock(opts.portfoliosGetPortfolio); - this.authorizations.getReceived = createEntityGetterMock(opts.authorizationsGetReceived); - this.getVenues = createEntityGetterMock(opts.getVenues); - this.getScopeId = createEntityGetterMock(opts.getScopeId); - this.getAssetBalance = createEntityGetterMock(opts.getAssetBalance); - this.getSecondaryAccounts = createEntityGetterMock(opts.getSecondaryAccounts); - - this.hasRoles = createEntityGetterMock(opts.hasRoles); - this.checkRoles = createEntityGetterMock(opts.checkRoles); - this.hasRole = createEntityGetterMock(opts.hasRole); - - this.authorizations.getSent = createEntityGetterMock(opts.authorizationsGetSent); - this.authorizations.getOne = createEntityGetterMock(opts.authorizationsGetOne); - this.assetPermissions.get = createEntityGetterMock(opts.assetPermissionsGet); - this.assetPermissions.getGroup = createEntityGetterMock(opts.assetPermissionsGetGroup); - this.assetPermissions.hasPermissions = createEntityGetterMock( - opts.assetPermissionsHasPermissions - ); - this.assetPermissions.checkPermissions = createEntityGetterMock( - opts.assetPermissionsCheckPermissions - ); - - this.areSecondaryAccountsFrozen = createEntityGetterMock(opts.areSecondaryAccountsFrozen); - this.isCddProvider = createEntityGetterMock(opts.isCddProvider); - - this.getParentDid = createEntityGetterMock(opts.getParentDid); - this.getChildIdentities = Promise.resolve([]); - this.preApproveAssets = createEntityGetterMock(opts.preApprovedAssets); - this.isAssetPreApproved = createEntityGetterMock(opts.isAssetPreApproved); - } - }, - () => ({ - did: 'someChildDid', - hasValidCdd: true, - isCddProvider: false, - getScopeId: 'someScopeId', - getAssetBalance: new BigNumber(100), - getSecondaryAccounts: { data: [], next: null }, - areSecondaryAccountsFrozen: false, - assetPermissionsGet: [], - assetPermissionsGetGroup: getKnownPermissionGroupInstance(), - assetPermissionsCheckPermissions: { - result: true, - }, - portfoliosGetPortfolio: getDefaultPortfolioInstance(), - assetPermissionsHasPermissions: true, - hasRole: true, - hasRoles: true, - checkRoles: { - result: true, - }, - authorizationsGetReceived: [], - authorizationsGetSent: { data: [], next: null, count: new BigNumber(0) }, - authorizationsGetOne: getAuthorizationRequestInstance(), - getVenues: [], - - getPrimaryAccount: { - account: getAccountInstance(), - permissions: { - assets: null, - portfolios: null, - transactions: null, - transactionGroups: [], - }, - }, - - toHuman: 'someChildDid', - getParentDid: getIdentityInstance(), - preApprovedAssets: { data: [], next: null, count: new BigNumber(0) }, - isAssetPreApproved: false, - getOffChainAuthorizationNonce: new BigNumber(0), - }), - ['ChildIdentity', 'Identity'] -); - const MockAccountClass = createMockEntityClass( class { uuid!: string; @@ -2320,11 +2178,6 @@ export const mockIdentityModule = (path: string) => (): Record Identity: MockIdentityClass, }); -export const mockChildIdentityModule = (path: string) => (): Record => ({ - ...jest.requireActual(path), - ChildIdentity: MockChildIdentityClass, -}); - export const mockAccountModule = (path: string) => (): Record => ({ ...jest.requireActual(path), Account: MockAccountClass, @@ -2473,7 +2326,6 @@ export const initMocks = function (opts?: MockOptions): void { */ export const configureMocks = function (opts?: MockOptions): void { MockIdentityClass.setOptions(opts?.identityOptions); - MockChildIdentityClass.setOptions(opts?.childIdentityOptions); MockAccountClass.setOptions(opts?.accountOptions); MockSubsidyClass.setOptions(opts?.subsidyOptions); MockTickerReservationClass.setOptions(opts?.tickerReservationOptions); @@ -2541,20 +2393,6 @@ export const getIdentityInstance = (opts?: IdentityOptions): MockIdentity => { return instance as unknown as MockIdentity; }; -/** - * @hidden - * Retrieve an Identity instance - */ -export const getChildIdentityInstance = (opts?: ChildIdentityOptions): MockChildIdentity => { - const instance = new MockChildIdentityClass(); - - if (opts) { - instance.configure(opts); - } - - return instance as unknown as MockChildIdentity; -}; - /** * @hidden * Retrieve an Account instance diff --git a/src/utils/__tests__/conversion.ts b/src/utils/__tests__/conversion.ts index 85e5b39450..fb5713f884 100644 --- a/src/utils/__tests__/conversion.ts +++ b/src/utils/__tests__/conversion.ts @@ -10,7 +10,7 @@ import { Moment, Permill, } from '@polkadot/types/interfaces'; -import { AccountId32, H512 } from '@polkadot/types/interfaces/runtime'; +import { AccountId32 } from '@polkadot/types/interfaces/runtime'; import { DispatchError } from '@polkadot/types/interfaces/system'; import { PalletCorporateActionsBallotBallotMeta, @@ -76,7 +76,7 @@ import { SpRuntimeMultiSignature, } from '@polkadot/types/lookup'; import { BTreeSet, Result } from '@polkadot/types-codec'; -import type { Codec, ITuple } from '@polkadot/types-codec/types'; +import type { ITuple } from '@polkadot/types-codec/types'; import { hexToU8a, stringToHex } from '@polkadot/util'; import { AuthorizationType as MeshAuthorizationType, @@ -143,7 +143,6 @@ import { AssetDocumentWithId, Authorization, AuthorizationType, - ChildKeyWithAuth, Claim, ClaimType, Condition, @@ -248,7 +247,6 @@ import { cddIdToString, cddStatusToBoolean, checkpointToRecordDateSpec, - childKeysWithAuthToCreateChildIdentitiesWithAuth, claimBalanceStatInputToStatUpdates, claimCountStatInputToStatUpdates, claimCountToClaimCountRestrictionValue, @@ -1519,7 +1517,7 @@ describe('authorizationToAuthorizationData and authorizationDataToAuthorization' expect(result).toBe(fakeResult); value = { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: { beneficiary: new Account({ address: 'beneficiary' }, context), subsidizer: new Account({ address: 'subsidizer' }, context), @@ -1665,12 +1663,6 @@ describe('authorizationToAuthorizationData and authorizationDataToAuthorization' result = authorizationDataToAuthorization(authorizationData, context); expect(result).toEqual(fakeResult); - result = authorizationDataToAuthorization( - authorizationData, - dsMockUtils.getContextInstance({ isV7: true }) - ); - expect(result).toEqual({ ...fakeResult, type: AuthorizationType.AddRelayerPayingKey }); // NOSONAR - const type = PermissionGroupType.Full; fakeResult = { type: AuthorizationType.BecomeAgent, @@ -4270,13 +4262,11 @@ describe('assetDispatchErrorToTransferError', () => { }); it('should process errors', () => { - const context = dsMockUtils.getContextInstance({ isV7: true }); + const context = dsMockUtils.getContextInstance(); context.polymeshApi.errors.asset = { InvalidGranularity: { is: jest.fn().mockReturnValue(false) }, SenderSameAsReceiver: { is: jest.fn().mockReturnValue(false) }, - InvalidTransferInvalidReceiverCDD: { is: jest.fn().mockReturnValue(false) }, - InvalidTransferInvalidSenderCDD: { is: jest.fn().mockReturnValue(false) }, InsufficientBalance: { is: jest.fn().mockReturnValue(false) }, InvalidTransferFrozenAsset: { is: jest.fn().mockReturnValue(false) }, InvalidTransferComplianceFailure: { is: jest.fn().mockReturnValue(false) }, @@ -4288,7 +4278,6 @@ describe('assetDispatchErrorToTransferError', () => { context.polymeshApi.errors.portfolio = { PortfolioDoesNotExist: { is: jest.fn().mockReturnValue(false) }, InsufficientPortfolioBalance: { is: jest.fn().mockReturnValue(false) }, - InvalidTransferSenderIdMatchesReceiverId: { is: jest.fn().mockReturnValue(false) }, } as unknown as DecoratedErrors<'promise'>['portfolio']; context.polymeshApi.errors.statistics = { @@ -4315,22 +4304,6 @@ describe('assetDispatchErrorToTransferError', () => { expect(result).toEqual(TransferError.SelfTransfer); - dsMockUtils.setErrorMock('asset', 'InvalidTransferInvalidReceiverCDD', { - returnValue: { is: jest.fn().mockReturnValueOnce(true) }, - }); - - result = assetDispatchErrorToTransferError(mockError, context); - - expect(result).toEqual(TransferError.InvalidReceiverCdd); - - dsMockUtils.setErrorMock('asset', 'InvalidTransferInvalidSenderCDD', { - returnValue: { is: jest.fn().mockReturnValueOnce(true) }, - }); - - result = assetDispatchErrorToTransferError(mockError, context); - - expect(result).toEqual(TransferError.InvalidSenderCdd); - dsMockUtils.setErrorMock('asset', 'InsufficientBalance', { returnValue: { is: jest.fn().mockReturnValueOnce(true) }, }); @@ -4395,14 +4368,6 @@ describe('assetDispatchErrorToTransferError', () => { expect(result).toEqual(TransferError.InsufficientPortfolioBalance); - dsMockUtils.setErrorMock('portfolio', 'InvalidTransferSenderIdMatchesReceiverId', { - returnValue: { is: jest.fn().mockReturnValueOnce(true) }, - }); - - result = assetDispatchErrorToTransferError(mockError, context); - - expect(result).toEqual(TransferError.SelfTransfer); - dsMockUtils.setErrorMock('statistics', 'InvalidTransferStatisticsFailure', { returnValue: { is: jest.fn().mockReturnValueOnce(true) }, }); @@ -5343,7 +5308,7 @@ describe('middlewareInstructionToHistoricInstruction', () => { expect(result.type).toEqual(InstructionType.SettleOnBlock); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((result as any).endBlock).toEqual(endBlock); - expect(result.venueId).toEqual(undefined); + expect(result.venueId).toBeUndefined(); expect(result.createdAt).toEqual(createdAt); resultLeg = result.legs[0] as NftLeg; expect(resultLeg.asset.id).toBe(hexToUuid(assetId)); @@ -6034,12 +5999,10 @@ describe('txTagToProtocolOp', () => { .mockReturnValue(fakeResult); expect(txTagToProtocolOp(TxTags.capitalDistribution.Distribute, context)).toEqual(fakeResult); - const mockResult = 'mockResult' as unknown as Codec; - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); - when(context.createType) - .calledWith('PolymeshCommonUtilitiesProtocolFeeProtocolOp', 'NftIssueNft') - .mockReturnValue(mockResult); - expect(txTagToProtocolOp(TxTags.nft.IssueNft, context)).toEqual(mockResult); + when(createTypeMock) + .calledWith('PolymeshPrimitivesProtocolFeeProtocolOp', 'NftIssueNft') + .mockReturnValue(fakeResult); + expect(txTagToProtocolOp(TxTags.nft.IssueNft, context)).toEqual(fakeResult); }); it('should throw an error if tag does not match any PolymeshPrimitivesProtocolFeeProtocolOp', () => { @@ -7447,12 +7410,12 @@ describe('portfolioLikeToPortfolio', () => { it('should convert a PortfolioLike to a DefaultPortfolio instance', () => { const result = portfolioLikeToPortfolio(did, context); - expect(result instanceof DefaultPortfolio).toBe(true); + expect(result).toBeInstanceOf(DefaultPortfolio); }); it('should convert a PortfolioLike to a NumberedPortfolio instance', () => { const result = portfolioLikeToPortfolio({ identity: did, id }, context); - expect(result instanceof NumberedPortfolio).toBe(true); + expect(result).toBeInstanceOf(NumberedPortfolio); }); }); @@ -7702,7 +7665,7 @@ describe('middlewarePortfolioToPortfolio', () => { } as MiddlewarePortfolio; let result = middlewarePortfolioToPortfolio(middlewarePortfolio, context); - expect(result instanceof DefaultPortfolio).toBe(true); + expect(result).toBeInstanceOf(DefaultPortfolio); middlewarePortfolio = { identityId: 'someDid', @@ -7710,7 +7673,7 @@ describe('middlewarePortfolioToPortfolio', () => { } as MiddlewarePortfolio; result = middlewarePortfolioToPortfolio(middlewarePortfolio, context); - expect(result instanceof NumberedPortfolio).toBe(true); + expect(result).toBeInstanceOf(NumberedPortfolio); }); }); @@ -7722,7 +7685,7 @@ describe('middlewareAssetHolderToAssetHolder', () => { }; const result = middlewareAssetHolderToAssetHolder(middlewareAssetHolder, context); - expect(result instanceof Account).toBe(true); + expect(result).toBeInstanceOf(Account); expect((result as Account).address).toBe('someAccount'); }); @@ -7734,7 +7697,7 @@ describe('middlewareAssetHolderToAssetHolder', () => { }; let result = middlewareAssetHolderToAssetHolder(middlewareAssetHolder, context); - expect(result instanceof DefaultPortfolio).toBe(true); + expect(result).toBeInstanceOf(DefaultPortfolio); middlewareAssetHolder = { identityId: 'someDid', @@ -7742,7 +7705,7 @@ describe('middlewareAssetHolderToAssetHolder', () => { }; result = middlewareAssetHolderToAssetHolder(middlewareAssetHolder, context); - expect(result instanceof NumberedPortfolio).toBe(true); + expect(result).toBeInstanceOf(NumberedPortfolio); }); }); @@ -8684,7 +8647,7 @@ describe('checkpointToRecordDateSpec', () => { const value = null; const context = dsMockUtils.getContextInstance(); const result = checkpointToRecordDateSpec(value, context); - expect(result).toEqual(null); + expect(result).toBeNull(); }); it('should convert a Checkpoint to a polkadot PalletCorporateActionsRecordDateSpec', () => { @@ -11064,7 +11027,7 @@ describe('middlewarePortfolioDataToPortfolio', () => { }; let result = middlewarePortfolioDataToPortfolio(defaultPortfolioData, context); - expect(result instanceof DefaultPortfolio).toBe(true); + expect(result).toBeInstanceOf(DefaultPortfolio); const numberedPortfolioData = { did: 'someDid', @@ -11072,7 +11035,7 @@ describe('middlewarePortfolioDataToPortfolio', () => { }; result = middlewarePortfolioDataToPortfolio(numberedPortfolioData, context); - expect(result instanceof NumberedPortfolio).toBe(true); + expect(result).toBeInstanceOf(NumberedPortfolio); }); }); @@ -11440,7 +11403,7 @@ describe('middlewareAuthorizationDataToAuthorization', () => { const relayerAddress = 'relayerAddress'; const allowance = new BigNumber(1000); fakeResult = { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: { beneficiary: expect.objectContaining({ address: beneficiaryAddress }), subsidizer: expect.objectContaining({ address: relayerAddress }), @@ -12042,62 +12005,6 @@ describe('signatureToMeshRuntimeMultiSignature', () => { expect(result).toEqual(fakeResult); }); - - it('should return a SpRuntimeMultiSignature for v7+ chain versions', () => { - const context = dsMockUtils.getContextInstance(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (context as any).isV7 = true; - - const fakeResult = 'SpCoreEcdsaSignature' as unknown as SpRuntimeMultiSignature; - - const signature = 'someSignature'; - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const fakeEcdsaSignature = 'fakeEcdsaSignature' as any; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const fakeEd25519Signature = 'fakeEd25519Signature' as any; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const fakeSr25519Signature = 'fakeSr25519Signature' as any; - - // Test Ecdsa - when(context.createType) - .calledWith('SpCoreEcdsaSignature', signature) - .mockReturnValue(fakeEcdsaSignature); - - when(context.createType) - .calledWith('SpRuntimeMultiSignature', { Ecdsa: fakeEcdsaSignature }) - .mockReturnValue(fakeResult); - - let result = signatureToMeshRuntimeMultiSignature(SignerKeyRingType.Ecdsa, signature, context); - - expect(result).toEqual(fakeResult); - - // Test Ed25519 - when(context.createType) - .calledWith('SpCoreEd25519Signature', signature) - .mockReturnValue(fakeEd25519Signature); - - when(context.createType) - .calledWith('SpRuntimeMultiSignature', { Ed25519: fakeEd25519Signature }) - .mockReturnValue(fakeResult); - - result = signatureToMeshRuntimeMultiSignature(SignerKeyRingType.Ed25519, signature, context); - - expect(result).toEqual(fakeResult); - - // Test Sr25519 - when(context.createType) - .calledWith('SpCoreSr25519Signature', signature) - .mockReturnValue(fakeSr25519Signature); - - when(context.createType) - .calledWith('SpRuntimeMultiSignature', { Sr25519: fakeSr25519Signature }) - .mockReturnValue(fakeResult); - - result = signatureToMeshRuntimeMultiSignature(SignerKeyRingType.Sr25519, signature, context); - - expect(result).toEqual(fakeResult); - }); }); describe('offChainMetadataToMeshReceiptMetadata', () => { @@ -12250,66 +12157,7 @@ describe('secondaryAccountWithAuthToSecondaryKeyWithAuth', () => { .calledWith('Vec', expect.any(Object)) .mockReturnValue(fakeResult); - let result = secondaryAccountWithAuthToSecondaryKeyWithAuth(accounts, context); - - expect(result).toEqual(fakeResult); - - dsMockUtils.configureMocks({ contextOptions: { isV7: true } }); - const mockResult = 'fakeSecondaryKeysWithAuth' as unknown as Vec; - - when(context.createType) - .calledWith('Vec', expect.any(Object)) - .mockReturnValue(mockResult); - - result = secondaryAccountWithAuthToSecondaryKeyWithAuth(accounts, context); - - expect(result).toEqual(mockResult); - }); -}); - -describe('childKeysWithAuthToCreateChildIdentitiesWithAuth', () => { - beforeAll(() => { - dsMockUtils.initMocks(); - }); - - afterEach(() => { - dsMockUtils.reset(); - }); - - afterAll(() => { - dsMockUtils.cleanup(); - }); - - it('should create child identities with auth', () => { - const context = dsMockUtils.getContextInstance(); - - const childKey = '5EYCAe5ijAx5xEfZdpCna3grUpY1M9M5vLUH5vpmwV1EnaYR'; - const childKeyAuths: ChildKeyWithAuth[] = [ - { - key: childKey, - authSignature: '0xSignature', - }, - ]; - - const childAccountId = 'childKey' as unknown as AccountId; - - when(context.createType).calledWith('AccountId', childKey).mockReturnValue(childAccountId); - - const h512Signature = '0xSignature' as unknown as H512; - when(context.createType).calledWith('H512', '0xSignature').mockReturnValue(h512Signature); - - const fakeResult = 'fakeSecondaryKeysWithAuth' as unknown as Vec; - - when(context.createType) - .calledWith('Vec', [ - { - key: childAccountId, - authSignature: h512Signature, - }, - ]) - .mockReturnValue(fakeResult); - - const result = childKeysWithAuthToCreateChildIdentitiesWithAuth(childKeyAuths, context); + const result = secondaryAccountWithAuthToSecondaryKeyWithAuth(accounts, context); expect(result).toEqual(fakeResult); }); @@ -12593,37 +12441,6 @@ describe('rawStakingLedgerToStakingLedgerEntry', () => { claimedRewards: expect.arrayContaining([new BigNumber(7)]), }); }); - - it('should handle v7 staking ledger format', () => { - const mockContext = dsMockUtils.getContextInstance({ isV7: true }); - - const rawNomination = dsMockUtils.createMockStakingLedger({ - total: dsMockUtils.createMockCompact( - dsMockUtils.createMockU128(new BigNumber(10).times(10 ** 6)) - ), - active: dsMockUtils.createMockCompact( - dsMockUtils.createMockU128(new BigNumber(5).times(10 ** 6)) - ), - unlocking: dsMockUtils.createMockVec([ - dsMockUtils.createMockUnlockChunk({ - value: dsMockUtils.createMockCompact(dsMockUtils.createMockU128(new BigNumber(8))), - era: dsMockUtils.createMockCompact(dsMockUtils.createMockU32(new BigNumber(9))), - }), - ]), - claimedRewards: dsMockUtils.createMockVec([dsMockUtils.createMockU32(new BigNumber(7))]), - stash: dsMockUtils.createMockAccountId(DUMMY_ACCOUNT_ID), - }); - - const result = rawStakingLedgerToStakingLedgerEntry(rawNomination, mockContext); - - expect(result).toEqual({ - stash: expect.any(Account), - total: new BigNumber(10), - active: new BigNumber(5), - unlocking: expect.arrayContaining([]), - claimedRewards: expect.arrayContaining([new BigNumber(7)]), - }); - }); }); describe('rawValidatorPrefToCommission', () => { @@ -13718,8 +13535,8 @@ describe('asset holder conversion helpers', () => { }); describe('assetHolderIdToMeshAssetHolder', () => { - it('should map a hex DID string for non-v7 chains', async () => { - const mockContext = dsMockUtils.getContextInstance({ isV7: false }); + it('should map a hex DID string', async () => { + const mockContext = dsMockUtils.getContextInstance(); stubMeshAssetHolderCreateTypes(mockContext); const result = await assetHolderIdToMeshAssetHolder(did, mockContext); expect(result).toBeDefined(); @@ -13729,15 +13546,8 @@ describe('asset holder conversion helpers', () => { ); }); - it('should map a hex DID string for v7 chains', async () => { - const v7Context = dsMockUtils.getContextInstance({ isV7: true }); - stubMeshAssetHolderCreateTypes(v7Context); - const result = await assetHolderIdToMeshAssetHolder(did, v7Context); - expect(result).toBeDefined(); - }); - - it('should map a plain address string for non-v7 chains', async () => { - const mockContext = dsMockUtils.getContextInstance({ isV7: false }); + it('should map a plain address string', async () => { + const mockContext = dsMockUtils.getContextInstance(); stubMeshAssetHolderCreateTypes(mockContext); const result = await assetHolderIdToMeshAssetHolder(DUMMY_ACCOUNT_ID, mockContext); expect(result).toBeDefined(); @@ -13747,35 +13557,8 @@ describe('asset holder conversion helpers', () => { ); }); - it('should map a plain address string for v7 when the account has an identity', async () => { - const v7Context = dsMockUtils.getContextInstance({ isV7: true }); - stubMeshAssetHolderCreateTypes(v7Context); - dsMockUtils.createQueryMock('identity', 'keyRecords', { - returnValue: createMockOption( - dsMockUtils.createMockKeyRecord({ - PrimaryKey: createMockIdentityId('linkedDid'), - }) - ), - }); - const result = await assetHolderIdToMeshAssetHolder(DUMMY_ACCOUNT_ID, v7Context); - expect(result).toBeDefined(); - }); - - it('should throw when a v7 string account has no identity', async () => { - const v7Context = dsMockUtils.getContextInstance({ isV7: true }); - entityMockUtils.configureMocks({ - accountOptions: { getIdentity: null }, - }); - await expect(assetHolderIdToMeshAssetHolder(DUMMY_ACCOUNT_ID, v7Context)).rejects.toThrow( - new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'Invalid string value', - }) - ); - }); - - it('should map a portfolio id object for non-v7', async () => { - const mockContext = dsMockUtils.getContextInstance({ isV7: false }); + it('should map a portfolio id object', async () => { + const mockContext = dsMockUtils.getContextInstance(); stubMeshAssetHolderCreateTypes(mockContext); const portfolioId = { did: 'pid', number: new BigNumber(1) }; const result = await assetHolderIdToMeshAssetHolder(portfolioId, mockContext); @@ -13785,19 +13568,11 @@ describe('asset holder conversion helpers', () => { expect.objectContaining({ Portfolio: expect.anything() }) ); }); - - it('should map a portfolio id object for v7', async () => { - const v7Context = dsMockUtils.getContextInstance({ isV7: true }); - stubMeshAssetHolderCreateTypes(v7Context); - const portfolioId = { did: 'pid', number: new BigNumber(1) }; - const result = await assetHolderIdToMeshAssetHolder(portfolioId, v7Context); - expect(result).toBeDefined(); - }); }); describe('assetHolderToAssetHolderKind', () => { - it('should map Account and portfolio variants for non-v7', () => { - const mockContext = dsMockUtils.getContextInstance({ isV7: false }); + it('should map Account and portfolio variants', () => { + const mockContext = dsMockUtils.getContextInstance(); const fakeKind = 'kind' as unknown as PolymeshPrimitivesIdentityIdPortfolioKind; when(mockContext.createType) @@ -13825,45 +13600,11 @@ describe('asset holder conversion helpers', () => { .mockReturnValue(fakeKind); expect(assetHolderToAssetHolderKind(numbered, mockContext)).toBe(fakeKind); }); - - it('should map Account and portfolio variants for v7', () => { - const v7Context = dsMockUtils.getContextInstance({ isV7: true }); - const fakeKind = 'kind' as unknown as PolymeshPrimitivesIdentityIdPortfolioKind; - const fakeAccountId = dsMockUtils.createMockAccountId(DUMMY_ACCOUNT_ID); - - when(v7Context.createType) - .calledWith('AccountId', DUMMY_ACCOUNT_ID) - .mockReturnValue(fakeAccountId); - when(v7Context.createType) - .calledWith('PolymeshPrimitivesIdentityIdPortfolioKind', { AccountId: fakeAccountId }) - .mockReturnValue(fakeKind); - expect( - assetHolderToAssetHolderKind( - new Account({ address: DUMMY_ACCOUNT_ID }, v7Context), - v7Context - ) - ).toBe(fakeKind); - - when(v7Context.createType) - .calledWith('PolymeshPrimitivesIdentityIdPortfolioKind', 'Default') - .mockReturnValue(fakeKind); - expect( - assetHolderToAssetHolderKind(new DefaultPortfolio({ did: 'd' }, v7Context), v7Context) - ).toBe(fakeKind); - - const numbered = new NumberedPortfolio({ did: 'd', id: new BigNumber(2) }, v7Context); - const rawU64 = dsMockUtils.createMockU64(new BigNumber(2)); - when(v7Context.createType).calledWith('u64', '2').mockReturnValue(rawU64); - when(v7Context.createType) - .calledWith('PolymeshPrimitivesIdentityIdPortfolioKind', { User: rawU64 }) - .mockReturnValue(fakeKind); - expect(assetHolderToAssetHolderKind(numbered, v7Context)).toBe(fakeKind); - }); }); describe('assetHolderIdsToBtreeSet', () => { - it('should create a BTreeSet of asset holders for non-v7', () => { - const mockContext = dsMockUtils.getContextInstance({ isV7: false }); + it('should create a BTreeSet of asset holders', () => { + const mockContext = dsMockUtils.getContextInstance(); const raw = createMockAssetHolder({ Account: dsMockUtils.createMockAccountId(DUMMY_ACCOUNT_ID), }); @@ -13873,20 +13614,6 @@ describe('asset holder conversion helpers', () => { .mockReturnValue(fakeSet); expect(assetHolderIdsToBtreeSet([raw, raw], mockContext)).toBe(fakeSet); }); - - it('should delegate to portfolio id btree set for v7', () => { - const v7Context = dsMockUtils.getContextInstance({ isV7: true }); - const raw = dsMockUtils.createMockPortfolioId(); - const fakeSet = {} as BTreeSet; - when(v7Context.createType) - .calledWith('BTreeSet', expect.anything()) - .mockReturnValue(fakeSet); - const result = assetHolderIdsToBtreeSet( - [raw, raw] as unknown as PolymeshPrimitivesAssetAssetHolder[], // NOSONAR - v7Context - ); - expect(result).toBe(fakeSet); - }); }); }); diff --git a/src/utils/__tests__/internal.ts b/src/utils/__tests__/internal.ts index e9547e7093..4df33250d1 100644 --- a/src/utils/__tests__/internal.ts +++ b/src/utils/__tests__/internal.ts @@ -82,7 +82,6 @@ import { asAccount, asAsset, asBaseAsset, - asChildIdentity, asDid, asFungibleAsset, asNftId, @@ -133,7 +132,6 @@ import { isMiddlewareV6Extrinsic, isModuleOrTagMatch, isPrintableAscii, - isV7Spec, mergeReceipts, neededStatTypeForRestrictionInput, optionize, @@ -2207,25 +2205,6 @@ describe('getIdentityFromKeyRecord', () => { }); }); -describe('asChildIdentity', () => { - it('should return child identity instance', () => { - const mockContext = dsMockUtils.getContextInstance(); - - const childDid = 'childDid'; - const childIdentity = entityMockUtils.getChildIdentityInstance({ - did: childDid, - }); - - let result = asChildIdentity(childDid, mockContext); - - expect(result).toEqual(expect.objectContaining({ did: childDid })); - - result = asChildIdentity(childIdentity, mockContext); - - expect(result).toEqual(expect.objectContaining({ did: childDid })); - }); -}); - describe('asFungibleAsset', () => { beforeAll(() => { dsMockUtils.initMocks(); @@ -3176,16 +3155,6 @@ describe('getAllowedMajors', () => { }); }); -describe('isV7Spec', () => { - it('should return true for spec versions below 8000000', () => { - expect(isV7Spec(7999999)).toBe(true); - }); - - it('should return false for spec versions 8000000 and above', () => { - expect(isV7Spec(8000000)).toBe(false); - }); -}); - describe('requestMulti', () => { let context: Context; diff --git a/src/utils/constants.ts b/src/utils/constants.ts index d308c1ee46..758e01440d 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -112,7 +112,7 @@ export const ROOT_TYPES = rootTypes; /** * The Polymesh chain spec version range that is compatible with this version of the SDK */ -export const SUPPORTED_SPEC_VERSION_RANGE = '7.0 || 7.1 || 7.2 || 7.3 || 8.0'; +export const SUPPORTED_SPEC_VERSION_RANGE = '8.0'; /** * The Polymesh private chain spec version range that is compatible with this version of the SDK diff --git a/src/utils/conversion.ts b/src/utils/conversion.ts index 2fb5c01974..60b1d69071 100644 --- a/src/utils/conversion.ts +++ b/src/utils/conversion.ts @@ -26,7 +26,6 @@ import { PalletStakingActiveEraInfo, PalletStakingNominations, PalletStakingStakingLedger, - PalletStakingUnlockChunk, PalletStakingValidatorPrefs, PalletStoFundingMethod, PalletStoFundraiser, @@ -97,8 +96,8 @@ import { SpRuntimeMultiSignature, } from '@polkadot/types/lookup'; import type { IsError } from '@polkadot/types/metadata/decorate/types'; -import { Codec, ITuple } from '@polkadot/types/types'; -import { BTreeSet, Compact, Result } from '@polkadot/types-codec'; +import { ITuple } from '@polkadot/types/types'; +import { BTreeSet, Result } from '@polkadot/types-codec'; import { hexHasPrefix, hexToString, @@ -128,18 +127,14 @@ import BigNumber from 'bignumber.js'; import { computeWithoutCheck } from 'iso-7064'; import { camelCase, - flatten, forEach, groupBy, - includes, isEqual, map, range, rangeRight, snakeCase, - uniq, uniqWith, - values, } from 'lodash'; import { @@ -211,7 +206,6 @@ import { AssetStat, Authorization, AuthorizationType, - ChildKeyWithAuth, Claim, ClaimBalanceStatInput, ClaimCountRestrictionValue, @@ -920,16 +914,12 @@ export function portfolioIdToMeshPortfolioId( /** * @hidden */ -export async function assetHolderIdToMeshAssetHolder( +export async function assetHolderIdToMeshAssetHolder( // eslint-disable-line require-await assetHolderId: AssetHolderId, context: Context ): Promise { if (typeof assetHolderId === 'string') { if (hexHasPrefix(assetHolderId)) { - if (context.isV7) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return portfolioIdToMeshPortfolioId({ did: assetHolderId }, context) as any; - } return context.createType( 'PolymeshPrimitivesAssetAssetHolder', { @@ -937,21 +927,6 @@ export async function assetHolderIdToMeshAssetHolder( } ); } - if (context.isV7) { - const account = new Account({ address: assetHolderId }, context); - const identity = await account.getIdentity(); - if (!identity) { - throw new PolymeshError({ - code: ErrorCode.UnmetPrerequisite, - message: 'Invalid string value', - }); - } - return context.createType('PolymeshPrimitivesIdentityIdPortfolioId', { - did: stringToIdentityId(identity.did, context), - kind: { AccountId: stringToAccountId(assetHolderId, context) }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - }) as any; - } return context.createType( 'PolymeshPrimitivesAssetAssetHolder', { @@ -959,10 +934,6 @@ export async function assetHolderIdToMeshAssetHolder( } ); } - if (context.isV7) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return portfolioIdToMeshPortfolioId(assetHolderId, context) as any; - } return context.createType( 'PolymeshPrimitivesAssetAssetHolder', { @@ -993,15 +964,6 @@ export function assetHolderToAssetHolderKind( assetHolder: AssetHolder, context: Context ): PolymeshPrimitivesAssetAssetHolderKind { - if (context.isV7) { - if (assetHolder instanceof Account) { - return context.createType('PolymeshPrimitivesIdentityIdPortfolioKind', { - AccountId: stringToAccountId(assetHolder.address, context), - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return portfolioToPortfolioKind(assetHolder, context) as any; - } if (assetHolder instanceof Account) { return context.createType('PolymeshPrimitivesAssetAssetHolderKind', 'Account'); } @@ -1058,7 +1020,7 @@ export function transactionPermissionsToTxGroups( excludedTags = transactionValues; } - return values(TxGroup) + return Object.values(TxGroup) .sort() .filter(group => { const tagsInGroup = txGroupToTxTags(group); @@ -1095,29 +1057,27 @@ function initExtrinsicDict( ): Record { const extrinsicDict: Record = {}; - uniq(txValues) - .sort() - .forEach(tag => { - if (tag.includes('.')) { - const { palletName, dispatchableName } = splitTag(tag as TxTag); - let pallet = extrinsicDict[palletName]; - - if (pallet === null) { - throw new PolymeshError({ - code: ErrorCode.ValidationError, - message, - data: { - module: palletName, - transactions: [dispatchableName], - }, - }); - } else pallet ??= extrinsicDict[palletName] = { tx: [] }; + [...new Set(txValues)].sort().forEach(tag => { + if (tag.includes('.')) { + const { palletName, dispatchableName } = splitTag(tag as TxTag); + let pallet = extrinsicDict[palletName]; - pallet.tx.push(dispatchableName); - } else { - extrinsicDict[stringUpperFirst(tag)] = null; - } - }); + if (pallet === null) { + throw new PolymeshError({ + code: ErrorCode.ValidationError, + message, + data: { + module: palletName, + transactions: [dispatchableName], + }, + }); + } else pallet ??= extrinsicDict[palletName] = { tx: [] }; + + pallet.tx.push(dispatchableName); + } else { + extrinsicDict[stringUpperFirst(tag)] = null; + } + }); return extrinsicDict; } @@ -1805,13 +1765,6 @@ export function authorizationDataToAuthorization( allowance: balanceToBigNumber(polyxLimit), }; - if (context.isV7) { - return { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR - value, - }; - } - return { type: AuthorizationType.OldAddRelayerPayingKey, value, @@ -2972,7 +2925,7 @@ export function complianceRequirementResultToRequirementCompliance( complies: boolToBoolean(result), }; - const existingCondition = conditions.find(condition => + const existingCondition = conditions.some(condition => conditionCompliancesAreEqual(condition, newCondition) ); @@ -3041,7 +2994,7 @@ export function complianceRequirementReportToRequirementCompliance( complies: boolToBoolean(satisfied), }; - const existingCondition = conditions.find(condition => + const existingCondition = conditions.some(condition => conditionCompliancesAreEqual(condition, newCondition) ); @@ -3104,7 +3057,7 @@ export function complianceRequirementToRequirement( ); } - const existingCondition = conditions.find(condition => + const existingCondition = conditions.some(condition => conditionsAreEqual(condition, newCondition) ); @@ -3149,7 +3102,7 @@ export function txTagToProtocolOp( tag: TxTag, context: Context ): PolymeshPrimitivesProtocolFeeProtocolOp { - const protocolOpTags = [ + const protocolOpTags: TxTag[] = [ TxTags.asset.RegisterUniqueTicker, TxTags.asset.RegisterTicker, TxTags.asset.Issue, @@ -3171,16 +3124,13 @@ export function txTagToProtocolOp( const [moduleName, extrinsicName] = tag.split('.'); const value = `${stringUpperFirst(moduleName)}${stringUpperFirst(extrinsicName)}`; - if (!includes(protocolOpTags, tag)) { + if (!protocolOpTags.includes(tag)) { throw new PolymeshError({ code: ErrorCode.ValidationError, message: `${value} does not match any PolymeshPrimitivesProtocolFeeProtocolOp`, }); } - if (context.isV7) { - return context.createType('PolymeshCommonUtilitiesProtocolFeeProtocolOp', value); - } return context.createType('PolymeshPrimitivesProtocolFeeProtocolOp', value); } @@ -3713,13 +3663,6 @@ export function assetHolderIdsToBtreeSet( rawAssetHolderIds: PolymeshPrimitivesAssetAssetHolder[], context: Context ): BTreeSet { - if (context.isV7) { - return portfolioIdsToBtreeSet( - rawAssetHolderIds as unknown as PolymeshPrimitivesIdentityIdPortfolioId[], // NOSONAR - context - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ) as any; - } return context.createType( 'BTreeSet', uniqWith(rawAssetHolderIds, isEqual) @@ -3751,7 +3694,7 @@ export function assetDispatchErrorToTransferError( type ErrorCase = [IsError, TransferError]; - let record: ErrorCase[] = [ + const record: ErrorCase[] = [ [assetErrors.NoSuchAsset, TransferError.AssetDoesNotExists], [assetErrors.InvalidGranularity, TransferError.InvalidGranularity], [assetErrors.SenderSameAsReceiver, TransferError.SelfTransfer], @@ -3765,20 +3708,6 @@ export function assetDispatchErrorToTransferError( [statisticsError.InvalidTransferStatisticsFailure, TransferError.TransferNotAllowed], ]; - if (context.isV7) { - record = [ - ...record, - [ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (portfolioErrors as any).InvalidTransferSenderIdMatchesReceiverId, - TransferError.SelfTransfer, - ], - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [(assetErrors as any).InvalidTransferInvalidReceiverCDD, TransferError.InvalidReceiverCdd], - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [(assetErrors as any).InvalidTransferInvalidSenderCDD, TransferError.InvalidSenderCdd], - ]; - } if (error.isModule) { const moduleErr = error.asModule; @@ -3902,8 +3831,8 @@ export function permissionsLikeToPermissions( if (transactions !== undefined) { transactionPermissions = transactions; } else if (transactionGroups !== undefined) { - transactionGroupPermissions = uniq(transactionGroups); - const groupTags = flatten(transactionGroups.map(txGroupToTxTags)); + transactionGroupPermissions = [...new Set(transactionGroups)]; + const groupTags = transactionGroups.map(txGroupToTxTags).flat(); transactionPermissions = { ...transactionPermissions, values: groupTags, @@ -5424,7 +5353,7 @@ export function middlewareAuthorizationDataToAuthorization( } return { - type: AuthorizationType.AddRelayerPayingKey, // NOSONAR + type: AuthorizationType.OldAddRelayerPayingKey, value: { beneficiary: new Account({ address: beneficiary }, context), subsidizer: new Account({ address: subsidizer }, context), @@ -5716,19 +5645,7 @@ export function signatureToMeshRuntimeMultiSignature( value: string, context: Context ): SpRuntimeMultiSignature { - let rawValue; - if (context.isV7) { - if (type === SignerKeyRingType.Ecdsa) { - rawValue = context.createType('SpCoreEcdsaSignature', value); - } else if (type === SignerKeyRingType.Ed25519) { - rawValue = context.createType('SpCoreEd25519Signature', value); - } else { - // assume sr 25519 - rawValue = context.createType('SpCoreSr25519Signature', value); - } - } else { - rawValue = context.createType('U8aFixed', value); - } + const rawValue = context.createType('U8aFixed', value); return context.createType('SpRuntimeMultiSignature', { [type]: rawValue, @@ -5805,35 +5722,9 @@ export function secondaryAccountWithAuthToSecondaryKeyWithAuth( }; }); - if (context.isV7) { - return context.createType( - 'Vec', - keyWithAuths - ); - } return context.createType('Vec', keyWithAuths); } -/** - * @hidden - * - * @deprecated no longer supported in chain v8 - */ -export function childKeysWithAuthToCreateChildIdentitiesWithAuth( - childKeyAuths: ChildKeyWithAuth[], - context: Context -): Vec { - const keyWithAuths = childKeyAuths.map(({ key, authSignature }) => ({ - key: stringToAccountId(asAccount(key, context).address, context), - authSignature: stringToH512(authSignature, context), - })); - - return context.createType( - 'Vec', - keyWithAuths - ); -} - /** * @hidden */ @@ -5950,30 +5841,13 @@ export function rawStakingLedgerToStakingLedgerEntry( ledger: PalletStakingStakingLedger, context: Context ): StakingLedger { - let rawTotal: Compact; - let rawActive: Compact; - let rawClaimedRewards: Vec; - let rawUnlocking: Vec; - let rawStash: AccountId32; - - if (context.isV7) { - ({ - total: rawTotal, - active: rawActive, - unlocking: rawUnlocking, - claimedRewards: rawClaimedRewards, - stash: rawStash, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } = ledger as any); - } else { - ({ - total: rawTotal, - active: rawActive, - unlocking: rawUnlocking, - legacyClaimedRewards: rawClaimedRewards, - stash: rawStash, - } = ledger); - } + const { + total: rawTotal, + active: rawActive, + unlocking: rawUnlocking, + legacyClaimedRewards: rawClaimedRewards, + stash: rawStash, + } = ledger; const total = balanceToBigNumber(rawTotal.unwrap()); const active = balanceToBigNumber(rawActive.unwrap()); diff --git a/src/utils/internal.ts b/src/utils/internal.ts index 8546257d77..2e910a399d 100644 --- a/src/utils/internal.ts +++ b/src/utils/internal.ts @@ -34,7 +34,6 @@ import { BaseAsset, Checkpoint, CheckpointSchedule, - ChildIdentity, Context, FungibleAsset, Identity, @@ -222,14 +221,6 @@ export function asIdentity(value: string | Identity, context: Context): Identity return typeof value === 'string' ? new Identity({ did: value }, context) : value; } -/** - * @hidden - * Given a DID return the corresponding ChildIdentity, given an ChildIdentity return the ChildIdentity - */ -export function asChildIdentity(value: string | ChildIdentity, context: Context): ChildIdentity { - return typeof value === 'string' ? new ChildIdentity({ did: value }, context) : value; -} - /** * @hidden * Given an address return the corresponding Account, given an Account return the Account @@ -2433,14 +2424,3 @@ export async function getCorporateActionWithDescription( return { corporateAction: ca.unwrap(), description }; } - -/** - * @hidden - */ -export function isV7Spec(specVersion: number): boolean { - if (specVersion < 8000000) { - return true; - } - - return false; -} diff --git a/src/utils/typeguards.ts b/src/utils/typeguards.ts index fe0f26e2af..fe7efb2c49 100644 --- a/src/utils/typeguards.ts +++ b/src/utils/typeguards.ts @@ -34,7 +34,6 @@ import { BlockedClaim, BuyLockupClaim, CddClaim, - CddProviderRole, Claim, ClaimType, ConditionType, @@ -312,13 +311,6 @@ export function isVenueOwnerRole(role: Role): role is VenueOwnerRole { return role.type === RoleType.VenueOwner; } -/** - * Return whether Role is CddProviderRole - */ -export function isCddProviderRole(role: Role): role is CddProviderRole { - return role.type === RoleType.CddProvider; -} - /** * Return whether Role is DidRegistrarRole */