Skip to content

Commit

Permalink
style: add warn for shadow variables (variables in scope that share s… (
Browse files Browse the repository at this point in the history
#663)

* 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
  • Loading branch information
whitneypurdum authored Oct 18, 2022
1 parent 97500b4 commit dd28b49
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 70 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
module.exports = {
extends: ['@energyweb'],
rules: {
"@typescript-eslint/no-shadow": "warn",
},
env: {
browser: true,
es2021: true,
Expand Down
4 changes: 2 additions & 2 deletions docs/api/classes/modules_domains.DomainsService.md
Original file line number Diff line number Diff line change
Expand Up @@ -713,13 +713,13 @@ ___

### readName

**readName**(`namehash`): `Promise`<`string`\>
**readName**(`namehashToRead`): `Promise`<`string`\>

#### Parameters

| Name | Type |
| :------ | :------ |
| `namehash` | `string` |
| `namehashToRead` | `string` |

#### Returns

Expand Down
30 changes: 15 additions & 15 deletions e2e/claims.service.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,8 @@ const roles: Record<string, IRoleDefinitionV2> = {
};
const mockGetRoleDefinition = jest
.fn()
.mockImplementation((namespace: string) => {
return roles[namespace];
.mockImplementation((roleDefNamespace: string) => {
return roles[roleDefNamespace];
});
const mockCachedDocument = jest.fn().mockImplementation((did: string) => {
return {
Expand Down Expand Up @@ -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 };

Expand All @@ -609,7 +609,7 @@ describe('Сlaim tests', () => {
});

expect(signer).toBe(issuerDID);
expect(did).toBe(requesterDID);
expect(decodedTokenDid).toBe(requesterDID);
}

expect(requester).toEqual(subjectDID);
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -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);
});

Expand Down Expand Up @@ -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())
)
);
Expand Down Expand Up @@ -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,
Expand Down
15 changes: 7 additions & 8 deletions e2e/verifiable-credentials.service.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof axios>).post.mockImplementation(() => {
return Promise.resolve({
data: { errors: [], vpRequest },
data: { errors: [], vpRequest: bloxmoveVpRequest },
});
});
getClaimsBySubject.mockResolvedValue(customerRoleClaim);
Expand All @@ -462,7 +461,7 @@ describe('Verifiable credentials tests', () => {
'getCredentialsByDefinition'
);
const {
selections: [{ selectResults }],
selections: [{ selectResults: results }],
} = await verifiableCredentialsService.initiateExchange({
type: VC_API_EXCHANGE,
url: exchangeUrl,
Expand All @@ -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,
Expand All @@ -512,7 +511,7 @@ describe('Verifiable credentials tests', () => {
await verifiableCredentialsService.continueExchange({
vpRequest,
credentials:
selectResults.verifiableCredential as VerifiableCredential<RoleCredentialSubject>[],
continueExchangeResults.verifiableCredential as VerifiableCredential<RoleCredentialSubject>[],
})
).toEqual(issuedPresentation);
});
Expand Down
4 changes: 2 additions & 2 deletions scripts/patches-build.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down
44 changes: 22 additions & 22 deletions src/modules/claims/claims.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ export class ClaimsService {
async issueClaimRequest({
requester,
token,
id,
id: requestId,
subjectAgreement,
registrationTypes,
issuerFields,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -584,12 +584,12 @@ export class ClaimsService {
* @param {RejectClaimRequestOptions} options object containing options
*/
async rejectClaimRequest({
id,
id: rejectClaimRequestId,
requesterDID,
rejectionReason,
}: RejectClaimRequestOptions): Promise<void> {
const message: IClaimRejection = {
id,
id: rejectClaimRequestId,
requester: requesterDID,
claimIssuer: [this._signerService.did],
isRejected: true,
Expand All @@ -610,8 +610,8 @@ export class ClaimsService {
*
* @param {DeleteClaimOptions} options object containing options
*/
async deleteClaim({ id }: DeleteClaimOptions): Promise<void> {
await this._cacheClient.deleteClaim(id);
async deleteClaim({ id: deleteClaimId }: DeleteClaimOptions): Promise<void> {
await this._cacheClient.deleteClaim(deleteClaimId);
}

/**
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
});
}

Expand All @@ -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',
},
};
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -1341,7 +1341,7 @@ export class ClaimsService {
role,
version,
}: ApproveRolePublishingOptions): Promise<string> {
const erc712_type_hash = id(
const erc712TypeHash = id(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
);
const agreement_type_hash = id(
Expand All @@ -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,
Expand Down
Loading

0 comments on commit dd28b49

Please sign in to comment.