From dd28b4985085b8eab371a2464c8594b09afee93f Mon Sep 17 00:00:00 2001 From: Whitney Purdum Date: Tue, 18 Oct 2022 10:44:23 -0400 Subject: [PATCH] =?UTF-8?q?style:=20add=20warn=20for=20shadow=20variables?= =?UTF-8?q?=20(variables=20in=20scope=20that=20share=20s=E2=80=A6=20(#663)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * style: add warn for shadow variables (variables in scope that share same name) * fix: set ignoreFunctionTypeParameterNameValueShadow to true * fix: change var name to avoid repeat * fix: add quotes * fix: rename method variable * fix: update var names for namespace to avoid shadowing * fix: remove linting rule extension * fix: remove shadowed var names * fix: update vc service e2e shadowed variables * fix: fix failing tests * fix: resolve shadowed variables in patches-build * fix: fix shadow variables * fix: fix version shadow var --- .eslintrc.js | 3 ++ .../classes/modules_domains.DomainsService.md | 4 +- e2e/claims.service.e2e.ts | 30 ++++++------ e2e/verifiable-credentials.service.e2e.ts | 15 +++--- scripts/patches-build.js | 4 +- src/modules/claims/claims.service.ts | 44 +++++++++--------- src/modules/domains/domains.service.ts | 46 ++++++++++--------- 7 files changed, 76 insertions(+), 70 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 04ab4e07..3ac13f2f 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,5 +1,8 @@ module.exports = { extends: ['@energyweb'], + rules: { + "@typescript-eslint/no-shadow": "warn", + }, env: { browser: true, es2021: true, diff --git a/docs/api/classes/modules_domains.DomainsService.md b/docs/api/classes/modules_domains.DomainsService.md index 9e1aff06..f688933c 100644 --- a/docs/api/classes/modules_domains.DomainsService.md +++ b/docs/api/classes/modules_domains.DomainsService.md @@ -713,13 +713,13 @@ ___ ### readName -▸ **readName**(`namehash`): `Promise`<`string`\> +▸ **readName**(`namehashToRead`): `Promise`<`string`\> #### Parameters | Name | Type | | :------ | :------ | -| `namehash` | `string` | +| `namehashToRead` | `string` | #### Returns diff --git a/e2e/claims.service.e2e.ts b/e2e/claims.service.e2e.ts index f99c7028..9f4cf081 100644 --- a/e2e/claims.service.e2e.ts +++ b/e2e/claims.service.e2e.ts @@ -169,8 +169,8 @@ const roles: Record = { }; const mockGetRoleDefinition = jest .fn() - .mockImplementation((namespace: string) => { - return roles[namespace]; + .mockImplementation((roleDefNamespace: string) => { + return roles[roleDefNamespace]; }); const mockCachedDocument = jest.fn().mockImplementation((did: string) => { return { @@ -597,7 +597,7 @@ describe('Сlaim tests', () => { if (registrationTypes.includes(RegistrationTypes.OffChain)) { expect(issuedToken).toBeDefined(); - const { claimData, signer, did } = (await didRegistry.decodeJWTToken({ + const { claimData, signer, did: decodedTokenDid } = (await didRegistry.decodeJWTToken({ token: issuedToken, })) as { [key: string]: string }; @@ -609,7 +609,7 @@ describe('Сlaim tests', () => { }); expect(signer).toBe(issuerDID); - expect(did).toBe(requesterDID); + expect(decodedTokenDid).toBe(requesterDID); } expect(requester).toEqual(subjectDID); @@ -646,8 +646,8 @@ describe('Сlaim tests', () => { }); test('asset enrollment by issuer of type DID', async () => { - mockGetAssetById.mockImplementationOnce(({ id }: { id: string }) => ({ - id, + mockGetAssetById.mockImplementationOnce(({ id: assetId }: { id: string }) => ({ + assetId, })); await signerService.connect(rootOwner, ProviderType.PrivateKey); const assetAddress = await assetsService.registerAsset(); @@ -879,7 +879,7 @@ describe('Сlaim tests', () => { claim: { token: res.issuedToken }, }); - const delay = (ms) => new Promise((res) => setTimeout(res, ms)); + const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await delay(8000); return expect( @@ -962,19 +962,19 @@ describe('Сlaim tests', () => { test('should be able to issue without request and publish onchain for owned asset', async () => { await signerService.connect(rootOwner, ProviderType.PrivateKey); - const claimType = `${roleForAsset}.${root}`; + const assetClaimType = `${roleForAsset}.${root}`; const assetDID = `did:${Methods.Erc1056}:${ Chain.VOLTA }:${await assetsService.registerAsset()}`; const claim = await issueWithoutRequest(rootOwner, { subjectDID: assetDID, - claimType, + claimType: assetClaimType, registrationTypes, }); expect(claim.onChainProof).toHaveLength(132); const mockedClaim = { - claimType, + claimType: assetClaimType, isApproved: true, onChainProof: claim.onChainProof, claimTypeVersion: version, @@ -986,11 +986,11 @@ describe('Сlaim tests', () => { .mockImplementationOnce(() => [mockedClaim]); await claimsService.publishPublicClaim({ - claim: { claimType }, + claim: { claimType: assetClaimType }, registrationTypes, }); expect( - await claimsService.hasOnChainRole(assetDID, claimType, version) + await claimsService.hasOnChainRole(assetDID, assetClaimType, version) ).toBe(true); }); @@ -1053,7 +1053,7 @@ describe('Сlaim tests', () => { const waitForRegister = new Promise((resolve) => claimManager.once( 'RoleRegistered', - (subject, role, version, expiry: BigNumber) => + (subject, role, vers, expiry: BigNumber) => resolve(expiry.toNumber()) ) ); @@ -1146,12 +1146,12 @@ describe('Сlaim tests', () => { const createExampleSignedCredential = async ( issuerFields: IssuerFields[], - namespace: string, + signedCredentialNamespace: string, expirationDate?: Date ) => { return await verifiableCredentialsService.createRoleVC({ id: rootOwnerDID, - namespace: namespace, + namespace: signedCredentialNamespace, version: '1', issuerFields, expirationDate, diff --git a/e2e/verifiable-credentials.service.e2e.ts b/e2e/verifiable-credentials.service.e2e.ts index 2ea95bee..48febac7 100644 --- a/e2e/verifiable-credentials.service.e2e.ts +++ b/e2e/verifiable-credentials.service.e2e.ts @@ -439,21 +439,20 @@ describe('Verifiable credentials tests', () => { test('initiateExchange() should return presentation matching presentation request', async () => { const { - selections: [{ selectResults }], + selections: [{ selectResults: slctResults }], } = await verifiableCredentialsService.initiateExchange({ type: VC_API_EXCHANGE, url: exchangeUrl, }); - expect(selectResults.verifiableCredential).toHaveLength(1); + expect(slctResults.verifiableCredential).toHaveLength(1); }); test('initiateExchange() should filter self-sign data input_descriptors before fetching credentials and selecting matches', async () => { /* * For rationale for this behaviour, see the comment on `verifiable-credentials-base.filterSelfSignDescriptors()` */ - const vpRequest: VpRequest = bloxmoveVpRequest as VpRequest; (axios as jest.Mocked).post.mockImplementation(() => { return Promise.resolve({ - data: { errors: [], vpRequest }, + data: { errors: [], vpRequest: bloxmoveVpRequest }, }); }); getClaimsBySubject.mockResolvedValue(customerRoleClaim); @@ -462,7 +461,7 @@ describe('Verifiable credentials tests', () => { 'getCredentialsByDefinition' ); const { - selections: [{ selectResults }], + selections: [{ selectResults: results }], } = await verifiableCredentialsService.initiateExchange({ type: VC_API_EXCHANGE, url: exchangeUrl, @@ -489,11 +488,11 @@ describe('Verifiable credentials tests', () => { }, ], }); - expect(selectResults.matches).toHaveLength(1); + expect(results.matches).toHaveLength(1); }); test('continueExchange() should return issued credentials', async () => { const { - selections: [{ selectResults }], + selections: [{ selectResults: continueExchangeResults }], } = await verifiableCredentialsService.initiateExchange({ type: VC_API_EXCHANGE, url: exchangeUrl, @@ -512,7 +511,7 @@ describe('Verifiable credentials tests', () => { await verifiableCredentialsService.continueExchange({ vpRequest, credentials: - selectResults.verifiableCredential as VerifiableCredential[], + continueExchangeResults.verifiableCredential as VerifiableCredential[], }) ).toEqual(issuedPresentation); }); diff --git a/scripts/patches-build.js b/scripts/patches-build.js index ae01280f..50e89a04 100644 --- a/scripts/patches-build.js +++ b/scripts/patches-build.js @@ -27,8 +27,8 @@ async function updatePatchFile(file) { fs.readFile(`./dist/patches/${file}`, 'utf8', (err, data) => { if (err) reject(err); const newData = data.replaceAll('node_modules', '..'); - fs.writeFile(`./dist/patches/${file}`, newData, 'utf8', (err) => { - if (err) reject(err); + fs.writeFile(`./dist/patches/${file}`, newData, 'utf8', (error) => { + if (error) reject(error); console.log(`Updated ${file}`); resolve(); }); diff --git a/src/modules/claims/claims.service.ts b/src/modules/claims/claims.service.ts index 78f01334..389752cf 100644 --- a/src/modules/claims/claims.service.ts +++ b/src/modules/claims/claims.service.ts @@ -408,7 +408,7 @@ export class ClaimsService { async issueClaimRequest({ requester, token, - id, + id: requestId, subjectAgreement, registrationTypes, issuerFields, @@ -436,7 +436,7 @@ export class ClaimsService { const { claimType: role, claimTypeVersion: version } = claimData; const message: IClaimIssuance = { - id, + id: requestId, requester, claimIssuer: [this._signerService.did], acceptedBy: this._signerService.did, @@ -584,12 +584,12 @@ export class ClaimsService { * @param {RejectClaimRequestOptions} options object containing options */ async rejectClaimRequest({ - id, + id: rejectClaimRequestId, requesterDID, rejectionReason, }: RejectClaimRequestOptions): Promise { const message: IClaimRejection = { - id, + id: rejectClaimRequestId, requester: requesterDID, claimIssuer: [this._signerService.did], isRejected: true, @@ -610,8 +610,8 @@ export class ClaimsService { * * @param {DeleteClaimOptions} options object containing options */ - async deleteClaim({ id }: DeleteClaimOptions): Promise { - await this._cacheClient.deleteClaim(id); + async deleteClaim({ id: deleteClaimId }: DeleteClaimOptions): Promise { + await this._cacheClient.deleteClaim(deleteClaimId); } /** @@ -754,7 +754,7 @@ export class ClaimsService { * @param {PublishPublicClaimOptions} options object containing options * @return URl to IPFS if registrationTypes includes RegistrationTypes.OffChain */ - async publishPublicClaim({ + async publishPublicClaim({ //FIX CLAIM DATA token, // backward compatibility registrationTypes = [RegistrationTypes.OffChain], claim, @@ -785,20 +785,20 @@ export class ClaimsService { namespace: this.getNamespaceFromClaimType(claim.claimType), isAccepted: true, }); - const claimData = claims.find((c) => c.claimType === claim.claimType); + const claimDataForClaimType = claims.find((c) => c.claimType === claim.claimType); - if (!claimData) { + if (!claimDataForClaimType) { throw new Error(ERROR_MESSAGES.PUBLISH_NOT_ISSUED_CLAIM); } - const expirationTimestamp = claimData.expirationTimestamp - ? Math.floor(+claimData.expirationTimestamp / 1000) + const expirationTimestamp = claimDataForClaimType.expirationTimestamp + ? Math.floor(+claimDataForClaimType.expirationTimestamp / 1000) : undefined; await this.registerOnchain({ - ...claimData, + ...claimDataForClaimType, expirationTimestamp, - onChainProof: claimData.onChainProof as string, - acceptedBy: claimData.acceptedBy as string, + onChainProof: claimDataForClaimType.onChainProof as string, + acceptedBy: claimDataForClaimType.acceptedBy as string, }); } @@ -811,21 +811,21 @@ export class ClaimsService { if (!this._didRegistry.isClaim(payload)) { throw new Error(ERROR_MESSAGES.CLAIM_TOKEN_DATA_MISSING); } - const token = claim.token as string; + const claimToken = claim.token as string; const verifiedDid = await this._didRegistry.verifyPublicClaim( - token, + claimToken, iss as string ); if (!verifiedDid || !compareDID(verifiedDid, iss as string)) { throw new Error('Incorrect signature'); } - url = await this._didRegistry.ipfsStore.save(token); + url = await this._didRegistry.ipfsStore.save(claimToken); const data = { type: DIDAttribute.ServicePoint, value: { id: await this.getClaimId({ claimData: claimData as ClaimData }), serviceEndpoint: url, - hash: hashes.SHA256(token), + hash: hashes.SHA256(claimToken), hashAlg: 'SHA256', }, }; @@ -1277,10 +1277,10 @@ export class ClaimsService { .map(({ conditions }) => conditions) .reduce((all, cur) => all.concat(cur), []); await Promise.all( - requiredRoles.map(async (role) => { + requiredRoles.map(async (requiredRole) => { const verificationResult = await this.resolveCredentialAndVerify( subject, - role + requiredRole ); if (!verificationResult.isVerified) { throw new Error(ERROR_MESSAGES.ROLE_PREREQUISITES_NOT_MET); @@ -1341,7 +1341,7 @@ export class ClaimsService { role, version, }: ApproveRolePublishingOptions): Promise { - const erc712_type_hash = id( + const erc712TypeHash = id( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); const agreement_type_hash = id( @@ -1353,7 +1353,7 @@ export class ClaimsService { defaultAbiCoder.encode( ['bytes32', 'bytes32', 'bytes32', 'uint256', 'address'], [ - erc712_type_hash, + erc712TypeHash, id('Claim Manager'), id('1.0'), chainId, diff --git a/src/modules/domains/domains.service.ts b/src/modules/domains/domains.service.ts index 92abf416..b39d761c 100644 --- a/src/modules/domains/domains.service.ts +++ b/src/modules/domains/domains.service.ts @@ -410,8 +410,8 @@ export class DomainsService { return; } - async readName(namehash: string) { - return this._domainDefinitionReader.readName(namehash); + async readName(namehashToRead: string) { + return this._domainDefinitionReader.readName(namehashToRead); } /** @@ -461,8 +461,12 @@ export class DomainsService { 'You are not able to change ownership of organization with registered apps' ); } else { - for await (const { namespace } of apps) { - await this.changeAppOwnership({ namespace, newOwner, returnSteps }); + for await (const { namespace: ns } of apps) { + await this.changeAppOwnership({ + namespace: ns, + newOwner, + returnSteps, + }); } } } @@ -473,18 +477,18 @@ export class DomainsService { ); } - const steps = changeOwnerNamespaces.map((namespace) => { - const tx = this.changeDomainOwnerTx({ newOwner, namespace }); + const steps = changeOwnerNamespaces.map((nmspace) => { + const tx = this.changeDomainOwnerTx({ newOwner, namespace: nmspace }); return { tx, next: async ({ retryCheck }: { retryCheck?: boolean } = {}) => { if (retryCheck) { - const owner = await this.getOwner({ namespace }); + const owner = await this.getOwner({ namespace: nmspace }); if (owner === newOwner) return; } return this._signerService.send(tx); }, - info: `Changing ownership of ${namespace}`, + info: `Changing ownership of ${nmspace}`, }; }); @@ -549,18 +553,18 @@ export class DomainsService { } const steps: ReturnStepWithRetryCheck[] = changeOwnerNamespaces.map( - (namespace) => { - const tx = this.changeDomainOwnerTx({ newOwner, namespace }); + (name) => { + const tx = this.changeDomainOwnerTx({ newOwner, namespace: name }); return { tx, next: async ({ retryCheck }: { retryCheck?: boolean } = {}) => { if (retryCheck) { - const owner = await this.getOwner({ namespace }); + const owner = await this.getOwner({ namespace: name }); if (owner === newOwner) return; } return this._signerService.send(tx); }, - info: `Changing ownership of ${namespace}`, + info: `Changing ownership of ${name}`, }; } ); @@ -666,18 +670,18 @@ export class DomainsService { getLogger().info(`Already deleted: ${alreadyFinished.join(', ')}`); } - const steps = namespacesToDelete.map((namespace) => { - const tx = this.deleteDomainTx({ namespace }); + const steps = namespacesToDelete.map((n) => { + const tx = this.deleteDomainTx({ namespace: n }); return { tx, next: async ({ retryCheck }: { retryCheck?: boolean } = {}) => { if (retryCheck) { - const owner = await this.getOwner({ namespace }); + const owner = await this.getOwner({ namespace: n }); if (owner === emptyAddress) return; } return this._signerService.send(tx); }, - info: `Deleting ${namespace}`, + info: `Deleting ${n}`, }; }); @@ -737,18 +741,18 @@ export class DomainsService { getLogger().info(`Already deleted: ${alreadyFinished.join(', ')}`); } - const steps = namespacesToDelete.map((namespace) => { - const tx = this.deleteDomainTx({ namespace }); + const steps = namespacesToDelete.map((nspace) => { + const tx = this.deleteDomainTx({ namespace: nspace }); return { tx, next: async ({ retryCheck }: { retryCheck?: boolean } = {}) => { if (retryCheck) { - const owner = await this.getOwner({ namespace }); + const owner = await this.getOwner({ namespace: nspace }); if (owner === emptyAddress) return; } return this._signerService.send(tx); }, - info: `Deleting ${namespace}`, + info: `Deleting ${nspace}`, }; }); @@ -1414,6 +1418,6 @@ export class DomainsService { } get domainReader(): DomainReader { - return this._domainDefinitionReader; + return this._domainDefinitionReader; } }