From 268946f0da18d31b27bc8eefe9ae232b5ea8ecaa Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 18 Dec 2024 15:56:59 +0400 Subject: [PATCH 1/5] Serialization/deserialization tweaks for `cheqd` --- examples/CHANGELOG.md | 9 ++ examples/package.json | 8 +- packages/cheqd-blockchain-api/CHANGELOG.md | 11 ++ packages/cheqd-blockchain-api/package.json | 4 +- packages/cheqd-blockchain-api/src/index.js | 75 ++++++++----- .../cheqd-blockchain-modules/CHANGELOG.md | 7 ++ .../cheqd-blockchain-modules/package.json | 6 +- packages/credential-sdk/CHANGELOG.md | 6 ++ packages/credential-sdk/package.json | 2 +- .../src/modules/tests/did-module.js | 84 ++++++++------- .../tests/offchain-signatures-module.js | 80 +++++++------- .../src/types/accumulator/accumulator-id.js | 41 +++---- .../src/types/did/document/ident-ref.js | 8 +- ...method-ref-or-cheqd-verification-method.js | 18 +--- .../did/document/verification-method-ref.js | 8 +- .../types/did/document/verification-method.js | 93 ++++++++++------ .../types/did/offchain/service-endpoint.js | 19 ++-- .../types/did/onchain/typed-did/cheqd-did.js | 4 + .../did/onchain/typed-did/dock-did-value.js | 16 +-- .../src/types/did/onchain/typed-did/index.js | 54 ++++------ .../onchain/verification-method-signature.js | 2 +- .../src/types/generic/typed-array.js | 6 +- .../src/types/generic/typed-bytes-array.js | 6 +- .../src/types/generic/typed-bytes.js | 22 ++-- .../src/types/generic/typed-enum.js | 64 +++++------ .../src/types/generic/typed-map.js | 8 +- .../src/types/generic/typed-number.js | 4 + .../src/types/generic/typed-set.js | 6 +- .../src/types/generic/typed-struct.js | 6 +- .../src/types/generic/typed-tuple.js | 6 +- .../src/types/generic/with-base.js | 32 +++--- .../src/types/generic/with-base58.js | 25 +++-- .../src/types/generic/with-base58btc.js | 17 ++- .../src/types/generic/with-base64.js | 25 +++-- .../src/types/generic/with-qualifier.js | 32 ++++-- .../credential-sdk/src/utils/interfaces.js | 101 +++++++++++++++--- packages/dock-blockchain-api/CHANGELOG.md | 7 ++ packages/dock-blockchain-api/package.json | 4 +- packages/dock-blockchain-modules/CHANGELOG.md | 7 ++ packages/dock-blockchain-modules/package.json | 6 +- 40 files changed, 577 insertions(+), 362 deletions(-) diff --git a/examples/CHANGELOG.md b/examples/CHANGELOG.md index d73301b93..1be6136e4 100644 --- a/examples/CHANGELOG.md +++ b/examples/CHANGELOG.md @@ -1,5 +1,14 @@ # @docknetwork/sdk-examples +## 0.6.7 + +### Patch Changes + +- Updated dependencies + - @docknetwork/credential-sdk@0.21.0 + - @docknetwork/dock-blockchain-api@0.8.7 + - @docknetwork/dock-blockchain-modules@0.11.2 + ## 0.6.6 ### Patch Changes diff --git a/examples/package.json b/examples/package.json index b3b9fd736..39bc30c33 100644 --- a/examples/package.json +++ b/examples/package.json @@ -2,7 +2,7 @@ "name": "@docknetwork/sdk-examples", "private": true, "type": "module", - "version": "0.6.6", + "version": "0.6.7", "scripts": { "bbs-dock-example": "babel-node ./bbs-dock.js", "claim-deduction-example": "babel-node ./claim-deduction.js", @@ -19,9 +19,9 @@ "lint": "eslint \"*.js\"" }, "dependencies": { - "@docknetwork/credential-sdk": "0.20.0", - "@docknetwork/dock-blockchain-api": "0.8.6", - "@docknetwork/dock-blockchain-modules": "0.11.1" + "@docknetwork/credential-sdk": "0.21.0", + "@docknetwork/dock-blockchain-api": "0.8.7", + "@docknetwork/dock-blockchain-modules": "0.11.2" }, "devDependencies": { "babel-eslint": "^10.1.0", diff --git a/packages/cheqd-blockchain-api/CHANGELOG.md b/packages/cheqd-blockchain-api/CHANGELOG.md index 5880a5072..18eb04c6b 100644 --- a/packages/cheqd-blockchain-api/CHANGELOG.md +++ b/packages/cheqd-blockchain-api/CHANGELOG.md @@ -1,5 +1,16 @@ # @docknetwork/cheqd-blockchain-api +## 0.15.0 + +### Minor Changes + +- Serialization/deserialization tweaks for `cheqd` + +### Patch Changes + +- Updated dependencies + - @docknetwork/credential-sdk@0.21.0 + ## 0.14.5 ### Patch Changes diff --git a/packages/cheqd-blockchain-api/package.json b/packages/cheqd-blockchain-api/package.json index 8fb377e86..b87ced1a4 100644 --- a/packages/cheqd-blockchain-api/package.json +++ b/packages/cheqd-blockchain-api/package.json @@ -1,6 +1,6 @@ { "name": "@docknetwork/cheqd-blockchain-api", - "version": "0.14.5", + "version": "0.15.0", "license": "MIT", "main": "./dist/esm/index.js", "type": "module", @@ -34,7 +34,7 @@ }, "dependencies": { "@cheqd/sdk": "cjs", - "@docknetwork/credential-sdk": "0.20.0" + "@docknetwork/credential-sdk": "0.21.0" }, "devDependencies": { "@babel/cli": "^7.24.1", diff --git a/packages/cheqd-blockchain-api/src/index.js b/packages/cheqd-blockchain-api/src/index.js index 82c21ab2f..211e434f8 100644 --- a/packages/cheqd-blockchain-api/src/index.js +++ b/packages/cheqd-blockchain-api/src/index.js @@ -1,30 +1,37 @@ -import { AbstractApiProvider } from '@docknetwork/credential-sdk/modules/abstract/common'; +import { AbstractApiProvider } from "@docknetwork/credential-sdk/modules/abstract/common"; import { - maybeToJSON, maybeToJSONString, fmtIter, extendNull, -} from '@docknetwork/credential-sdk/utils'; +} from "@docknetwork/credential-sdk/utils"; import { DIDModule, ResourceModule, createCheqdSDK, CheqdNetwork, -} from '@cheqd/sdk'; +} from "@cheqd/sdk"; import { MsgCreateDidDocPayload, MsgUpdateDidDocPayload, MsgDeactivateDidDocPayload, protobufPackage as didProtobufPackage, -} from '@cheqd/ts-proto/cheqd/did/v2/index.js'; +} from "@cheqd/ts-proto/cheqd/did/v2/index.js"; import { MsgCreateResourcePayload, protobufPackage as resourceProtobufPackage, -} from '@cheqd/ts-proto/cheqd/resource/v2/index.js'; +} from "@cheqd/ts-proto/cheqd/resource/v2/index.js"; import { - DidRef, NamespaceDid, CheqdSetDidDocumentPayloadWithTypeUrlAndSignatures, CheqdCheqdDeactivateDidDocumentPayloadWithTypeUrlAndSignatures, CheqdCreateResourcePayloadWithTypeUrlAndSignatures, -} from '@docknetwork/credential-sdk/types'; -import { TypedEnum } from '@docknetwork/credential-sdk/types/generic'; + DidRef, + NamespaceDid, + CheqdSetDidDocumentPayloadWithTypeUrlAndSignatures, + CheqdCheqdDeactivateDidDocumentPayloadWithTypeUrlAndSignatures, + CheqdCreateResourcePayloadWithTypeUrlAndSignatures, + CheqdCreateResource, + CheqdDIDDocument, + CheqdDeactivateDidDocument, +} from "@docknetwork/credential-sdk/types"; +import { TypedEnum } from "@docknetwork/credential-sdk/types/generic"; +import { maybeToCheqdPayloadOrJSON } from "../../credential-sdk/src/utils"; export class CheqdAPI extends AbstractApiProvider { /** @@ -50,16 +57,20 @@ export class CheqdAPI extends AbstractApiProvider { }); static Payloads = extendNull({ - MsgCreateDidDoc: MsgCreateDidDocPayload, - MsgUpdateDidDoc: MsgUpdateDidDocPayload, - MsgDeactivateDidDoc: MsgDeactivateDidDocPayload, - MsgCreateResource: MsgCreateResourcePayload, + MsgCreateDidDoc: [CheqdDIDDocument, MsgCreateDidDocPayload], + MsgUpdateDidDoc: [CheqdDIDDocument, MsgUpdateDidDocPayload], + MsgDeactivateDidDoc: [ + CheqdDeactivateDidDocument, + MsgDeactivateDidDocPayload, + ], + MsgCreateResource: [CheqdCreateResource, MsgCreateResourcePayload], }); static PayloadWrappers = extendNull({ MsgCreateDidDoc: CheqdSetDidDocumentPayloadWithTypeUrlAndSignatures, MsgUpdateDidDoc: CheqdSetDidDocumentPayloadWithTypeUrlAndSignatures, - MsgDeactivateDidDoc: CheqdCheqdDeactivateDidDocumentPayloadWithTypeUrlAndSignatures, + MsgDeactivateDidDoc: + CheqdCheqdDeactivateDidDocumentPayloadWithTypeUrlAndSignatures, MsgCreateResource: CheqdCreateResourcePayloadWithTypeUrlAndSignatures, }); @@ -75,11 +86,11 @@ export class CheqdAPI extends AbstractApiProvider { if (network !== CheqdNetwork.Mainnet && network !== CheqdNetwork.Testnet) { throw new Error( `Invalid network provided: \`${network}\`, expected one of \`${fmtIter( - Object.values(CheqdNetwork), - )}\``, + Object.values(CheqdNetwork) + )}\`` ); } else if (wallet == null) { - throw new Error('`wallet` must be provided'); + throw new Error("`wallet` must be provided"); } this.ensureNotInitialized(); @@ -123,20 +134,23 @@ export class CheqdAPI extends AbstractApiProvider { * @returns {Promise} */ async stateChangeBytes(method, payload) { - const { [method]: Payload } = this.constructor.Payloads; - if (Payload == null) { + const { [method]: Payloads } = this.constructor.Payloads; + if (Payloads == null) { throw new Error( - `Can't find payload constructor for the provided method \`${method}\``, + `Can't find payload constructor for the provided method \`${method}\`` ); } - const jsonPayload = maybeToJSON(payload); + const [TypedPayload, Payload] = Payloads; + + const typedPayload = TypedPayload.from(payload); + const jsonPayload = maybeToCheqdPayloadOrJSON(typedPayload); const sdkPayload = Payload.fromPartial(jsonPayload); try { return Payload.encode(sdkPayload).finish(); } catch (err) { throw new Error( - `Failed to encode payload \`${maybeToJSONString(sdkPayload)}\`: ${err}`, + `Failed to encode payload \`${maybeToJSONString(sdkPayload)}\`: ${err}` ); } } @@ -162,28 +176,33 @@ export class CheqdAPI extends AbstractApiProvider { throw new Error(`No payload wrapper found for \`${typeUrl}\``); } - const sender = from ?? (await this.sdk.options.wallet.getAccounts())[0].address; + const sender = + from ?? (await this.sdk.options.wallet.getAccounts())[0].address; const payment = { amount: [amount], - gas: '3600000', // TODO: dynamically calculate needed amount + gas: "3600000", // TODO: dynamically calculate needed amount payer: sender, }; - const txJSON = PayloadWrapper.from(tx).toJSON(); + const txJSON = maybeToCheqdPayloadOrJSON( + PayloadWrapper.from(JSON.parse(JSON.stringify(tx.toJSON()))) + ); txJSON.typeUrl = `/${prefix}.${typeUrl}`; const res = await this.sdk.signer.signAndBroadcast( sender, [txJSON], payment, - memo ?? '', + memo ?? "" ); if (res.code) { console.error(res); throw new Error( - JSON.stringify(res, (_, value) => (typeof value === 'bigint' ? `${value.toString()}n` : value)), + JSON.stringify(res, (_, value) => + typeof value === "bigint" ? `${value.toString()}n` : value + ) ); } @@ -191,7 +210,7 @@ export class CheqdAPI extends AbstractApiProvider { } methods() { - return ['cheqd']; + return ["cheqd"]; } supportsIdentifier(id) { diff --git a/packages/cheqd-blockchain-modules/CHANGELOG.md b/packages/cheqd-blockchain-modules/CHANGELOG.md index 5bc8267f6..27b80798a 100644 --- a/packages/cheqd-blockchain-modules/CHANGELOG.md +++ b/packages/cheqd-blockchain-modules/CHANGELOG.md @@ -1,5 +1,12 @@ # @docknetwork/cheqd-blockchain-modules +## 0.13.3 + +### Patch Changes + +- Updated dependencies + - @docknetwork/credential-sdk@0.21.0 + ## 0.13.2 ### Patch Changes diff --git a/packages/cheqd-blockchain-modules/package.json b/packages/cheqd-blockchain-modules/package.json index feb053595..e1d24580a 100644 --- a/packages/cheqd-blockchain-modules/package.json +++ b/packages/cheqd-blockchain-modules/package.json @@ -1,6 +1,6 @@ { "name": "@docknetwork/cheqd-blockchain-modules", - "version": "0.13.2", + "version": "0.13.3", "type": "module", "license": "MIT", "main": "./dist/esm/index.js", @@ -33,7 +33,7 @@ "node": ">=18.0.0" }, "dependencies": { - "@docknetwork/credential-sdk": "0.20.0" + "@docknetwork/credential-sdk": "0.21.0" }, "devDependencies": { "@babel/cli": "^7.24.1", @@ -42,7 +42,7 @@ "@babel/plugin-syntax-import-attributes": "^7.25.6", "@babel/plugin-transform-modules-commonjs": "^7.24.1", "@babel/preset-env": "^7.24.3", - "@docknetwork/cheqd-blockchain-api": "0.14.5", + "@docknetwork/cheqd-blockchain-api": "0.15.0", "@rollup/plugin-alias": "^4.0.2", "@rollup/plugin-babel": "^6.0.4", "@rollup/plugin-commonjs": "^24.0.0", diff --git a/packages/credential-sdk/CHANGELOG.md b/packages/credential-sdk/CHANGELOG.md index b02fa1582..97fcc4cf3 100644 --- a/packages/credential-sdk/CHANGELOG.md +++ b/packages/credential-sdk/CHANGELOG.md @@ -1,5 +1,11 @@ # @docknetwork/credential-sdk +## 0.21.0 + +### Minor Changes + +- Serialization/deserialization tweaks for `cheqd` + ## 0.20.0 ### Minor Changes diff --git a/packages/credential-sdk/package.json b/packages/credential-sdk/package.json index d336c2ff4..cbdde0869 100644 --- a/packages/credential-sdk/package.json +++ b/packages/credential-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@docknetwork/credential-sdk", - "version": "0.20.0", + "version": "0.21.0", "license": "MIT", "type": "module", "files": [ diff --git a/packages/credential-sdk/src/modules/tests/did-module.js b/packages/credential-sdk/src/modules/tests/did-module.js index 923116f45..141145ae4 100644 --- a/packages/credential-sdk/src/modules/tests/did-module.js +++ b/packages/credential-sdk/src/modules/tests/did-module.js @@ -1,5 +1,5 @@ -import { DidKeypair, Ed25519Keypair } from '../../keypairs'; -import { DIDResolver } from '../../resolver'; +import { DidKeypair, Ed25519Keypair } from "../../keypairs"; +import { DIDResolver } from "../../resolver"; import { DIDDocument, BBSPublicKeyValue, @@ -8,21 +8,21 @@ import { PSPublicKeyValue, VerificationMethodRef, ServiceEndpoint, -} from '../../types'; -import { TypedBytes } from '../../types/generic'; -import { NoDIDError } from '../abstract/did/errors'; -import { testIf } from './common'; +} from "../../types"; +import { TypedBytes } from "../../types/generic"; +import { NoDIDError } from "../abstract/did/errors"; +import { testIf } from "./common"; // eslint-disable-next-line jest/no-export export default function generateDIDModuleTests( { did: module }, { DID }, - filter = () => true, + filter = () => true ) { const test = testIf(filter); describe(`Using ${module.constructor.name}`, () => { - test('Creates basic `DIDDocument` with keys', async () => { + test("Creates basic `DIDDocument` with keys", async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -33,11 +33,11 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); }); - test('Creates `DIDDocument` containing BBS/BBSPlus/PS keys', async () => { + test("Creates `DIDDocument` containing BBS/BBSPlus/PS keys", async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -57,11 +57,11 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); }); - test('Updates `DIDDocument` containing BBS/BBSPlus/PS keys', async () => { + test("Updates `DIDDocument` containing BBS/BBSPlus/PS keys", async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -69,7 +69,7 @@ export default function generateDIDModuleTests( const bbsKey = new DidKey(new BBSPublicKeyValue(TypedBytes.random(100))); const bbsPlusKey = new DidKey( - new BBSPlusPublicKeyValue(TypedBytes.random(100)), + new BBSPlusPublicKeyValue(TypedBytes.random(100)) ); const psKey = new DidKey(new PSPublicKeyValue(TypedBytes.random(1000))); @@ -78,7 +78,7 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); document.addKey([did, document.nextKeyIndex()], bbsKey); @@ -88,7 +88,7 @@ export default function generateDIDModuleTests( await module.updateDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); expect(document.didKeys().toJSON()).toEqual([ @@ -102,17 +102,17 @@ export default function generateDIDModuleTests( ]); }); - test('Creates `DIDDocument` containing services', async () => { + test("Creates `DIDDocument` containing services", async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); const didKeypair = new DidKeypair([did, 1], keyPair); - const service1 = new ServiceEndpoint('LinkedDomains', [ - 'ServiceEndpoint#1', + const service1 = new ServiceEndpoint("LinkedDomains", [ + "ServiceEndpoint#1", ]); - const service2 = new ServiceEndpoint('LinkedDomains', [ - 'ServiceEndpoint#2', + const service2 = new ServiceEndpoint("LinkedDomains", [ + "ServiceEndpoint#2", ]); const document = DIDDocument.create(did, [didKeypair.didKey()], [], { @@ -123,21 +123,21 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); }); - test('Updates `DIDDocument` containing services', async () => { + test("Updates `DIDDocument` containing services", async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); const didKeypair = new DidKeypair([did, 1], keyPair); - const service1 = new ServiceEndpoint('LinkedDomains', [ - 'ServiceEndpoint#1', + const service1 = new ServiceEndpoint("LinkedDomains", [ + "ServiceEndpoint#1", ]); - const service2 = new ServiceEndpoint('LinkedDomains', [ - 'ServiceEndpoint#2', + const service2 = new ServiceEndpoint("LinkedDomains", [ + "ServiceEndpoint#2", ]); const document = DIDDocument.create(did, [didKeypair.didKey()]); @@ -145,24 +145,24 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); - document.addServiceEndpoint([did, 'service1'], service1); - document.addServiceEndpoint([did, 'service2'], service2); + document.addServiceEndpoint([did, "service1"], service1); + document.addServiceEndpoint([did, "service2"], service2); await module.updateDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); - document.removeServiceEndpoint([did, 'service2']); + document.removeServiceEndpoint([did, "service2"]); await module.updateDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); expect(document.service.length).toEqual(1); @@ -186,25 +186,27 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair2); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); document.removeKey([did, 2]); await module.updateDocument(document, didKeypair1); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); document.addKey([did, 3], didKeypair3.didKey()); - await expect(() => module.updateDocument(document, didKeypair2)).rejects.toThrow(); + await expect(() => + module.updateDocument(document, didKeypair2) + ).rejects.toThrow(); await module.updateDocument(document, didKeypair1); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); }); - test('Removes (deactivates) `DIDDocument`', async () => { + test("Removes (deactivates) `DIDDocument`", async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -214,12 +216,12 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); await module.removeDocument(did, didKeypair); await expect(() => module.getDocument(did)).rejects.toThrow( - new NoDIDError(did), + new NoDIDError(did) ); }); @@ -227,11 +229,11 @@ export default function generateDIDModuleTests( const did = DID.random(); await expect(() => module.getDocument(did)).rejects.toThrow( - new NoDIDError(did), + new NoDIDError(did) ); }); - test('`DIDResolver`', async () => { + test("`DIDResolver`", async () => { const resolver = new DIDResolver(module); const did = DID.random(); diff --git a/packages/credential-sdk/src/modules/tests/offchain-signatures-module.js b/packages/credential-sdk/src/modules/tests/offchain-signatures-module.js index 25acbca8f..fac7e0aba 100644 --- a/packages/credential-sdk/src/modules/tests/offchain-signatures-module.js +++ b/packages/credential-sdk/src/modules/tests/offchain-signatures-module.js @@ -1,4 +1,4 @@ -import { DidKeypair, Ed25519Keypair } from '../../keypairs'; +import { DidKeypair, Ed25519Keypair } from "../../keypairs"; import { BBSParams, BBSParamsValue, @@ -14,23 +14,21 @@ import { PSParamsValue, PSPublicKey, PSPublicKeyValue, -} from '../../types'; -import { testIf } from './common'; -import { TypedBytes } from '../../types/generic'; -import { stringToU8a } from '../../utils'; +} from "../../types"; +import { testIf } from "./common"; +import { TypedBytes } from "../../types/generic"; +import { stringToU8a } from "../../utils"; // eslint-disable-next-line jest/no-export export default function generateOffchainSignatureModuleTests( - { - did: didModule, offchainSignatures, bbs, bbsPlus, ps, - }, + { did: didModule, offchainSignatures, bbs, bbsPlus, ps }, { DID, OffchainSignaturesParamsRef }, - filter = () => true, + filter = () => true ) { const test = testIf(filter); describe(`Checks ${didModule.constructor.name} and ${offchainSignatures.constructor.name} with all public keys and params`, () => { - test('Generates a `DIDDocument` with `OffchainPublicKey` and creates a `OffchainParameters` owned by this DID', async () => { + test("Generates a `DIDDocument` with `OffchainPublicKey` and creates a `OffchainParameters` owned by this DID", async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -38,51 +36,51 @@ export default function generateOffchainSignatureModuleTests( await didModule.createDocument( DIDDocument.create(did, [didKeypair.didKey()]), - didKeypair, + didKeypair ); const bbsParamsId = await offchainSignatures.nextParamsId(did); const bbsParamsRef = new OffchainSignaturesParamsRef(did, bbsParamsId); const bbsParams = new BBSParams( - new BBSParamsValue(TypedBytes.random(100), stringToU8a('bbs')), + new BBSParamsValue(TypedBytes.random(100), stringToU8a("bbs")) ); await offchainSignatures.addParams( bbsParamsId, bbsParams, did, - didKeypair, + didKeypair ); const bbsPlusParamsId = await offchainSignatures.nextParamsId(did); const bbsPlusParamsRef = new OffchainSignaturesParamsRef( did, - bbsPlusParamsId, + bbsPlusParamsId ); const bbsPlusParams = new BBSPlusParams( - new BBSPlusParamsValue(TypedBytes.random(100), stringToU8a('bbs+')), + new BBSPlusParamsValue(TypedBytes.random(100), stringToU8a("bbs+")) ); await offchainSignatures.addParams( bbsPlusParamsId, bbsPlusParams, did, - didKeypair, + didKeypair ); const psParamsId = await offchainSignatures.nextParamsId(did); const psParamsRef = new OffchainSignaturesParamsRef(did, psParamsId); const psParams = new PSParams( - new PSParamsValue(TypedBytes.random(100), stringToU8a('ps')), + new PSParamsValue(TypedBytes.random(100), stringToU8a("ps")) ); await offchainSignatures.addParams(psParamsId, psParams, did, didKeypair); const bbsKey = new BBSPublicKey( - new BBSPublicKeyValue(TypedBytes.random(100), bbsParamsRef), + new BBSPublicKeyValue(TypedBytes.random(100), bbsParamsRef) ); const bbsPlusKey = new BBSPlusPublicKey( - new BBSPlusPublicKeyValue(TypedBytes.random(100), bbsPlusParamsRef), + new BBSPlusPublicKeyValue(TypedBytes.random(100), bbsPlusParamsRef) ); const psKey = new PSPublicKey( - new PSPublicKeyValue(TypedBytes.random(1000), psParamsRef), + new PSPublicKeyValue(TypedBytes.random(1000), psParamsRef) ); const document = DIDDocument.create(did, [ @@ -95,27 +93,27 @@ export default function generateOffchainSignatureModuleTests( await didModule.updateDocument(document, didKeypair); expect((await didModule.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); expect( - (await offchainSignatures.getParams(did, bbsParamsId)).toJSON(), + (await offchainSignatures.getParams(did, bbsParamsId)).toJSON() ).toEqual(bbsParams.toJSON()); expect( - (await offchainSignatures.getParams(did, bbsPlusParamsId)).toJSON(), + (await offchainSignatures.getParams(did, bbsPlusParamsId)).toJSON() ).toEqual(bbsPlusParams.toJSON()); expect( - (await offchainSignatures.getParams(did, psParamsId)).toJSON(), + (await offchainSignatures.getParams(did, psParamsId)).toJSON() ).toEqual(psParams.toJSON()); expect( - (await offchainSignatures.getAllParamsByDid(did)).toJSON().sort(), + (await offchainSignatures.getAllParamsByDid(did)).toJSON().sort() ).toEqual( [ [bbsParamsId.toJSON(), bbsParams.toJSON()], [bbsPlusParamsId.toJSON(), bbsPlusParams.toJSON()], [psParamsId.toJSON(), psParams.toJSON()], - ].sort(), + ].sort() ); expect((await bbsKey.withParams(offchainSignatures)).toJSON()).toEqual({ @@ -123,7 +121,7 @@ export default function generateOffchainSignatureModuleTests( }); expect( - (await bbsPlusKey.withParams(offchainSignatures)).toJSON(), + (await bbsPlusKey.withParams(offchainSignatures)).toJSON() ).toEqual({ bbsPlus: { ...bbsPlusKey.toJSON().bbsPlus, @@ -139,7 +137,7 @@ export default function generateOffchainSignatureModuleTests( }); }); - test('Returns `null` in case of missing params', async () => { + test("Returns `null` in case of missing params", async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); const didKeypair = new DidKeypair([did, 1], keyPair); @@ -151,17 +149,19 @@ export default function generateOffchainSignatureModuleTests( await didModule.createDocument(document, didKeypair); const psKey = new PSPublicKey( - new PSPublicKeyValue(TypedBytes.random(1000), psParamsRef), + new PSPublicKeyValue(TypedBytes.random(1000), psParamsRef) ); expect( await offchainSignatures.getParams( did, - await offchainSignatures.nextParamsId(did), - ), + await offchainSignatures.nextParamsId(did) + ) ).toBe(null); - await expect(() => psKey.withParams(offchainSignatures)).rejects.toThrow(); + await expect(() => + psKey.withParams(offchainSignatures) + ).rejects.toThrow(); }); }); @@ -184,7 +184,7 @@ export default function generateOffchainSignatureModuleTests( ]; describe.each(cases)( - 'Checks basic workflow for each module', + "Checks basic workflow for each module", ({ module, PublicKey, Params }) => { test(`Generates a \`DIDDocument\` with \`OffchainPublicKey\` and creates a \`OffchainParameters\` owned by this DID using ${module.constructor.name} with ${PublicKey.name} and ${Params.name}`, async () => { const did = DID.random(); @@ -194,7 +194,7 @@ export default function generateOffchainSignatureModuleTests( await didModule.createDocument( DIDDocument.create(did, [didKeypair.didKey()]), - didKeypair, + didKeypair ); const id = await offchainSignatures.nextParamsId(did); @@ -202,8 +202,8 @@ export default function generateOffchainSignatureModuleTests( const params = new Params( new Params.Class( TypedBytes.random(100), - stringToU8a(module.constructor.name), - ), + stringToU8a(module.constructor.name) + ) ); expect(await module.getParams(did, id)).toEqual(null); @@ -211,7 +211,7 @@ export default function generateOffchainSignatureModuleTests( await module.addParams(id, params, did, didKeypair); const key = new PublicKey( - new PublicKey.Class(TypedBytes.random(100), ref), + new PublicKey.Class(TypedBytes.random(100), ref) ); const document = DIDDocument.create(did, [ @@ -222,13 +222,13 @@ export default function generateOffchainSignatureModuleTests( await didModule.updateDocument(document, didKeypair); expect((await didModule.getDocument(did)).toJSON()).toEqual( - document.toJSON(), + document.toJSON() ); expect((await module.getParams(did, id)).toJSON()).toEqual( - params.toJSON(), + params.toJSON() ); }); - }, + } ); } diff --git a/packages/credential-sdk/src/types/accumulator/accumulator-id.js b/packages/credential-sdk/src/types/accumulator/accumulator-id.js index bbccc27a9..51bbec9cc 100644 --- a/packages/credential-sdk/src/types/accumulator/accumulator-id.js +++ b/packages/credential-sdk/src/types/accumulator/accumulator-id.js @@ -1,4 +1,4 @@ -import { CheqdMainnetDid, CheqdTestnetDid, DidRef } from '../did'; +import { CheqdMainnetDid, CheqdTestnetDid, DidRef } from "../did"; import { TypedBytes, TypedEnum, @@ -6,33 +6,35 @@ import { sized, withFrom, withQualifier, -} from '../generic'; +} from "../generic"; export class AccumulatorId extends withFrom( withQualifier(TypedEnum, true), - (value, from) => { + (valueWithUncheckedPrefix, from) => { + const value = + typeof valueWithUncheckedPrefix === "string" && + valueWithUncheckedPrefix.startsWith("dock:accumulator:") + ? `accumulator:dock:${valueWithUncheckedPrefix.slice(17)}` + : valueWithUncheckedPrefix; + try { // eslint-disable-next-line no-use-before-define return from(DockAccumulatorIdValue.from(value)); } catch { return from(value); } - }, -) { - static Qualifier = 'accumulator:'; - - toJSON() { - return String(this); } +) { + static Qualifier = "accumulator:"; } export class CheqdAccumulatorIdValue extends withQualifier(DidRef) { - static Qualifier = 'accumulator:cheqd:'; + static Qualifier = "accumulator:cheqd:"; static Ident = TypedUUID; static fromUnqualifiedString(str) { - const lastColon = str.lastIndexOf(':'); + const lastColon = str.lastIndexOf(":"); const did = `did:cheqd:${str.slice(0, lastColon)}`; const id = str.slice(lastColon + 1); @@ -41,11 +43,11 @@ export class CheqdAccumulatorIdValue extends withQualifier(DidRef) { toEncodedString() { const { did, value } = this; - let prefix = ''; + let prefix = ""; if (did.value instanceof CheqdTestnetDid) { - prefix = 'testnet'; + prefix = "testnet"; } else if (did.value instanceof CheqdMainnetDid) { - prefix = 'mainnet'; + prefix = "mainnet"; } return `${prefix}:${did.toEncodedString()}:${value}`; @@ -60,10 +62,11 @@ export class DockAccumulatorIdIdent extends withQualifier( withFrom( sized(TypedBytes), // eslint-disable-next-line no-use-before-define - (value, from) => (value instanceof DockAccumulatorId ? value[1] : from(value)), - ), + (value, from) => + value instanceof DockAccumulatorId ? value[1] : from(value) + ) ) { - static Qualifier = 'accumulator:dock:'; + static Qualifier = "accumulator:dock:"; static Size = 32; @@ -79,7 +82,7 @@ export class DockAccumulatorIdIdent extends withQualifier( export class CheqdAccumulatorId extends AccumulatorId { static Class = CheqdAccumulatorIdValue; - static Type = 'cheqd'; + static Type = "cheqd"; static random(did) { return new this(this.Class.random(did)); @@ -89,7 +92,7 @@ export class CheqdAccumulatorId extends AccumulatorId { export class DockAccumulatorId extends AccumulatorId { static Class = DockAccumulatorIdIdent; - static Type = 'dock'; + static Type = "dock"; static random() { return new this(this.Class.random()); diff --git a/packages/credential-sdk/src/types/did/document/ident-ref.js b/packages/credential-sdk/src/types/did/document/ident-ref.js index f0452bdb9..7189ce985 100644 --- a/packages/credential-sdk/src/types/did/document/ident-ref.js +++ b/packages/credential-sdk/src/types/did/document/ident-ref.js @@ -1,8 +1,8 @@ -import { withQualifier, TypedTuple, TypedString } from '../../generic'; -import { NamespaceDid } from '../onchain/typed-did'; +import { withQualifier, TypedTuple, TypedString } from "../../generic"; +import { NamespaceDid } from "../onchain/typed-did"; export default class IdentRef extends withQualifier(TypedTuple) { - static Qualifier = ''; + static Qualifier = ""; static Ident = TypedString; @@ -40,7 +40,7 @@ export default class IdentRef extends withQualifier(TypedTuple) { return `${did}#${value}`; } - toJSON() { + toCheqdPayload() { return this.toString(); } } diff --git a/packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js b/packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js index d0a884726..3a96bb250 100644 --- a/packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js +++ b/packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js @@ -1,22 +1,14 @@ -import VerificationMethodRef from './verification-method-ref'; -import { CheqdVerificationMethod } from './verification-method'; -import { withFrom } from '../../generic'; +import VerificationMethodRef from "./verification-method-ref"; +import { CheqdVerificationMethodAssertion } from "./verification-method"; +import { withFrom } from "../../generic"; export default class VerificationMethodRefOrCheqdVerificationMethod extends withFrom( VerificationMethodRef, (value, from) => { try { - return class CheqdVerificationMethodToJSONString extends CheqdVerificationMethod { - toJSON() { - return JSON.stringify(JSON.stringify(super.toJSON())); - } - - static from(obj) { - return typeof obj === 'string' ? super.fromJSON(JSON.parse(JSON.parse(obj))) : super.from(obj); - } - }.from(value); + return CheqdVerificationMethodAssertion.from(value); } catch { return from(value); } - }, + } ) {} diff --git a/packages/credential-sdk/src/types/did/document/verification-method-ref.js b/packages/credential-sdk/src/types/did/document/verification-method-ref.js index 235d6e387..cf93bba2e 100644 --- a/packages/credential-sdk/src/types/did/document/verification-method-ref.js +++ b/packages/credential-sdk/src/types/did/document/verification-method-ref.js @@ -1,8 +1,8 @@ -import { withQualifier, TypedTuple, TypedNumber } from '../../generic'; -import { NamespaceDid } from '../onchain/typed-did'; +import { withQualifier, TypedTuple, TypedNumber } from "../../generic"; +import { NamespaceDid } from "../onchain/typed-did"; export default class VerificationMethodRef extends withQualifier(TypedTuple) { - static Qualifier = ''; + static Qualifier = ""; static Classes = [NamespaceDid, TypedNumber]; @@ -32,7 +32,7 @@ export default class VerificationMethodRef extends withQualifier(TypedTuple) { return `${did}#keys-${index}`; } - toJSON() { + toCheqdPayload() { return this.toEncodedString(); } } diff --git a/packages/credential-sdk/src/types/did/document/verification-method.js b/packages/credential-sdk/src/types/did/document/verification-method.js index 9ce3b129e..c66f46d45 100644 --- a/packages/credential-sdk/src/types/did/document/verification-method.js +++ b/packages/credential-sdk/src/types/did/document/verification-method.js @@ -1,6 +1,11 @@ import { - withFrom, TypedStruct, withBase58, TypedBytes, option, TypedString, -} from '../../generic'; + withFrom, + TypedStruct, + withBase58, + TypedBytes, + option, + TypedString, +} from "../../generic"; import { BBDT16PublicKey, BBDT16PublicKeyValue, @@ -10,12 +15,12 @@ import { BBSPublicKeyValue, PSPublicKey, PSPublicKeyValue, -} from '../../offchain-signatures'; +} from "../../offchain-signatures"; import { PublicKeyEd25519, PublicKeySecp256k1, PublicKeySr25519, -} from '../../public-keys'; +} from "../../public-keys"; import { EcdsaSecp256k1VerKeyName, Ed255192020VerKeyName, @@ -25,20 +30,29 @@ import { Bls12381BBS23DockVerKeyName, Bls12381PSDockVerKeyName, Bls12381BBDT16DockVerKeyName, -} from '../../../vc/crypto'; -import { Ed25519Verification2018Method, Ed25519Verification2020Method, VerificationMethodType } from './verification-method-type'; -import VerificationMethodRef from './verification-method-ref'; -import { NamespaceDid } from '../onchain/typed-did'; +} from "../../../vc/crypto"; +import { + Ed25519Verification2018Method, + Ed25519Verification2020Method, + VerificationMethodType, +} from "./verification-method-type"; +import VerificationMethodRef from "./verification-method-ref"; +import { NamespaceDid } from "../onchain/typed-did"; import { - fmtIter, valueBytes, filterObj, -} from '../../../utils'; + fmtIter, + valueBytes, + filterObj, + maybeToCheqdPayloadOrJSON, +} from "../../../utils"; export class PublicKeyBase58 extends withBase58(TypedBytes) {} // eslint-disable-next-line no-use-before-define -export class VerificationMethod extends withFrom(TypedStruct, (value, from) => (value instanceof CheqdVerificationMethod - ? value.toVerificationMethod() - : from(value))) { +export class VerificationMethod extends withFrom(TypedStruct, (value, from) => + value instanceof CheqdVerificationMethod + ? value.toVerificationMethod() + : from(value) +) { static Classes = { id: VerificationMethodRef, type: VerificationMethodType, @@ -51,27 +65,27 @@ export class VerificationMethod extends withFrom(TypedStruct, (value, from) => ( isOffchain() { return !( - this.type instanceof Ed25519Verification2018Method - || this.type instanceof Ed25519Verification2020Method + this.type instanceof Ed25519Verification2018Method || + this.type instanceof Ed25519Verification2020Method ); } publicKey() { const bytes = ( - this.publicKeyBase58 - || this.publicKeyBase64 - || this.publicKeyJwk - || this.publicKeyHex + this.publicKeyBase58 || + this.publicKeyBase64 || + this.publicKeyJwk || + this.publicKeyHex )?.bytes; if (bytes == null) { throw new Error( `Expected either of ${fmtIter([ - 'publicKeyBase58', - 'publicKeyBase64', - 'publicKeyJwk', - 'publicKeyHex', - ])} to be specified`, + "publicKeyBase58", + "publicKeyBase64", + "publicKeyJwk", + "publicKeyHex", + ])} to be specified` ); } @@ -104,7 +118,7 @@ export class VerificationMethod extends withFrom(TypedStruct, (value, from) => ( ref, didKey.publicKey.constructor.VerKeyType, ref[0], - valueBytes(didKey.publicKey), + valueBytes(didKey.publicKey) ); } @@ -114,7 +128,7 @@ export class VerificationMethod extends withFrom(TypedStruct, (value, from) => ( this.id, this.controller, this.type, - valueBytes(this.publicKey()), + valueBytes(this.publicKey()) ); } @@ -125,9 +139,10 @@ export class VerificationMethod extends withFrom(TypedStruct, (value, from) => ( export class CheqdVerificationMethod extends withFrom( TypedStruct, - (value, from) => (value instanceof VerificationMethod - ? from(value.toCheqdVerificationMethod()) - : from(value)), + (value, from) => + value instanceof VerificationMethod + ? from(value.toCheqdVerificationMethod()) + : from(value) ) { static Classes = { id: VerificationMethodRef, @@ -138,8 +153,8 @@ export class CheqdVerificationMethod extends withFrom( isOffchain() { return !( - this.verificationMethodType instanceof Ed25519Verification2018Method - || this.verificationMethodType instanceof Ed25519Verification2020Method + this.verificationMethodType instanceof Ed25519Verification2018Method || + this.verificationMethodType instanceof Ed25519Verification2020Method ); } @@ -148,7 +163,21 @@ export class CheqdVerificationMethod extends withFrom( this.id, this.verificationMethodType, this.controller, - this.verificationMaterial, + this.verificationMaterial ); } } + +export class CheqdVerificationMethodAssertion extends CheqdVerificationMethod { + toCheqdPayload() { + return JSON.stringify( + JSON.stringify(this.apply(maybeToCheqdPayloadOrJSON)) + ); + } + + static from(obj) { + return typeof obj === "string" + ? super.fromJSON(JSON.parse(JSON.parse(obj))) + : super.from(obj); + } +} diff --git a/packages/credential-sdk/src/types/did/offchain/service-endpoint.js b/packages/credential-sdk/src/types/did/offchain/service-endpoint.js index 2add085be..32bab6dd9 100644 --- a/packages/credential-sdk/src/types/did/offchain/service-endpoint.js +++ b/packages/credential-sdk/src/types/did/offchain/service-endpoint.js @@ -1,4 +1,4 @@ -import { maybeToNumber } from '../../../utils'; +import { maybeToJSONString, maybeToNumber } from "../../../utils"; import { TypedStruct, TypedString, @@ -7,17 +7,17 @@ import { createPlaceholder, TypedMap, Any, -} from '../../generic'; +} from "../../generic"; const LinkedDomainsPlaceholder = createPlaceholder((value) => { if ( - +maybeToNumber(value) === 0b0001 - || String(value) === 'LinkedDomains' - || value == null + +maybeToNumber(value) === 0b0001 || + String(value) === "LinkedDomains" || + value == null ) { return 0b0001; } else { - throw new Error(`Unknown value \`${value}\``); + throw new Error(`Unknown value \`${maybeToJSONString(value)}\``); } }); @@ -35,13 +35,16 @@ export class ServiceEndpointType extends TypedEnum { } } export class LinkedDomains extends ServiceEndpointType { - static Type = 'LinkedDomains'; + static Type = "LinkedDomains"; static Class = LinkedDomainsPlaceholder; - toJSON() { return this.constructor.Type; } + + apply(fn) { + return fn(this.constructor.Type); + } } ServiceEndpointType.bindVariants(LinkedDomains); diff --git a/packages/credential-sdk/src/types/did/onchain/typed-did/cheqd-did.js b/packages/credential-sdk/src/types/did/onchain/typed-did/cheqd-did.js index fdc1f7eb9..c65dc627a 100644 --- a/packages/credential-sdk/src/types/did/onchain/typed-did/cheqd-did.js +++ b/packages/credential-sdk/src/types/did/onchain/typed-did/cheqd-did.js @@ -58,6 +58,10 @@ export class CheqdDid extends withQualifier(TypedEnum, true) { toJSON() { return String(this); } + + toCheqdPayload() { + return String(this); + } } export class CheqdTestnetDid extends CheqdDid { diff --git a/packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js b/packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js index e04d4fbc7..5dfbab114 100644 --- a/packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js +++ b/packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js @@ -1,14 +1,14 @@ -import { DockDIDQualifier } from '../constants'; -import { decodeFromSS58, encodeAsSS58, isHex } from '../../../../utils'; +import { DockDIDQualifier } from "../constants"; +import { decodeFromSS58, encodeAsSS58, isHex } from "../../../../utils"; import { withQualifier, TypedBytes, sized, TypedNumber, TypedStruct, -} from '../../../generic'; -import DidOrDidMethodKeySignature from './signature'; -import { Signature } from '../../../signatures'; +} from "../../../generic"; +import DidOrDidMethodKeySignature from "./signature"; +import { Signature } from "../../../signatures"; /** * `did:dock:*` @@ -16,7 +16,7 @@ import { Signature } from '../../../signatures'; export default class DockDidValue extends sized(withQualifier(TypedBytes)) { static Qualifier = DockDIDQualifier; - static Type = 'did'; + static Type = "did"; static Size = 32; @@ -35,7 +35,7 @@ export default class DockDidValue extends sized(withQualifier(TypedBytes)) { // eslint-disable-next-line no-use-before-define return new DockDidSignature( // eslint-disable-next-line no-use-before-define - new DockDidSignatureValue(this, keyPair.keyId, keyPair.sign(bytes)), + new DockDidSignatureValue(this, keyPair.keyId, keyPair.sign(bytes)) ); } } @@ -49,7 +49,7 @@ export class DockDidSignatureValue extends TypedStruct { } export class DockDidSignature extends DidOrDidMethodKeySignature { - static Type = 'didSignature'; + static Type = "didSignature"; static Class = DockDidSignatureValue; } diff --git a/packages/credential-sdk/src/types/did/onchain/typed-did/index.js b/packages/credential-sdk/src/types/did/onchain/typed-did/index.js index fa23b2d4a..6e00d6148 100644 --- a/packages/credential-sdk/src/types/did/onchain/typed-did/index.js +++ b/packages/credential-sdk/src/types/did/onchain/typed-did/index.js @@ -1,9 +1,9 @@ -import { DidMethodKeyPublicKey, DidMethodKeySignature } from './did-method-key'; -import DockDidValue, { DockDidSignature } from './dock-did-value'; -import { TypedEnum, TypedTuple, withQualifier } from '../../../generic'; -import { CheqdDid } from './cheqd-did'; -import { withExtendedStaticProperties } from '../../../../utils'; -import DidOrDidMethodKeySignature from './signature'; +import { DidMethodKeyPublicKey, DidMethodKeySignature } from "./did-method-key"; +import DockDidValue, { DockDidSignature } from "./dock-did-value"; +import { TypedEnum, TypedTuple, withQualifier } from "../../../generic"; +import { CheqdDid } from "./cheqd-did"; +import { withExtendedStaticProperties } from "../../../../utils"; +import DidOrDidMethodKeySignature from "./signature"; export class DockDidOrDidMethodKey extends withQualifier(TypedEnum, true) { /** @@ -48,7 +48,7 @@ export class DockDidOrDidMethodKey extends withQualifier(TypedEnum, true) { async changeState(api, method, name, payload, keyRef) { return await method( payload, - await this.signStateChange(api, name, payload, keyRef), + await this.signStateChange(api, name, payload, keyRef) ); } @@ -104,19 +104,11 @@ export class DidMethodKey extends DockDidOrDidMethodKey { DockDidOrDidMethodKey.bindVariants(DockDid, DidMethodKey); -class DockDidValueToString extends DockDidValue { - toJSON() { - return String(this); - } -} - -class DidMethodKeyPublicKeyToString extends DidMethodKeyPublicKey { - toJSON() { +export class NamespaceDid extends withQualifier(TypedEnum, true) { + toCheqdPayload() { return String(this); } -} -export class NamespaceDid extends withQualifier(TypedEnum, true) { toJSON() { return String(this); } @@ -141,29 +133,29 @@ export class NamespaceDid extends withQualifier(TypedEnum, true) { return super.from( value instanceof DockDidOrDidMethodKey && value.isDid ? { dock: value.asDid } - : value, + : value ); } } class DockNamespaceDid extends NamespaceDid { - static Qualifier = 'did:dock:'; + static Qualifier = "did:dock:"; - static Type = 'dock'; + static Type = "dock"; - static Class = DockDidValueToString; + static Class = DockDidValue; } class DidNamespaceKey extends NamespaceDid { - static Qualifier = 'did:key:'; + static Qualifier = "did:key:"; - static Type = 'didMethodKey'; + static Type = "didMethodKey"; - static Class = DidMethodKeyPublicKeyToString; + static Class = DidMethodKeyPublicKey; } class CheqdNamespaceDid extends NamespaceDid { - static Qualifier = 'did:cheqd:'; + static Qualifier = "did:cheqd:"; - static Type = 'cheqd'; + static Type = "cheqd"; static Class = CheqdDid; } @@ -171,10 +163,10 @@ class CheqdNamespaceDid extends NamespaceDid { NamespaceDid.bindVariants(DockNamespaceDid, DidNamespaceKey, CheqdNamespaceDid); export class DidRef extends withExtendedStaticProperties( - ['Ident'], - withQualifier(TypedTuple), + ["Ident"], + withQualifier(TypedTuple) ) { - static Qualifier = ''; + static Qualifier = ""; static get Classes() { return [NamespaceDid, this.Ident]; @@ -217,8 +209,8 @@ export class DidRef extends withExtendedStaticProperties( DidOrDidMethodKeySignature.bindVariants( DockDidSignature, - DidMethodKeySignature, + DidMethodKeySignature ); export { DockDidValue, DidMethodKeyPublicKey }; -export * from './cheqd-did'; +export * from "./cheqd-did"; diff --git a/packages/credential-sdk/src/types/did/onchain/verification-method-signature.js b/packages/credential-sdk/src/types/did/onchain/verification-method-signature.js index b968e42f8..50e1bfb69 100644 --- a/packages/credential-sdk/src/types/did/onchain/verification-method-signature.js +++ b/packages/credential-sdk/src/types/did/onchain/verification-method-signature.js @@ -5,7 +5,7 @@ import { VerificationMethodRef } from '../document'; import { DidKeypair } from '../../../keypairs'; class BytesSignatureEd25519Value extends SignatureEd25519Value { - toJSON() { + toCheqdPayload() { return this.bytes; } } diff --git a/packages/credential-sdk/src/types/generic/typed-array.js b/packages/credential-sdk/src/types/generic/typed-array.js index 39e71902d..f7bce8685 100644 --- a/packages/credential-sdk/src/types/generic/typed-array.js +++ b/packages/credential-sdk/src/types/generic/typed-array.js @@ -1,6 +1,6 @@ import { ArrayWithoutPrototypeMethods, ensureArrayLike } from '../../utils'; import { withExtendedStaticProperties } from '../../utils/inheritance'; -import { maybeEq, maybeFrom, maybeToJSON } from '../../utils/interfaces'; +import { maybeEq, maybeFrom } from '../../utils/interfaces'; import withBase from './with-base'; import withCatchNull from './with-catch-null'; import withEq from './with-eq'; @@ -47,8 +47,8 @@ class TypedArray extends withBase(ArrayWithoutPrototypeMethods) { ); } - toJSON() { - return [...Array.prototype.values.call(this)].map(maybeToJSON); + apply(fn) { + return [...this].map(fn); } static fromApi(arr) { diff --git a/packages/credential-sdk/src/types/generic/typed-bytes-array.js b/packages/credential-sdk/src/types/generic/typed-bytes-array.js index 1b64cd096..fc94a0705 100644 --- a/packages/credential-sdk/src/types/generic/typed-bytes-array.js +++ b/packages/credential-sdk/src/types/generic/typed-bytes-array.js @@ -1,4 +1,4 @@ -import TypedBytes from './typed-bytes'; +import TypedBytes from "./typed-bytes"; export default class TypedBytesArray extends TypedBytes { get value() { @@ -6,6 +6,10 @@ export default class TypedBytesArray extends TypedBytes { } toJSON() { + return Array.from(this); + } + + toCheqdPayload() { return this.value; } } diff --git a/packages/credential-sdk/src/types/generic/typed-bytes.js b/packages/credential-sdk/src/types/generic/typed-bytes.js index bc75b44c0..8630d18cc 100644 --- a/packages/credential-sdk/src/types/generic/typed-bytes.js +++ b/packages/credential-sdk/src/types/generic/typed-bytes.js @@ -3,12 +3,12 @@ import { randomAsU8a, u8aToHex, u8aToU8a, -} from '../../utils/bytes'; -import { ensureByte } from '../../utils'; -import { ArrayWithoutPrototypeMethods } from '../../utils/generic'; -import withBase from './with-base'; -import withCatchNull from './with-catch-null'; -import withEq from './with-eq'; +} from "../../utils/bytes"; +import { ensureByte } from "../../utils"; +import { ArrayWithoutPrototypeMethods } from "../../utils/generic"; +import withBase from "./with-base"; +import withCatchNull from "./with-catch-null"; +import withEq from "./with-eq"; class TypedBytes extends withBase(ArrayWithoutPrototypeMethods) { constructor(value) { @@ -41,7 +41,7 @@ class TypedBytes extends withBase(ArrayWithoutPrototypeMethods) { // eslint-disable-next-line no-bitwise if (!Number.isInteger(size) || (size & 65535) !== size || !size) { throw new Error( - `Expected a natural number between 1 and 65535, received: \`${size}\``, + `Expected a natural number between 1 and 65535, received: \`${size}\`` ); } @@ -53,7 +53,11 @@ class TypedBytes extends withBase(ArrayWithoutPrototypeMethods) { } toJSON() { - return this.value; + return this.toHex(); + } + + apply(fn) { + return fn(this.value); } static fromJSON(json) { @@ -63,7 +67,7 @@ class TypedBytes extends withBase(ArrayWithoutPrototypeMethods) { static from(obj) { if (obj instanceof this) { return obj; - } else if (!Array.isArray(obj) && typeof obj !== 'string') { + } else if (!Array.isArray(obj) && typeof obj !== "string") { return this.fromApi(obj); } else { return new this(obj); diff --git a/packages/credential-sdk/src/types/generic/typed-enum.js b/packages/credential-sdk/src/types/generic/typed-enum.js index f67858989..e3e3b8077 100644 --- a/packages/credential-sdk/src/types/generic/typed-enum.js +++ b/packages/credential-sdk/src/types/generic/typed-enum.js @@ -1,19 +1,19 @@ /* eslint-disable max-classes-per-file */ -import { fmtIter } from '../../utils/generic'; +import { fmtIter } from "../../utils/generic"; import { isEqualToOrPrototypeOf, withExtendedStaticProperties, -} from '../../utils/inheritance'; +} from "../../utils/inheritance"; import { maybeEq, maybeFrom, maybeNew, maybeToJSON, -} from '../../utils/interfaces'; -import withBase from './with-base'; -import Null from './typed-null'; -import withCatchNull from './with-catch-null'; -import withEq from './with-eq'; +} from "../../utils/interfaces"; +import withBase from "./with-base"; +import Null from "./typed-null"; +import withCatchNull from "./with-catch-null"; +import withEq from "./with-eq"; /** * @template V @@ -176,18 +176,14 @@ class TypedEnum extends withBase(class EnumBase {}) { return this[this.type]; } - /** - * Convert the instance to a JSON representation. - * @returns {Object} The JSON representation of the instance. - */ - toJSON() { + apply(fn) { if (this.constructor.isNullish) { - return this.constructor.JsonType; + return fn(this.constructor.JsonType); } else { const { type, value } = this; return { - [type]: maybeToJSON(value), + [type]: fn(value), }; } } @@ -196,17 +192,17 @@ class TypedEnum extends withBase(class EnumBase {}) { static fromJSON(json) { if (json == null) { throw new Error( - `Received \`null\` while object was expected by \`${this.name}\``, + `Received \`null\` while object was expected by \`${this.name}\`` ); } - if (typeof json === 'string' && this.isNullish) { + if (typeof json === "string" && this.isNullish) { if (this.Class != null) { if (this.JsonType === json || this.Type === json) { return maybeNew(this, []); } throw new Error( - `Unexpected json in \`${this}\`: \`${json}\`, expected \`${this.JsonType}\``, + `Unexpected json in \`${this}\`: \`${json}\`, expected \`${this.JsonType}\`` ); } else { for (const Variant of this.Variants) { @@ -217,8 +213,8 @@ class TypedEnum extends withBase(class EnumBase {}) { throw new Error( `Unexpected json in \`${this}\`: \`${json}\`, expected one of ${fmtIter( - new Set([...this.Variants].flatMap((v) => [v.JsonType, v.Type])), - )}`, + new Set([...this.Variants].flatMap((v) => [v.JsonType, v.Type])) + )}` ); } } @@ -227,8 +223,8 @@ class TypedEnum extends withBase(class EnumBase {}) { if (keys.length !== 1) { throw new Error( `Expected object with 1 key, received \`${json}\` with keys: ${fmtIter( - keys, - )} by ${this.name}`, + keys + )} by ${this.name}` ); } const [key] = keys; @@ -239,7 +235,7 @@ class TypedEnum extends withBase(class EnumBase {}) { } throw new Error( - `Unexpected key \`${key}\`, expected \`${this.JsonType}\` by \`${this.name}\``, + `Unexpected key \`${key}\`, expected \`${this.JsonType}\` by \`${this.name}\`` ); } else { for (const Variant of this.Variants) { @@ -250,8 +246,8 @@ class TypedEnum extends withBase(class EnumBase {}) { throw new Error( `Invalid key \`${key}\`, expected one of ${fmtIter( - new Set([...this.Variants].flatMap((v) => [v.JsonType, v.Type])), - )} by \`${this.name}\``, + new Set([...this.Variants].flatMap((v) => [v.JsonType, v.Type])) + )} by \`${this.name}\`` ); } } @@ -262,7 +258,7 @@ class TypedEnum extends withBase(class EnumBase {}) { return maybeNew(this, [obj[this.asIdentifier]]); } else { throw new Error( - `Incompatible value provided: \`${obj}\` to \`${this}\``, + `Incompatible value provided: \`${obj}\` to \`${this}\`` ); } } else { @@ -275,19 +271,23 @@ class TypedEnum extends withBase(class EnumBase {}) { throw new Error( `Invalid object received: \`${maybeToJSON( - obj, + obj )}\`, expected to build an instance of ${fmtIter( - this.Variants.map((v) => v.Type), - )} by \`${this.name}\``, + this.Variants.map((v) => v.Type) + )} by \`${this.name}\`` ); } static variant(obj) { - return this.Variants.find((variant) => isEqualToOrPrototypeOf(variant.Class, obj?.constructor ?? Null)); + return this.Variants.find((variant) => + isEqualToOrPrototypeOf(variant.Class, obj?.constructor ?? Null) + ); } static directVariant(obj) { - return this.Variants.find((variant) => isEqualToOrPrototypeOf(variant, obj?.constructor ?? Null)); + return this.Variants.find((variant) => + isEqualToOrPrototypeOf(variant, obj?.constructor ?? Null) + ); } static get isNullish() { @@ -299,7 +299,7 @@ class TypedEnum extends withBase(class EnumBase {}) { static from(obj) { if (obj instanceof this) { return obj; - } else if (typeof obj === 'string' && this.isNullish) { + } else if (typeof obj === "string" && this.isNullish) { return this.fromJSON(obj); } else if (Object.getPrototypeOf(obj) === Object.getPrototypeOf({})) { return this.fromJSON(obj); @@ -332,5 +332,5 @@ class TypedEnum extends withBase(class EnumBase {}) { } export default withEq( - withCatchNull(withExtendedStaticProperties(['Variants'], TypedEnum)), + withCatchNull(withExtendedStaticProperties(["Variants"], TypedEnum)) ); diff --git a/packages/credential-sdk/src/types/generic/typed-map.js b/packages/credential-sdk/src/types/generic/typed-map.js index d11ec4110..7939622c1 100644 --- a/packages/credential-sdk/src/types/generic/typed-map.js +++ b/packages/credential-sdk/src/types/generic/typed-map.js @@ -65,9 +65,11 @@ class TypedMap extends withBase(Map) { } toJSON() { - return [...this.entries()] - .map(([key, value]) => [maybeToJSON(key), maybeToJSON(value)]) - .sort(([k1], [k2]) => String(k1).localeCompare(String(k2))); + return this.apply(maybeToJSON).sort(([k1], [k2]) => String(k1).localeCompare(String(k2))); + } + + apply(fn) { + return [...this.entries()].map(([key, value]) => [fn(key), fn(value)]); } static fromJSON(entries) { diff --git a/packages/credential-sdk/src/types/generic/typed-number.js b/packages/credential-sdk/src/types/generic/typed-number.js index d9a89cb26..97474aaed 100644 --- a/packages/credential-sdk/src/types/generic/typed-number.js +++ b/packages/credential-sdk/src/types/generic/typed-number.js @@ -33,6 +33,10 @@ class TypedNumber extends withBase(class NumberBase {}) { return this.value; } + apply(fn) { + return fn(this.value); + } + static from(value) { if (value instanceof this) { return value; diff --git a/packages/credential-sdk/src/types/generic/typed-set.js b/packages/credential-sdk/src/types/generic/typed-set.js index 8e6141425..b8f24aee7 100644 --- a/packages/credential-sdk/src/types/generic/typed-set.js +++ b/packages/credential-sdk/src/types/generic/typed-set.js @@ -50,7 +50,11 @@ class TypedSet extends withBase(Set) { } toJSON() { - return [...this.values()].map(maybeToJSON).sort(); + return this.apply(maybeToJSON).sort(); + } + + apply(fn) { + return [...this.values()].map(fn); } clear() { diff --git a/packages/credential-sdk/src/types/generic/typed-struct.js b/packages/credential-sdk/src/types/generic/typed-struct.js index 01c3dc41a..8a20c8290 100644 --- a/packages/credential-sdk/src/types/generic/typed-struct.js +++ b/packages/credential-sdk/src/types/generic/typed-struct.js @@ -2,7 +2,7 @@ import { validateProperties, withExtendedStaticProperties, } from '../../utils/inheritance'; -import { maybeToJSON, maybeEq, maybeFrom } from '../../utils/interfaces'; +import { maybeEq, maybeFrom } from '../../utils/interfaces'; import withBase from './with-base'; import withCatchNull from './with-catch-null'; import withEq from './with-eq'; @@ -40,9 +40,9 @@ class TypedStruct extends withBase(class StructBase {}) { Object.seal(this); } - toJSON() { + apply(fn) { return Object.fromEntries( - Object.entries(this).map(([key, value]) => [key, maybeToJSON(value)]), + Object.entries(this).map(([key, value]) => [key, fn(value)]), ); } diff --git a/packages/credential-sdk/src/types/generic/typed-tuple.js b/packages/credential-sdk/src/types/generic/typed-tuple.js index 099f9a0f4..8331fd774 100644 --- a/packages/credential-sdk/src/types/generic/typed-tuple.js +++ b/packages/credential-sdk/src/types/generic/typed-tuple.js @@ -1,5 +1,5 @@ import { withExtendedStaticProperties } from '../../utils/inheritance'; -import { maybeEq, maybeFrom, maybeToJSON } from '../../utils/interfaces'; +import { maybeEq, maybeFrom } from '../../utils/interfaces'; import { ArrayWithoutPrototypeMethods } from '../../utils/generic'; import withBase from './with-base'; import withCatchNull from './with-catch-null'; @@ -53,8 +53,8 @@ class TypedTuple extends withBase(ArrayWithoutPrototypeMethods) { Object.seal(this); } - toJSON() { - return [...Array.prototype.values.call(this)].map(maybeToJSON); + apply(fn) { + return [...this].map(fn); } static from(value) { diff --git a/packages/credential-sdk/src/types/generic/with-base.js b/packages/credential-sdk/src/types/generic/with-base.js index 1b53c165e..66e2b5660 100644 --- a/packages/credential-sdk/src/types/generic/with-base.js +++ b/packages/credential-sdk/src/types/generic/with-base.js @@ -3,7 +3,7 @@ import { withExtendedStaticProperties, withExtendedPrototypeProperties, } from '../../utils/inheritance'; -import { applyToValue, maybeEq } from '../../utils/interfaces'; +import { maybeEq, maybeToJSON } from '../../utils/interfaces'; import withCatchNull from './with-catch-null'; import withEq from './with-eq'; @@ -57,6 +57,16 @@ export default function withBase(klass) { * @returns {object} The JSON representation of the instance. */ toJSON() { + return this.apply(maybeToJSON); + } + + /** + * Recursively applies supplied function to the underlying values. + * @template T + * @param {function(this): T} _fn + * @returns {T} + */ + apply(_fn) { throw new Error('Unimplemented'); } @@ -84,24 +94,6 @@ export default function withBase(klass) { return JSON.stringify(this.toJSON()); } - /** - * Applies supplied function to the underlying value if `check` returns `true`. - * Otherwise, attempts to do the same on the inner value. - * - * @template T - * @param {function(this): T} fn - * @returns {T} - */ - applyToValue(check, fn) { - if (check(this)) { - return fn(this); - } - const { value } = this; - const hasValue = typeof value !== 'undefined'; - - return applyToValue(check, fn, value ?? this, hasValue); - } - /** * Performs an equality check against other value. * @@ -117,7 +109,7 @@ export default function withBase(klass) { return withExtendedStaticProperties( ['fromJSON', 'fromApi'], withExtendedPrototypeProperties( - ['toJSON'], + ['apply'], withEq(withCatchNull(classes[name])), ), ); diff --git a/packages/credential-sdk/src/types/generic/with-base58.js b/packages/credential-sdk/src/types/generic/with-base58.js index 54c52fb4f..072300cc9 100644 --- a/packages/credential-sdk/src/types/generic/with-base58.js +++ b/packages/credential-sdk/src/types/generic/with-base58.js @@ -1,8 +1,13 @@ -import withFrom from './with-from'; +import withFrom from "./with-from"; import { - decodeFromBase58, encodeAsBase58, isEqualToOrPrototypeOf, u8aToString, stringToU8a, maybeToJSONString, -} from '../../utils'; -import TypedEnum from './typed-enum'; + decodeFromBase58, + encodeAsBase58, + isEqualToOrPrototypeOf, + u8aToString, + stringToU8a, + maybeToJSONString, +} from "../../utils"; +import TypedEnum from "./typed-enum"; export default function withBase58(klass) { const name = `withBase58(${klass.name})`; @@ -19,6 +24,10 @@ export default function withBase58(klass) { return String(this); } + get value() { + return this.toBase58(); + } + static fromBase58(str) { return this.from(decodeFromBase58(str)); } @@ -35,7 +44,9 @@ export default function withBase58(klass) { [name]: class extends klass { static Class = klass.Class; - static Variants = !klass.Class ? klass.Variants?.map(withBase58) : klass.Variants; + static Variants = !klass.Class + ? klass.Variants?.map(withBase58) + : klass.Variants; toString() { return this.toBase58(); @@ -58,5 +69,7 @@ export default function withBase58(klass) { res = obj[name]; } - return withFrom(res, function from(value, fromFn) { return (typeof value === 'string' ? this.fromBase58(value) : fromFn(value)); }); + return withFrom(res, function from(value, fromFn) { + return typeof value === "string" ? this.fromBase58(value) : fromFn(value); + }); } diff --git a/packages/credential-sdk/src/types/generic/with-base58btc.js b/packages/credential-sdk/src/types/generic/with-base58btc.js index 432823c19..61de245ed 100644 --- a/packages/credential-sdk/src/types/generic/with-base58btc.js +++ b/packages/credential-sdk/src/types/generic/with-base58btc.js @@ -1,6 +1,6 @@ -import withFrom from './with-from'; -import { decodeFromBase58btc, encodeAsBase58btc } from '../../utils/base-x'; -import { withExtendedStaticProperties } from '../../utils/inheritance'; +import withFrom from "./with-from"; +import { decodeFromBase58btc, encodeAsBase58btc } from "../../utils/base-x"; +import { withExtendedStaticProperties } from "../../utils/inheritance"; export default function withBase58btc(klass) { const name = `withBase58btc(${klass.name})`; @@ -17,6 +17,10 @@ export default function withBase58btc(klass) { return String(this); } + get value() { + return this.toBase58btc(); + } + static fromBase58btc(str) { return this.from(decodeFromBase58btc(str)); } @@ -31,5 +35,10 @@ export default function withBase58btc(klass) { }, }; - return withExtendedStaticProperties(['Prefix'], withFrom(obj[name], (value, from) => (typeof value === 'string' ? this.fromBase58btc(value) : from(value)))); + return withExtendedStaticProperties( + ["Prefix"], + withFrom(obj[name], (value, from) => + typeof value === "string" ? this.fromBase58btc(value) : from(value) + ) + ); } diff --git a/packages/credential-sdk/src/types/generic/with-base64.js b/packages/credential-sdk/src/types/generic/with-base64.js index c0f499364..ac04378aa 100644 --- a/packages/credential-sdk/src/types/generic/with-base64.js +++ b/packages/credential-sdk/src/types/generic/with-base64.js @@ -1,8 +1,13 @@ -import withFrom from './with-from'; +import withFrom from "./with-from"; import { - decodeFromBase64, encodeAsBase64, isEqualToOrPrototypeOf, u8aToString, stringToU8a, maybeToJSONString, -} from '../../utils'; -import TypedEnum from './typed-enum'; + decodeFromBase64, + encodeAsBase64, + isEqualToOrPrototypeOf, + u8aToString, + stringToU8a, + maybeToJSONString, +} from "../../utils"; +import TypedEnum from "./typed-enum"; export default function withBase64(klass) { const name = `withBase64(${klass.name})`; @@ -19,6 +24,10 @@ export default function withBase64(klass) { return String(this); } + get value() { + return this.toBase64(); + } + static fromBase64(str) { return this.from(decodeFromBase64(str)); } @@ -35,7 +44,9 @@ export default function withBase64(klass) { [name]: class extends klass { static Class = klass.Class; - static Variants = !klass.Class ? klass.Variants?.map(withBase64) : klass.Variants; + static Variants = !klass.Class + ? klass.Variants?.map(withBase64) + : klass.Variants; toString() { return this.toBase64(); @@ -58,5 +69,7 @@ export default function withBase64(klass) { res = obj[name]; } - return withFrom(res, function from(value, fromFn) { return (typeof value === 'string' ? this.fromBase64(value) : fromFn(value)); }); + return withFrom(res, function from(value, fromFn) { + return typeof value === "string" ? this.fromBase64(value) : fromFn(value); + }); } diff --git a/packages/credential-sdk/src/types/generic/with-qualifier.js b/packages/credential-sdk/src/types/generic/with-qualifier.js index 0d2bdf050..ef063c296 100644 --- a/packages/credential-sdk/src/types/generic/with-qualifier.js +++ b/packages/credential-sdk/src/types/generic/with-qualifier.js @@ -1,12 +1,12 @@ -import TypedBytes from './typed-bytes'; +import TypedBytes from "./typed-bytes"; import { withExtendedStaticProperties, withExtendedPrototypeProperties, -} from '../../utils/inheritance'; -import { maybeFrom } from '../../utils/interfaces'; -import withFrom from './with-from'; -import { fmtIter } from '../../utils'; -import TypedString from './typed-string'; +} from "../../utils/inheritance"; +import { maybeFrom } from "../../utils/interfaces"; +import withFrom from "./with-from"; +import { fmtIter } from "../../utils"; +import TypedString from "./typed-string"; /** * Extends supplied class. @@ -28,7 +28,8 @@ export default function withQualifier(klass, wrapper = false) { static get Qualifiers() { return [].concat( - this.Qualifier ?? this.Class?.Qualifiers ?? + this.Qualifier ?? + this.Class?.Qualifiers ?? this.Variants.flatMap((variant) => [].concat( variant.Qualifier ?? variant !== this @@ -98,6 +99,10 @@ export default function withQualifier(klass, wrapper = false) { toString() { return this.value.toString(); } + + toCheqdPayload() { + return String(this); + } }, }; @@ -110,8 +115,10 @@ export default function withQualifier(klass, wrapper = false) { } } else if ( value?.constructor?.Qualifier != null && - !this.Qualifiers.find((qualifier) => - value.constructor.Qualifier.startsWith(qualifier) || qualifier.startsWith(value.constructor.Qualifier) + !this.Qualifiers.find( + (qualifier) => + value.constructor.Qualifier.startsWith(qualifier) || + qualifier.startsWith(value.constructor.Qualifier) ) ) { throw new Error( @@ -181,6 +188,10 @@ export default function withQualifier(klass, wrapper = false) { toString() { return this.toQualifiedEncodedString(); } + + toCheqdPayload() { + return String(this); + } }, }; @@ -201,7 +212,8 @@ export default function withQualifier(klass, wrapper = false) { } } else if ( value?.constructor?.Qualifier != null && - !value.constructor.Qualifier.startsWith(this.Qualifier) && !this.Qualifier.startsWith(value.constructor.Qualifier) + !value.constructor.Qualifier.startsWith(this.Qualifier) && + !this.Qualifier.startsWith(value.constructor.Qualifier) ) { throw new Error( `Value has a different qualifier: \`${value.constructor.Qualifier}\` while expected \`${this.Qualifier}\` by \`${this.name}\`` diff --git a/packages/credential-sdk/src/utils/interfaces.js b/packages/credential-sdk/src/utils/interfaces.js index fd7e86bc4..0dca70239 100644 --- a/packages/credential-sdk/src/utils/interfaces.js +++ b/packages/credential-sdk/src/utils/interfaces.js @@ -4,9 +4,10 @@ * @param {T} value * @returns {object} */ -export const maybeToJSON = (value) => (typeof value?.toJSON === 'function' - ? value.toJSON() - : JSON.parse(JSON.stringify(value))); +export const maybeToJSON = (value) => + typeof value?.toJSON === "function" + ? value.toJSON() + : JSON.parse(JSON.stringify(value)); /** * Stringifies the provided value converted to JSON. @@ -16,15 +17,30 @@ export const maybeToJSON = (value) => (typeof value?.toJSON === 'function' */ export const maybeToJSONString = (value) => JSON.stringify(maybeToJSON(value)); +/** + * Attempts to convert provided value to the Cheqd Payload or JSON. + * @param {*} value + * @returns {object} + */ +export const maybeToCheqdPayloadOrJSON = (obj) => + typeof obj?.toCheqdPayload === "function" + ? obj.toCheqdPayload() + : typeof obj?.apply === "function" + ? obj.apply(maybeToCheqdPayloadOrJSON) + : typeof value !== "object" && typeof value !== "function" + ? obj + : maybeToJSON(obj); + /** * Returns bytes of the value converted to a stringified JSON. * @template T * @param {T} value * @returns {string} */ -export const maybeToJSONStringBytes = (value) => (typeof value?.maybeToJSONStringBytes === 'function' - ? value.toJSONStringBytes() - : Uint8Array.from(Buffer.from(maybeToJSONString(value)))); +export const maybeToJSONStringBytes = (value) => + typeof value?.maybeToJSONStringBytes === "function" + ? value.toJSONStringBytes() + : Uint8Array.from(Buffer.from(maybeToJSONString(value))); /** * Attempts to compare two values using `value.eq(other)`, returns `boolean`. @@ -33,7 +49,8 @@ export const maybeToJSONStringBytes = (value) => (typeof value?.maybeToJSONStrin * @param {T} other * @returns {boolean} */ -export const maybeEq = (value, other) => (typeof value?.eq === 'function' ? value.eq(other) : value === other); +export const maybeEq = (value, other) => + typeof value?.eq === "function" ? value.eq(other) : value === other; /** * Attempts to call `value.toHuman()` or `value.toJSON`, returns `value` if methods don't exist. @@ -41,7 +58,8 @@ export const maybeEq = (value, other) => (typeof value?.eq === 'function' ? valu * @param {T} value * @returns {object} */ -export const maybeToHuman = (obj) => (obj && typeof obj.toHuman === 'function' ? obj.toHuman() : maybeToJSON(obj)); +export const maybeToHuman = (obj) => + obj && typeof obj.toHuman === "function" ? obj.toHuman() : maybeToJSON(obj); /** * Attempts to call `value.toNumber()`, returns `+value` if method doesn't exist. @@ -49,13 +67,14 @@ export const maybeToHuman = (obj) => (obj && typeof obj.toHuman === 'function' ? * @param {T} value * @returns {number} */ -export const maybeToNumber = (value) => (typeof value?.toNumber === 'function' ? value.toNumber() : +value); +export const maybeToNumber = (value) => + typeof value?.toNumber === "function" ? value.toNumber() : +value; /** * Marks function that it can't be used as a constructor. */ export const NotAConstructor = Symbol.for( - '@docknetwork/credential-sdk/NotAConstructor', + "@docknetwork/credential-sdk/NotAConstructor" ); /** @@ -63,17 +82,58 @@ export const NotAConstructor = Symbol.for( * @param Class * @param args */ -export const maybeNew = (Class, args) => (!Class[NotAConstructor] ? new Class(...args) : Class.apply(Class, args)); +export const maybeNew = (Class, args) => + !Class[NotAConstructor] ? new Class(...args) : Class.apply(Class, args); /** * Attempts to create new instance of the supplied class using `Class.from(obj)`, instantiates class if `from` doesn't exist. * @param Class * @param args */ -export const maybeFrom = (klass, obj) => (typeof klass.from === 'function' ? klass.from(obj) : maybeNew(klass, [obj])); +export const maybeFrom = (klass, obj) => + typeof klass.from === "function" ? klass.from(obj) : maybeNew(klass, [obj]); + +/** + * Error thrown when the provided function was executed more than once or wasn't executed at all. + */ +export class MustBeExecutedOnce extends Error { + constructor(fn) { + super(`Function must be executed exactly once: \`${fn}\``); + } + + static ensure(fn, call) { + let executed = false; + const willExecute = () => { + if (executed) { + throw new this(fn); + } + + executed = true; + }; + const wasExecuted = () => { + if (!executed) { + throw new this(fn); + } + }; + + const name = `mustBeExecutedOnce(${fn.name})`; + const obj = { + [name](...args) { + willExecute(); + + return fn.apply(this, args); + }, + }; + + const res = call(obj[name]); + wasExecuted(); + + return res; + } +} /** - * Applies function to the inner value of the provided object. + * Applies function to the first value of the provided object that passes the check. * @template T * @template I * @template O @@ -82,14 +142,21 @@ export const maybeFrom = (klass, obj) => (typeof klass.from === 'function' ? kla * @param {T} value * @returns {O} */ -export const applyToValue = (check, fn, value, rec = true) => { +export const applyToValue = (check, fn, value) => { if (check(value)) { return fn(value); - } else if (rec && typeof value?.applyToValue === 'function') { - return value.applyToValue(check, fn); + } else if (typeof value?.apply === "function") { + let res; + MustBeExecutedOnce.ensure( + (obj) => { + res = applyToValue(check, fn, obj); + }, + (wrapped) => value.apply(wrapped) + ); + return res; } throw new Error( - `\`fn\` can't be applied because value \`${value}\` didn't pass the check \`${check}\``, + `\`fn\` can't be applied because value \`${value}\` didn't pass the check \`${check}\`` ); }; diff --git a/packages/dock-blockchain-api/CHANGELOG.md b/packages/dock-blockchain-api/CHANGELOG.md index 0c98f2569..310a5b706 100644 --- a/packages/dock-blockchain-api/CHANGELOG.md +++ b/packages/dock-blockchain-api/CHANGELOG.md @@ -1,5 +1,12 @@ # @docknetwork/dock-blockchain-api +## 0.8.7 + +### Patch Changes + +- Updated dependencies + - @docknetwork/credential-sdk@0.21.0 + ## 0.8.6 ### Patch Changes diff --git a/packages/dock-blockchain-api/package.json b/packages/dock-blockchain-api/package.json index 56edbeb90..621eb9660 100644 --- a/packages/dock-blockchain-api/package.json +++ b/packages/dock-blockchain-api/package.json @@ -1,6 +1,6 @@ { "name": "@docknetwork/dock-blockchain-api", - "version": "0.8.6", + "version": "0.8.7", "license": "MIT", "main": "./dist/esm/index.js", "type": "module", @@ -89,7 +89,7 @@ "@polkadot/api": "10.12.4" }, "dependencies": { - "@docknetwork/credential-sdk": "0.20.0", + "@docknetwork/credential-sdk": "0.21.0", "@docknetwork/node-types": "^0.17.0", "@juanelas/base64": "^1.0.5", "@polkadot/api": "10.12.4", diff --git a/packages/dock-blockchain-modules/CHANGELOG.md b/packages/dock-blockchain-modules/CHANGELOG.md index 7e5f7160a..64e844dd9 100644 --- a/packages/dock-blockchain-modules/CHANGELOG.md +++ b/packages/dock-blockchain-modules/CHANGELOG.md @@ -1,5 +1,12 @@ # @docknetwork/dock-blockchain-modules +## 0.11.2 + +### Patch Changes + +- Updated dependencies + - @docknetwork/credential-sdk@0.21.0 + ## 0.11.1 ### Patch Changes diff --git a/packages/dock-blockchain-modules/package.json b/packages/dock-blockchain-modules/package.json index 1fc09eacb..25ac6f60c 100644 --- a/packages/dock-blockchain-modules/package.json +++ b/packages/dock-blockchain-modules/package.json @@ -1,6 +1,6 @@ { "name": "@docknetwork/dock-blockchain-modules", - "version": "0.11.1", + "version": "0.11.2", "license": "MIT", "type": "module", "main": "./dist/esm/index.js", @@ -33,7 +33,7 @@ "node": ">=18.0.0" }, "dependencies": { - "@docknetwork/credential-sdk": "0.20.0" + "@docknetwork/credential-sdk": "0.21.0" }, "devDependencies": { "@babel/cli": "^7.24.1", @@ -42,7 +42,7 @@ "@babel/plugin-syntax-import-attributes": "^7.25.6", "@babel/plugin-transform-modules-commonjs": "^7.24.1", "@babel/preset-env": "^7.24.3", - "@docknetwork/dock-blockchain-api": "0.8.6", + "@docknetwork/dock-blockchain-api": "0.8.7", "@rollup/plugin-alias": "^4.0.2", "@rollup/plugin-babel": "^6.0.4", "@rollup/plugin-commonjs": "^24.0.0", From 96f5acc4529604cad8b6d49d47ef5d13874f45d6 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 18 Dec 2024 15:59:38 +0400 Subject: [PATCH 2/5] Lints --- packages/cheqd-blockchain-api/src/index.js | 41 +++++---- .../src/modules/tests/did-module.js | 84 +++++++++---------- .../tests/offchain-signatures-module.js | 80 +++++++++--------- .../src/types/accumulator/accumulator-id.js | 38 ++++----- .../src/types/did/document/ident-ref.js | 6 +- ...method-ref-or-cheqd-verification-method.js | 8 +- .../did/document/verification-method-ref.js | 6 +- .../types/did/document/verification-method.js | 67 +++++++-------- .../types/did/offchain/service-endpoint.js | 13 +-- .../did/onchain/typed-did/dock-did-value.js | 16 ++-- .../src/types/did/onchain/typed-did/index.js | 38 ++++----- .../src/types/generic/typed-bytes-array.js | 2 +- .../src/types/generic/typed-bytes.js | 16 ++-- .../src/types/generic/typed-enum.js | 54 ++++++------ .../src/types/generic/with-base58.js | 8 +- .../src/types/generic/with-base58btc.js | 12 ++- .../src/types/generic/with-base64.js | 8 +- .../src/types/generic/with-qualifier.js | 12 +-- .../credential-sdk/src/utils/interfaces.js | 50 +++++------ 19 files changed, 268 insertions(+), 291 deletions(-) diff --git a/packages/cheqd-blockchain-api/src/index.js b/packages/cheqd-blockchain-api/src/index.js index 211e434f8..07b509d6f 100644 --- a/packages/cheqd-blockchain-api/src/index.js +++ b/packages/cheqd-blockchain-api/src/index.js @@ -1,25 +1,25 @@ -import { AbstractApiProvider } from "@docknetwork/credential-sdk/modules/abstract/common"; +import { AbstractApiProvider } from '@docknetwork/credential-sdk/modules/abstract/common'; import { maybeToJSONString, fmtIter, extendNull, -} from "@docknetwork/credential-sdk/utils"; +} from '@docknetwork/credential-sdk/utils'; import { DIDModule, ResourceModule, createCheqdSDK, CheqdNetwork, -} from "@cheqd/sdk"; +} from '@cheqd/sdk'; import { MsgCreateDidDocPayload, MsgUpdateDidDocPayload, MsgDeactivateDidDocPayload, protobufPackage as didProtobufPackage, -} from "@cheqd/ts-proto/cheqd/did/v2/index.js"; +} from '@cheqd/ts-proto/cheqd/did/v2/index.js'; import { MsgCreateResourcePayload, protobufPackage as resourceProtobufPackage, -} from "@cheqd/ts-proto/cheqd/resource/v2/index.js"; +} from '@cheqd/ts-proto/cheqd/resource/v2/index.js'; import { DidRef, NamespaceDid, @@ -29,9 +29,9 @@ import { CheqdCreateResource, CheqdDIDDocument, CheqdDeactivateDidDocument, -} from "@docknetwork/credential-sdk/types"; -import { TypedEnum } from "@docknetwork/credential-sdk/types/generic"; -import { maybeToCheqdPayloadOrJSON } from "../../credential-sdk/src/utils"; +} from '@docknetwork/credential-sdk/types'; +import { TypedEnum } from '@docknetwork/credential-sdk/types/generic'; +import { maybeToCheqdPayloadOrJSON } from '../../credential-sdk/src/utils'; export class CheqdAPI extends AbstractApiProvider { /** @@ -86,11 +86,11 @@ export class CheqdAPI extends AbstractApiProvider { if (network !== CheqdNetwork.Mainnet && network !== CheqdNetwork.Testnet) { throw new Error( `Invalid network provided: \`${network}\`, expected one of \`${fmtIter( - Object.values(CheqdNetwork) - )}\`` + Object.values(CheqdNetwork), + )}\``, ); } else if (wallet == null) { - throw new Error("`wallet` must be provided"); + throw new Error('`wallet` must be provided'); } this.ensureNotInitialized(); @@ -137,7 +137,7 @@ export class CheqdAPI extends AbstractApiProvider { const { [method]: Payloads } = this.constructor.Payloads; if (Payloads == null) { throw new Error( - `Can't find payload constructor for the provided method \`${method}\`` + `Can't find payload constructor for the provided method \`${method}\``, ); } const [TypedPayload, Payload] = Payloads; @@ -150,7 +150,7 @@ export class CheqdAPI extends AbstractApiProvider { return Payload.encode(sdkPayload).finish(); } catch (err) { throw new Error( - `Failed to encode payload \`${maybeToJSONString(sdkPayload)}\`: ${err}` + `Failed to encode payload \`${maybeToJSONString(sdkPayload)}\`: ${err}`, ); } } @@ -176,16 +176,15 @@ export class CheqdAPI extends AbstractApiProvider { throw new Error(`No payload wrapper found for \`${typeUrl}\``); } - const sender = - from ?? (await this.sdk.options.wallet.getAccounts())[0].address; + const sender = from ?? (await this.sdk.options.wallet.getAccounts())[0].address; const payment = { amount: [amount], - gas: "3600000", // TODO: dynamically calculate needed amount + gas: '3600000', // TODO: dynamically calculate needed amount payer: sender, }; const txJSON = maybeToCheqdPayloadOrJSON( - PayloadWrapper.from(JSON.parse(JSON.stringify(tx.toJSON()))) + PayloadWrapper.from(JSON.parse(JSON.stringify(tx.toJSON()))), ); txJSON.typeUrl = `/${prefix}.${typeUrl}`; @@ -193,16 +192,14 @@ export class CheqdAPI extends AbstractApiProvider { sender, [txJSON], payment, - memo ?? "" + memo ?? '', ); if (res.code) { console.error(res); throw new Error( - JSON.stringify(res, (_, value) => - typeof value === "bigint" ? `${value.toString()}n` : value - ) + JSON.stringify(res, (_, value) => (typeof value === 'bigint' ? `${value.toString()}n` : value)), ); } @@ -210,7 +207,7 @@ export class CheqdAPI extends AbstractApiProvider { } methods() { - return ["cheqd"]; + return ['cheqd']; } supportsIdentifier(id) { diff --git a/packages/credential-sdk/src/modules/tests/did-module.js b/packages/credential-sdk/src/modules/tests/did-module.js index 141145ae4..923116f45 100644 --- a/packages/credential-sdk/src/modules/tests/did-module.js +++ b/packages/credential-sdk/src/modules/tests/did-module.js @@ -1,5 +1,5 @@ -import { DidKeypair, Ed25519Keypair } from "../../keypairs"; -import { DIDResolver } from "../../resolver"; +import { DidKeypair, Ed25519Keypair } from '../../keypairs'; +import { DIDResolver } from '../../resolver'; import { DIDDocument, BBSPublicKeyValue, @@ -8,21 +8,21 @@ import { PSPublicKeyValue, VerificationMethodRef, ServiceEndpoint, -} from "../../types"; -import { TypedBytes } from "../../types/generic"; -import { NoDIDError } from "../abstract/did/errors"; -import { testIf } from "./common"; +} from '../../types'; +import { TypedBytes } from '../../types/generic'; +import { NoDIDError } from '../abstract/did/errors'; +import { testIf } from './common'; // eslint-disable-next-line jest/no-export export default function generateDIDModuleTests( { did: module }, { DID }, - filter = () => true + filter = () => true, ) { const test = testIf(filter); describe(`Using ${module.constructor.name}`, () => { - test("Creates basic `DIDDocument` with keys", async () => { + test('Creates basic `DIDDocument` with keys', async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -33,11 +33,11 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); }); - test("Creates `DIDDocument` containing BBS/BBSPlus/PS keys", async () => { + test('Creates `DIDDocument` containing BBS/BBSPlus/PS keys', async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -57,11 +57,11 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); }); - test("Updates `DIDDocument` containing BBS/BBSPlus/PS keys", async () => { + test('Updates `DIDDocument` containing BBS/BBSPlus/PS keys', async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -69,7 +69,7 @@ export default function generateDIDModuleTests( const bbsKey = new DidKey(new BBSPublicKeyValue(TypedBytes.random(100))); const bbsPlusKey = new DidKey( - new BBSPlusPublicKeyValue(TypedBytes.random(100)) + new BBSPlusPublicKeyValue(TypedBytes.random(100)), ); const psKey = new DidKey(new PSPublicKeyValue(TypedBytes.random(1000))); @@ -78,7 +78,7 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); document.addKey([did, document.nextKeyIndex()], bbsKey); @@ -88,7 +88,7 @@ export default function generateDIDModuleTests( await module.updateDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); expect(document.didKeys().toJSON()).toEqual([ @@ -102,17 +102,17 @@ export default function generateDIDModuleTests( ]); }); - test("Creates `DIDDocument` containing services", async () => { + test('Creates `DIDDocument` containing services', async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); const didKeypair = new DidKeypair([did, 1], keyPair); - const service1 = new ServiceEndpoint("LinkedDomains", [ - "ServiceEndpoint#1", + const service1 = new ServiceEndpoint('LinkedDomains', [ + 'ServiceEndpoint#1', ]); - const service2 = new ServiceEndpoint("LinkedDomains", [ - "ServiceEndpoint#2", + const service2 = new ServiceEndpoint('LinkedDomains', [ + 'ServiceEndpoint#2', ]); const document = DIDDocument.create(did, [didKeypair.didKey()], [], { @@ -123,21 +123,21 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); }); - test("Updates `DIDDocument` containing services", async () => { + test('Updates `DIDDocument` containing services', async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); const didKeypair = new DidKeypair([did, 1], keyPair); - const service1 = new ServiceEndpoint("LinkedDomains", [ - "ServiceEndpoint#1", + const service1 = new ServiceEndpoint('LinkedDomains', [ + 'ServiceEndpoint#1', ]); - const service2 = new ServiceEndpoint("LinkedDomains", [ - "ServiceEndpoint#2", + const service2 = new ServiceEndpoint('LinkedDomains', [ + 'ServiceEndpoint#2', ]); const document = DIDDocument.create(did, [didKeypair.didKey()]); @@ -145,24 +145,24 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); - document.addServiceEndpoint([did, "service1"], service1); - document.addServiceEndpoint([did, "service2"], service2); + document.addServiceEndpoint([did, 'service1'], service1); + document.addServiceEndpoint([did, 'service2'], service2); await module.updateDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); - document.removeServiceEndpoint([did, "service2"]); + document.removeServiceEndpoint([did, 'service2']); await module.updateDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); expect(document.service.length).toEqual(1); @@ -186,27 +186,25 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair2); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); document.removeKey([did, 2]); await module.updateDocument(document, didKeypair1); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); document.addKey([did, 3], didKeypair3.didKey()); - await expect(() => - module.updateDocument(document, didKeypair2) - ).rejects.toThrow(); + await expect(() => module.updateDocument(document, didKeypair2)).rejects.toThrow(); await module.updateDocument(document, didKeypair1); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); }); - test("Removes (deactivates) `DIDDocument`", async () => { + test('Removes (deactivates) `DIDDocument`', async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -216,12 +214,12 @@ export default function generateDIDModuleTests( await module.createDocument(document, didKeypair); expect((await module.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); await module.removeDocument(did, didKeypair); await expect(() => module.getDocument(did)).rejects.toThrow( - new NoDIDError(did) + new NoDIDError(did), ); }); @@ -229,11 +227,11 @@ export default function generateDIDModuleTests( const did = DID.random(); await expect(() => module.getDocument(did)).rejects.toThrow( - new NoDIDError(did) + new NoDIDError(did), ); }); - test("`DIDResolver`", async () => { + test('`DIDResolver`', async () => { const resolver = new DIDResolver(module); const did = DID.random(); diff --git a/packages/credential-sdk/src/modules/tests/offchain-signatures-module.js b/packages/credential-sdk/src/modules/tests/offchain-signatures-module.js index fac7e0aba..25acbca8f 100644 --- a/packages/credential-sdk/src/modules/tests/offchain-signatures-module.js +++ b/packages/credential-sdk/src/modules/tests/offchain-signatures-module.js @@ -1,4 +1,4 @@ -import { DidKeypair, Ed25519Keypair } from "../../keypairs"; +import { DidKeypair, Ed25519Keypair } from '../../keypairs'; import { BBSParams, BBSParamsValue, @@ -14,21 +14,23 @@ import { PSParamsValue, PSPublicKey, PSPublicKeyValue, -} from "../../types"; -import { testIf } from "./common"; -import { TypedBytes } from "../../types/generic"; -import { stringToU8a } from "../../utils"; +} from '../../types'; +import { testIf } from './common'; +import { TypedBytes } from '../../types/generic'; +import { stringToU8a } from '../../utils'; // eslint-disable-next-line jest/no-export export default function generateOffchainSignatureModuleTests( - { did: didModule, offchainSignatures, bbs, bbsPlus, ps }, + { + did: didModule, offchainSignatures, bbs, bbsPlus, ps, + }, { DID, OffchainSignaturesParamsRef }, - filter = () => true + filter = () => true, ) { const test = testIf(filter); describe(`Checks ${didModule.constructor.name} and ${offchainSignatures.constructor.name} with all public keys and params`, () => { - test("Generates a `DIDDocument` with `OffchainPublicKey` and creates a `OffchainParameters` owned by this DID", async () => { + test('Generates a `DIDDocument` with `OffchainPublicKey` and creates a `OffchainParameters` owned by this DID', async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); @@ -36,51 +38,51 @@ export default function generateOffchainSignatureModuleTests( await didModule.createDocument( DIDDocument.create(did, [didKeypair.didKey()]), - didKeypair + didKeypair, ); const bbsParamsId = await offchainSignatures.nextParamsId(did); const bbsParamsRef = new OffchainSignaturesParamsRef(did, bbsParamsId); const bbsParams = new BBSParams( - new BBSParamsValue(TypedBytes.random(100), stringToU8a("bbs")) + new BBSParamsValue(TypedBytes.random(100), stringToU8a('bbs')), ); await offchainSignatures.addParams( bbsParamsId, bbsParams, did, - didKeypair + didKeypair, ); const bbsPlusParamsId = await offchainSignatures.nextParamsId(did); const bbsPlusParamsRef = new OffchainSignaturesParamsRef( did, - bbsPlusParamsId + bbsPlusParamsId, ); const bbsPlusParams = new BBSPlusParams( - new BBSPlusParamsValue(TypedBytes.random(100), stringToU8a("bbs+")) + new BBSPlusParamsValue(TypedBytes.random(100), stringToU8a('bbs+')), ); await offchainSignatures.addParams( bbsPlusParamsId, bbsPlusParams, did, - didKeypair + didKeypair, ); const psParamsId = await offchainSignatures.nextParamsId(did); const psParamsRef = new OffchainSignaturesParamsRef(did, psParamsId); const psParams = new PSParams( - new PSParamsValue(TypedBytes.random(100), stringToU8a("ps")) + new PSParamsValue(TypedBytes.random(100), stringToU8a('ps')), ); await offchainSignatures.addParams(psParamsId, psParams, did, didKeypair); const bbsKey = new BBSPublicKey( - new BBSPublicKeyValue(TypedBytes.random(100), bbsParamsRef) + new BBSPublicKeyValue(TypedBytes.random(100), bbsParamsRef), ); const bbsPlusKey = new BBSPlusPublicKey( - new BBSPlusPublicKeyValue(TypedBytes.random(100), bbsPlusParamsRef) + new BBSPlusPublicKeyValue(TypedBytes.random(100), bbsPlusParamsRef), ); const psKey = new PSPublicKey( - new PSPublicKeyValue(TypedBytes.random(1000), psParamsRef) + new PSPublicKeyValue(TypedBytes.random(1000), psParamsRef), ); const document = DIDDocument.create(did, [ @@ -93,27 +95,27 @@ export default function generateOffchainSignatureModuleTests( await didModule.updateDocument(document, didKeypair); expect((await didModule.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); expect( - (await offchainSignatures.getParams(did, bbsParamsId)).toJSON() + (await offchainSignatures.getParams(did, bbsParamsId)).toJSON(), ).toEqual(bbsParams.toJSON()); expect( - (await offchainSignatures.getParams(did, bbsPlusParamsId)).toJSON() + (await offchainSignatures.getParams(did, bbsPlusParamsId)).toJSON(), ).toEqual(bbsPlusParams.toJSON()); expect( - (await offchainSignatures.getParams(did, psParamsId)).toJSON() + (await offchainSignatures.getParams(did, psParamsId)).toJSON(), ).toEqual(psParams.toJSON()); expect( - (await offchainSignatures.getAllParamsByDid(did)).toJSON().sort() + (await offchainSignatures.getAllParamsByDid(did)).toJSON().sort(), ).toEqual( [ [bbsParamsId.toJSON(), bbsParams.toJSON()], [bbsPlusParamsId.toJSON(), bbsPlusParams.toJSON()], [psParamsId.toJSON(), psParams.toJSON()], - ].sort() + ].sort(), ); expect((await bbsKey.withParams(offchainSignatures)).toJSON()).toEqual({ @@ -121,7 +123,7 @@ export default function generateOffchainSignatureModuleTests( }); expect( - (await bbsPlusKey.withParams(offchainSignatures)).toJSON() + (await bbsPlusKey.withParams(offchainSignatures)).toJSON(), ).toEqual({ bbsPlus: { ...bbsPlusKey.toJSON().bbsPlus, @@ -137,7 +139,7 @@ export default function generateOffchainSignatureModuleTests( }); }); - test("Returns `null` in case of missing params", async () => { + test('Returns `null` in case of missing params', async () => { const did = DID.random(); const keyPair = Ed25519Keypair.random(); const didKeypair = new DidKeypair([did, 1], keyPair); @@ -149,19 +151,17 @@ export default function generateOffchainSignatureModuleTests( await didModule.createDocument(document, didKeypair); const psKey = new PSPublicKey( - new PSPublicKeyValue(TypedBytes.random(1000), psParamsRef) + new PSPublicKeyValue(TypedBytes.random(1000), psParamsRef), ); expect( await offchainSignatures.getParams( did, - await offchainSignatures.nextParamsId(did) - ) + await offchainSignatures.nextParamsId(did), + ), ).toBe(null); - await expect(() => - psKey.withParams(offchainSignatures) - ).rejects.toThrow(); + await expect(() => psKey.withParams(offchainSignatures)).rejects.toThrow(); }); }); @@ -184,7 +184,7 @@ export default function generateOffchainSignatureModuleTests( ]; describe.each(cases)( - "Checks basic workflow for each module", + 'Checks basic workflow for each module', ({ module, PublicKey, Params }) => { test(`Generates a \`DIDDocument\` with \`OffchainPublicKey\` and creates a \`OffchainParameters\` owned by this DID using ${module.constructor.name} with ${PublicKey.name} and ${Params.name}`, async () => { const did = DID.random(); @@ -194,7 +194,7 @@ export default function generateOffchainSignatureModuleTests( await didModule.createDocument( DIDDocument.create(did, [didKeypair.didKey()]), - didKeypair + didKeypair, ); const id = await offchainSignatures.nextParamsId(did); @@ -202,8 +202,8 @@ export default function generateOffchainSignatureModuleTests( const params = new Params( new Params.Class( TypedBytes.random(100), - stringToU8a(module.constructor.name) - ) + stringToU8a(module.constructor.name), + ), ); expect(await module.getParams(did, id)).toEqual(null); @@ -211,7 +211,7 @@ export default function generateOffchainSignatureModuleTests( await module.addParams(id, params, did, didKeypair); const key = new PublicKey( - new PublicKey.Class(TypedBytes.random(100), ref) + new PublicKey.Class(TypedBytes.random(100), ref), ); const document = DIDDocument.create(did, [ @@ -222,13 +222,13 @@ export default function generateOffchainSignatureModuleTests( await didModule.updateDocument(document, didKeypair); expect((await didModule.getDocument(did)).toJSON()).toEqual( - document.toJSON() + document.toJSON(), ); expect((await module.getParams(did, id)).toJSON()).toEqual( - params.toJSON() + params.toJSON(), ); }); - } + }, ); } diff --git a/packages/credential-sdk/src/types/accumulator/accumulator-id.js b/packages/credential-sdk/src/types/accumulator/accumulator-id.js index 51bbec9cc..aceba9d4c 100644 --- a/packages/credential-sdk/src/types/accumulator/accumulator-id.js +++ b/packages/credential-sdk/src/types/accumulator/accumulator-id.js @@ -1,4 +1,4 @@ -import { CheqdMainnetDid, CheqdTestnetDid, DidRef } from "../did"; +import { CheqdMainnetDid, CheqdTestnetDid, DidRef } from '../did'; import { TypedBytes, TypedEnum, @@ -6,16 +6,15 @@ import { sized, withFrom, withQualifier, -} from "../generic"; +} from '../generic'; export class AccumulatorId extends withFrom( withQualifier(TypedEnum, true), (valueWithUncheckedPrefix, from) => { - const value = - typeof valueWithUncheckedPrefix === "string" && - valueWithUncheckedPrefix.startsWith("dock:accumulator:") - ? `accumulator:dock:${valueWithUncheckedPrefix.slice(17)}` - : valueWithUncheckedPrefix; + const value = typeof valueWithUncheckedPrefix === 'string' + && valueWithUncheckedPrefix.startsWith('dock:accumulator:') + ? `accumulator:dock:${valueWithUncheckedPrefix.slice(17)}` + : valueWithUncheckedPrefix; try { // eslint-disable-next-line no-use-before-define @@ -23,18 +22,18 @@ export class AccumulatorId extends withFrom( } catch { return from(value); } - } + }, ) { - static Qualifier = "accumulator:"; + static Qualifier = 'accumulator:'; } export class CheqdAccumulatorIdValue extends withQualifier(DidRef) { - static Qualifier = "accumulator:cheqd:"; + static Qualifier = 'accumulator:cheqd:'; static Ident = TypedUUID; static fromUnqualifiedString(str) { - const lastColon = str.lastIndexOf(":"); + const lastColon = str.lastIndexOf(':'); const did = `did:cheqd:${str.slice(0, lastColon)}`; const id = str.slice(lastColon + 1); @@ -43,11 +42,11 @@ export class CheqdAccumulatorIdValue extends withQualifier(DidRef) { toEncodedString() { const { did, value } = this; - let prefix = ""; + let prefix = ''; if (did.value instanceof CheqdTestnetDid) { - prefix = "testnet"; + prefix = 'testnet'; } else if (did.value instanceof CheqdMainnetDid) { - prefix = "mainnet"; + prefix = 'mainnet'; } return `${prefix}:${did.toEncodedString()}:${value}`; @@ -62,11 +61,10 @@ export class DockAccumulatorIdIdent extends withQualifier( withFrom( sized(TypedBytes), // eslint-disable-next-line no-use-before-define - (value, from) => - value instanceof DockAccumulatorId ? value[1] : from(value) - ) + (value, from) => (value instanceof DockAccumulatorId ? value[1] : from(value)), + ), ) { - static Qualifier = "accumulator:dock:"; + static Qualifier = 'accumulator:dock:'; static Size = 32; @@ -82,7 +80,7 @@ export class DockAccumulatorIdIdent extends withQualifier( export class CheqdAccumulatorId extends AccumulatorId { static Class = CheqdAccumulatorIdValue; - static Type = "cheqd"; + static Type = 'cheqd'; static random(did) { return new this(this.Class.random(did)); @@ -92,7 +90,7 @@ export class CheqdAccumulatorId extends AccumulatorId { export class DockAccumulatorId extends AccumulatorId { static Class = DockAccumulatorIdIdent; - static Type = "dock"; + static Type = 'dock'; static random() { return new this(this.Class.random()); diff --git a/packages/credential-sdk/src/types/did/document/ident-ref.js b/packages/credential-sdk/src/types/did/document/ident-ref.js index 7189ce985..1df694d3a 100644 --- a/packages/credential-sdk/src/types/did/document/ident-ref.js +++ b/packages/credential-sdk/src/types/did/document/ident-ref.js @@ -1,8 +1,8 @@ -import { withQualifier, TypedTuple, TypedString } from "../../generic"; -import { NamespaceDid } from "../onchain/typed-did"; +import { withQualifier, TypedTuple, TypedString } from '../../generic'; +import { NamespaceDid } from '../onchain/typed-did'; export default class IdentRef extends withQualifier(TypedTuple) { - static Qualifier = ""; + static Qualifier = ''; static Ident = TypedString; diff --git a/packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js b/packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js index 3a96bb250..3b334b2fd 100644 --- a/packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js +++ b/packages/credential-sdk/src/types/did/document/verification-method-ref-or-cheqd-verification-method.js @@ -1,6 +1,6 @@ -import VerificationMethodRef from "./verification-method-ref"; -import { CheqdVerificationMethodAssertion } from "./verification-method"; -import { withFrom } from "../../generic"; +import VerificationMethodRef from './verification-method-ref'; +import { CheqdVerificationMethodAssertion } from './verification-method'; +import { withFrom } from '../../generic'; export default class VerificationMethodRefOrCheqdVerificationMethod extends withFrom( VerificationMethodRef, @@ -10,5 +10,5 @@ export default class VerificationMethodRefOrCheqdVerificationMethod extends with } catch { return from(value); } - } + }, ) {} diff --git a/packages/credential-sdk/src/types/did/document/verification-method-ref.js b/packages/credential-sdk/src/types/did/document/verification-method-ref.js index cf93bba2e..a157317bc 100644 --- a/packages/credential-sdk/src/types/did/document/verification-method-ref.js +++ b/packages/credential-sdk/src/types/did/document/verification-method-ref.js @@ -1,8 +1,8 @@ -import { withQualifier, TypedTuple, TypedNumber } from "../../generic"; -import { NamespaceDid } from "../onchain/typed-did"; +import { withQualifier, TypedTuple, TypedNumber } from '../../generic'; +import { NamespaceDid } from '../onchain/typed-did'; export default class VerificationMethodRef extends withQualifier(TypedTuple) { - static Qualifier = ""; + static Qualifier = ''; static Classes = [NamespaceDid, TypedNumber]; diff --git a/packages/credential-sdk/src/types/did/document/verification-method.js b/packages/credential-sdk/src/types/did/document/verification-method.js index c66f46d45..5576a45b9 100644 --- a/packages/credential-sdk/src/types/did/document/verification-method.js +++ b/packages/credential-sdk/src/types/did/document/verification-method.js @@ -5,7 +5,7 @@ import { TypedBytes, option, TypedString, -} from "../../generic"; +} from '../../generic'; import { BBDT16PublicKey, BBDT16PublicKeyValue, @@ -15,12 +15,12 @@ import { BBSPublicKeyValue, PSPublicKey, PSPublicKeyValue, -} from "../../offchain-signatures"; +} from '../../offchain-signatures'; import { PublicKeyEd25519, PublicKeySecp256k1, PublicKeySr25519, -} from "../../public-keys"; +} from '../../public-keys'; import { EcdsaSecp256k1VerKeyName, Ed255192020VerKeyName, @@ -30,29 +30,27 @@ import { Bls12381BBS23DockVerKeyName, Bls12381PSDockVerKeyName, Bls12381BBDT16DockVerKeyName, -} from "../../../vc/crypto"; +} from '../../../vc/crypto'; import { Ed25519Verification2018Method, Ed25519Verification2020Method, VerificationMethodType, -} from "./verification-method-type"; -import VerificationMethodRef from "./verification-method-ref"; -import { NamespaceDid } from "../onchain/typed-did"; +} from './verification-method-type'; +import VerificationMethodRef from './verification-method-ref'; +import { NamespaceDid } from '../onchain/typed-did'; import { fmtIter, valueBytes, filterObj, maybeToCheqdPayloadOrJSON, -} from "../../../utils"; +} from '../../../utils'; export class PublicKeyBase58 extends withBase58(TypedBytes) {} // eslint-disable-next-line no-use-before-define -export class VerificationMethod extends withFrom(TypedStruct, (value, from) => - value instanceof CheqdVerificationMethod - ? value.toVerificationMethod() - : from(value) -) { +export class VerificationMethod extends withFrom(TypedStruct, (value, from) => (value instanceof CheqdVerificationMethod + ? value.toVerificationMethod() + : from(value))) { static Classes = { id: VerificationMethodRef, type: VerificationMethodType, @@ -65,27 +63,27 @@ export class VerificationMethod extends withFrom(TypedStruct, (value, from) => isOffchain() { return !( - this.type instanceof Ed25519Verification2018Method || - this.type instanceof Ed25519Verification2020Method + this.type instanceof Ed25519Verification2018Method + || this.type instanceof Ed25519Verification2020Method ); } publicKey() { const bytes = ( - this.publicKeyBase58 || - this.publicKeyBase64 || - this.publicKeyJwk || - this.publicKeyHex + this.publicKeyBase58 + || this.publicKeyBase64 + || this.publicKeyJwk + || this.publicKeyHex )?.bytes; if (bytes == null) { throw new Error( `Expected either of ${fmtIter([ - "publicKeyBase58", - "publicKeyBase64", - "publicKeyJwk", - "publicKeyHex", - ])} to be specified` + 'publicKeyBase58', + 'publicKeyBase64', + 'publicKeyJwk', + 'publicKeyHex', + ])} to be specified`, ); } @@ -118,7 +116,7 @@ export class VerificationMethod extends withFrom(TypedStruct, (value, from) => ref, didKey.publicKey.constructor.VerKeyType, ref[0], - valueBytes(didKey.publicKey) + valueBytes(didKey.publicKey), ); } @@ -128,7 +126,7 @@ export class VerificationMethod extends withFrom(TypedStruct, (value, from) => this.id, this.controller, this.type, - valueBytes(this.publicKey()) + valueBytes(this.publicKey()), ); } @@ -139,10 +137,9 @@ export class VerificationMethod extends withFrom(TypedStruct, (value, from) => export class CheqdVerificationMethod extends withFrom( TypedStruct, - (value, from) => - value instanceof VerificationMethod - ? from(value.toCheqdVerificationMethod()) - : from(value) + (value, from) => (value instanceof VerificationMethod + ? from(value.toCheqdVerificationMethod()) + : from(value)), ) { static Classes = { id: VerificationMethodRef, @@ -153,8 +150,8 @@ export class CheqdVerificationMethod extends withFrom( isOffchain() { return !( - this.verificationMethodType instanceof Ed25519Verification2018Method || - this.verificationMethodType instanceof Ed25519Verification2020Method + this.verificationMethodType instanceof Ed25519Verification2018Method + || this.verificationMethodType instanceof Ed25519Verification2020Method ); } @@ -163,7 +160,7 @@ export class CheqdVerificationMethod extends withFrom( this.id, this.verificationMethodType, this.controller, - this.verificationMaterial + this.verificationMaterial, ); } } @@ -171,12 +168,12 @@ export class CheqdVerificationMethod extends withFrom( export class CheqdVerificationMethodAssertion extends CheqdVerificationMethod { toCheqdPayload() { return JSON.stringify( - JSON.stringify(this.apply(maybeToCheqdPayloadOrJSON)) + JSON.stringify(this.apply(maybeToCheqdPayloadOrJSON)), ); } static from(obj) { - return typeof obj === "string" + return typeof obj === 'string' ? super.fromJSON(JSON.parse(JSON.parse(obj))) : super.from(obj); } diff --git a/packages/credential-sdk/src/types/did/offchain/service-endpoint.js b/packages/credential-sdk/src/types/did/offchain/service-endpoint.js index 32bab6dd9..8829d5d72 100644 --- a/packages/credential-sdk/src/types/did/offchain/service-endpoint.js +++ b/packages/credential-sdk/src/types/did/offchain/service-endpoint.js @@ -1,4 +1,4 @@ -import { maybeToJSONString, maybeToNumber } from "../../../utils"; +import { maybeToJSONString, maybeToNumber } from '../../../utils'; import { TypedStruct, TypedString, @@ -7,13 +7,13 @@ import { createPlaceholder, TypedMap, Any, -} from "../../generic"; +} from '../../generic'; const LinkedDomainsPlaceholder = createPlaceholder((value) => { if ( - +maybeToNumber(value) === 0b0001 || - String(value) === "LinkedDomains" || - value == null + +maybeToNumber(value) === 0b0001 + || String(value) === 'LinkedDomains' + || value == null ) { return 0b0001; } else { @@ -35,9 +35,10 @@ export class ServiceEndpointType extends TypedEnum { } } export class LinkedDomains extends ServiceEndpointType { - static Type = "LinkedDomains"; + static Type = 'LinkedDomains'; static Class = LinkedDomainsPlaceholder; + toJSON() { return this.constructor.Type; } diff --git a/packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js b/packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js index 5dfbab114..e04d4fbc7 100644 --- a/packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js +++ b/packages/credential-sdk/src/types/did/onchain/typed-did/dock-did-value.js @@ -1,14 +1,14 @@ -import { DockDIDQualifier } from "../constants"; -import { decodeFromSS58, encodeAsSS58, isHex } from "../../../../utils"; +import { DockDIDQualifier } from '../constants'; +import { decodeFromSS58, encodeAsSS58, isHex } from '../../../../utils'; import { withQualifier, TypedBytes, sized, TypedNumber, TypedStruct, -} from "../../../generic"; -import DidOrDidMethodKeySignature from "./signature"; -import { Signature } from "../../../signatures"; +} from '../../../generic'; +import DidOrDidMethodKeySignature from './signature'; +import { Signature } from '../../../signatures'; /** * `did:dock:*` @@ -16,7 +16,7 @@ import { Signature } from "../../../signatures"; export default class DockDidValue extends sized(withQualifier(TypedBytes)) { static Qualifier = DockDIDQualifier; - static Type = "did"; + static Type = 'did'; static Size = 32; @@ -35,7 +35,7 @@ export default class DockDidValue extends sized(withQualifier(TypedBytes)) { // eslint-disable-next-line no-use-before-define return new DockDidSignature( // eslint-disable-next-line no-use-before-define - new DockDidSignatureValue(this, keyPair.keyId, keyPair.sign(bytes)) + new DockDidSignatureValue(this, keyPair.keyId, keyPair.sign(bytes)), ); } } @@ -49,7 +49,7 @@ export class DockDidSignatureValue extends TypedStruct { } export class DockDidSignature extends DidOrDidMethodKeySignature { - static Type = "didSignature"; + static Type = 'didSignature'; static Class = DockDidSignatureValue; } diff --git a/packages/credential-sdk/src/types/did/onchain/typed-did/index.js b/packages/credential-sdk/src/types/did/onchain/typed-did/index.js index 6e00d6148..401830c59 100644 --- a/packages/credential-sdk/src/types/did/onchain/typed-did/index.js +++ b/packages/credential-sdk/src/types/did/onchain/typed-did/index.js @@ -1,9 +1,9 @@ -import { DidMethodKeyPublicKey, DidMethodKeySignature } from "./did-method-key"; -import DockDidValue, { DockDidSignature } from "./dock-did-value"; -import { TypedEnum, TypedTuple, withQualifier } from "../../../generic"; -import { CheqdDid } from "./cheqd-did"; -import { withExtendedStaticProperties } from "../../../../utils"; -import DidOrDidMethodKeySignature from "./signature"; +import { DidMethodKeyPublicKey, DidMethodKeySignature } from './did-method-key'; +import DockDidValue, { DockDidSignature } from './dock-did-value'; +import { TypedEnum, TypedTuple, withQualifier } from '../../../generic'; +import { CheqdDid } from './cheqd-did'; +import { withExtendedStaticProperties } from '../../../../utils'; +import DidOrDidMethodKeySignature from './signature'; export class DockDidOrDidMethodKey extends withQualifier(TypedEnum, true) { /** @@ -48,7 +48,7 @@ export class DockDidOrDidMethodKey extends withQualifier(TypedEnum, true) { async changeState(api, method, name, payload, keyRef) { return await method( payload, - await this.signStateChange(api, name, payload, keyRef) + await this.signStateChange(api, name, payload, keyRef), ); } @@ -133,29 +133,29 @@ export class NamespaceDid extends withQualifier(TypedEnum, true) { return super.from( value instanceof DockDidOrDidMethodKey && value.isDid ? { dock: value.asDid } - : value + : value, ); } } class DockNamespaceDid extends NamespaceDid { - static Qualifier = "did:dock:"; + static Qualifier = 'did:dock:'; - static Type = "dock"; + static Type = 'dock'; static Class = DockDidValue; } class DidNamespaceKey extends NamespaceDid { - static Qualifier = "did:key:"; + static Qualifier = 'did:key:'; - static Type = "didMethodKey"; + static Type = 'didMethodKey'; static Class = DidMethodKeyPublicKey; } class CheqdNamespaceDid extends NamespaceDid { - static Qualifier = "did:cheqd:"; + static Qualifier = 'did:cheqd:'; - static Type = "cheqd"; + static Type = 'cheqd'; static Class = CheqdDid; } @@ -163,10 +163,10 @@ class CheqdNamespaceDid extends NamespaceDid { NamespaceDid.bindVariants(DockNamespaceDid, DidNamespaceKey, CheqdNamespaceDid); export class DidRef extends withExtendedStaticProperties( - ["Ident"], - withQualifier(TypedTuple) + ['Ident'], + withQualifier(TypedTuple), ) { - static Qualifier = ""; + static Qualifier = ''; static get Classes() { return [NamespaceDid, this.Ident]; @@ -209,8 +209,8 @@ export class DidRef extends withExtendedStaticProperties( DidOrDidMethodKeySignature.bindVariants( DockDidSignature, - DidMethodKeySignature + DidMethodKeySignature, ); export { DockDidValue, DidMethodKeyPublicKey }; -export * from "./cheqd-did"; +export * from './cheqd-did'; diff --git a/packages/credential-sdk/src/types/generic/typed-bytes-array.js b/packages/credential-sdk/src/types/generic/typed-bytes-array.js index fc94a0705..6dc118dc7 100644 --- a/packages/credential-sdk/src/types/generic/typed-bytes-array.js +++ b/packages/credential-sdk/src/types/generic/typed-bytes-array.js @@ -1,4 +1,4 @@ -import TypedBytes from "./typed-bytes"; +import TypedBytes from './typed-bytes'; export default class TypedBytesArray extends TypedBytes { get value() { diff --git a/packages/credential-sdk/src/types/generic/typed-bytes.js b/packages/credential-sdk/src/types/generic/typed-bytes.js index 8630d18cc..1f582232b 100644 --- a/packages/credential-sdk/src/types/generic/typed-bytes.js +++ b/packages/credential-sdk/src/types/generic/typed-bytes.js @@ -3,12 +3,12 @@ import { randomAsU8a, u8aToHex, u8aToU8a, -} from "../../utils/bytes"; -import { ensureByte } from "../../utils"; -import { ArrayWithoutPrototypeMethods } from "../../utils/generic"; -import withBase from "./with-base"; -import withCatchNull from "./with-catch-null"; -import withEq from "./with-eq"; +} from '../../utils/bytes'; +import { ensureByte } from '../../utils'; +import { ArrayWithoutPrototypeMethods } from '../../utils/generic'; +import withBase from './with-base'; +import withCatchNull from './with-catch-null'; +import withEq from './with-eq'; class TypedBytes extends withBase(ArrayWithoutPrototypeMethods) { constructor(value) { @@ -41,7 +41,7 @@ class TypedBytes extends withBase(ArrayWithoutPrototypeMethods) { // eslint-disable-next-line no-bitwise if (!Number.isInteger(size) || (size & 65535) !== size || !size) { throw new Error( - `Expected a natural number between 1 and 65535, received: \`${size}\`` + `Expected a natural number between 1 and 65535, received: \`${size}\``, ); } @@ -67,7 +67,7 @@ class TypedBytes extends withBase(ArrayWithoutPrototypeMethods) { static from(obj) { if (obj instanceof this) { return obj; - } else if (!Array.isArray(obj) && typeof obj !== "string") { + } else if (!Array.isArray(obj) && typeof obj !== 'string') { return this.fromApi(obj); } else { return new this(obj); diff --git a/packages/credential-sdk/src/types/generic/typed-enum.js b/packages/credential-sdk/src/types/generic/typed-enum.js index e3e3b8077..364461471 100644 --- a/packages/credential-sdk/src/types/generic/typed-enum.js +++ b/packages/credential-sdk/src/types/generic/typed-enum.js @@ -1,19 +1,19 @@ /* eslint-disable max-classes-per-file */ -import { fmtIter } from "../../utils/generic"; +import { fmtIter } from '../../utils/generic'; import { isEqualToOrPrototypeOf, withExtendedStaticProperties, -} from "../../utils/inheritance"; +} from '../../utils/inheritance'; import { maybeEq, maybeFrom, maybeNew, maybeToJSON, -} from "../../utils/interfaces"; -import withBase from "./with-base"; -import Null from "./typed-null"; -import withCatchNull from "./with-catch-null"; -import withEq from "./with-eq"; +} from '../../utils/interfaces'; +import withBase from './with-base'; +import Null from './typed-null'; +import withCatchNull from './with-catch-null'; +import withEq from './with-eq'; /** * @template V @@ -192,17 +192,17 @@ class TypedEnum extends withBase(class EnumBase {}) { static fromJSON(json) { if (json == null) { throw new Error( - `Received \`null\` while object was expected by \`${this.name}\`` + `Received \`null\` while object was expected by \`${this.name}\``, ); } - if (typeof json === "string" && this.isNullish) { + if (typeof json === 'string' && this.isNullish) { if (this.Class != null) { if (this.JsonType === json || this.Type === json) { return maybeNew(this, []); } throw new Error( - `Unexpected json in \`${this}\`: \`${json}\`, expected \`${this.JsonType}\`` + `Unexpected json in \`${this}\`: \`${json}\`, expected \`${this.JsonType}\``, ); } else { for (const Variant of this.Variants) { @@ -213,8 +213,8 @@ class TypedEnum extends withBase(class EnumBase {}) { throw new Error( `Unexpected json in \`${this}\`: \`${json}\`, expected one of ${fmtIter( - new Set([...this.Variants].flatMap((v) => [v.JsonType, v.Type])) - )}` + new Set([...this.Variants].flatMap((v) => [v.JsonType, v.Type])), + )}`, ); } } @@ -223,8 +223,8 @@ class TypedEnum extends withBase(class EnumBase {}) { if (keys.length !== 1) { throw new Error( `Expected object with 1 key, received \`${json}\` with keys: ${fmtIter( - keys - )} by ${this.name}` + keys, + )} by ${this.name}`, ); } const [key] = keys; @@ -235,7 +235,7 @@ class TypedEnum extends withBase(class EnumBase {}) { } throw new Error( - `Unexpected key \`${key}\`, expected \`${this.JsonType}\` by \`${this.name}\`` + `Unexpected key \`${key}\`, expected \`${this.JsonType}\` by \`${this.name}\``, ); } else { for (const Variant of this.Variants) { @@ -246,8 +246,8 @@ class TypedEnum extends withBase(class EnumBase {}) { throw new Error( `Invalid key \`${key}\`, expected one of ${fmtIter( - new Set([...this.Variants].flatMap((v) => [v.JsonType, v.Type])) - )} by \`${this.name}\`` + new Set([...this.Variants].flatMap((v) => [v.JsonType, v.Type])), + )} by \`${this.name}\``, ); } } @@ -258,7 +258,7 @@ class TypedEnum extends withBase(class EnumBase {}) { return maybeNew(this, [obj[this.asIdentifier]]); } else { throw new Error( - `Incompatible value provided: \`${obj}\` to \`${this}\`` + `Incompatible value provided: \`${obj}\` to \`${this}\``, ); } } else { @@ -271,23 +271,19 @@ class TypedEnum extends withBase(class EnumBase {}) { throw new Error( `Invalid object received: \`${maybeToJSON( - obj + obj, )}\`, expected to build an instance of ${fmtIter( - this.Variants.map((v) => v.Type) - )} by \`${this.name}\`` + this.Variants.map((v) => v.Type), + )} by \`${this.name}\``, ); } static variant(obj) { - return this.Variants.find((variant) => - isEqualToOrPrototypeOf(variant.Class, obj?.constructor ?? Null) - ); + return this.Variants.find((variant) => isEqualToOrPrototypeOf(variant.Class, obj?.constructor ?? Null)); } static directVariant(obj) { - return this.Variants.find((variant) => - isEqualToOrPrototypeOf(variant, obj?.constructor ?? Null) - ); + return this.Variants.find((variant) => isEqualToOrPrototypeOf(variant, obj?.constructor ?? Null)); } static get isNullish() { @@ -299,7 +295,7 @@ class TypedEnum extends withBase(class EnumBase {}) { static from(obj) { if (obj instanceof this) { return obj; - } else if (typeof obj === "string" && this.isNullish) { + } else if (typeof obj === 'string' && this.isNullish) { return this.fromJSON(obj); } else if (Object.getPrototypeOf(obj) === Object.getPrototypeOf({})) { return this.fromJSON(obj); @@ -332,5 +328,5 @@ class TypedEnum extends withBase(class EnumBase {}) { } export default withEq( - withCatchNull(withExtendedStaticProperties(["Variants"], TypedEnum)) + withCatchNull(withExtendedStaticProperties(['Variants'], TypedEnum)), ); diff --git a/packages/credential-sdk/src/types/generic/with-base58.js b/packages/credential-sdk/src/types/generic/with-base58.js index 072300cc9..7c44ec914 100644 --- a/packages/credential-sdk/src/types/generic/with-base58.js +++ b/packages/credential-sdk/src/types/generic/with-base58.js @@ -1,4 +1,4 @@ -import withFrom from "./with-from"; +import withFrom from './with-from'; import { decodeFromBase58, encodeAsBase58, @@ -6,8 +6,8 @@ import { u8aToString, stringToU8a, maybeToJSONString, -} from "../../utils"; -import TypedEnum from "./typed-enum"; +} from '../../utils'; +import TypedEnum from './typed-enum'; export default function withBase58(klass) { const name = `withBase58(${klass.name})`; @@ -70,6 +70,6 @@ export default function withBase58(klass) { } return withFrom(res, function from(value, fromFn) { - return typeof value === "string" ? this.fromBase58(value) : fromFn(value); + return typeof value === 'string' ? this.fromBase58(value) : fromFn(value); }); } diff --git a/packages/credential-sdk/src/types/generic/with-base58btc.js b/packages/credential-sdk/src/types/generic/with-base58btc.js index 61de245ed..f99c549df 100644 --- a/packages/credential-sdk/src/types/generic/with-base58btc.js +++ b/packages/credential-sdk/src/types/generic/with-base58btc.js @@ -1,6 +1,6 @@ -import withFrom from "./with-from"; -import { decodeFromBase58btc, encodeAsBase58btc } from "../../utils/base-x"; -import { withExtendedStaticProperties } from "../../utils/inheritance"; +import withFrom from './with-from'; +import { decodeFromBase58btc, encodeAsBase58btc } from '../../utils/base-x'; +import { withExtendedStaticProperties } from '../../utils/inheritance'; export default function withBase58btc(klass) { const name = `withBase58btc(${klass.name})`; @@ -36,9 +36,7 @@ export default function withBase58btc(klass) { }; return withExtendedStaticProperties( - ["Prefix"], - withFrom(obj[name], (value, from) => - typeof value === "string" ? this.fromBase58btc(value) : from(value) - ) + ['Prefix'], + withFrom(obj[name], (value, from) => (typeof value === 'string' ? this.fromBase58btc(value) : from(value))), ); } diff --git a/packages/credential-sdk/src/types/generic/with-base64.js b/packages/credential-sdk/src/types/generic/with-base64.js index ac04378aa..938754ca3 100644 --- a/packages/credential-sdk/src/types/generic/with-base64.js +++ b/packages/credential-sdk/src/types/generic/with-base64.js @@ -1,4 +1,4 @@ -import withFrom from "./with-from"; +import withFrom from './with-from'; import { decodeFromBase64, encodeAsBase64, @@ -6,8 +6,8 @@ import { u8aToString, stringToU8a, maybeToJSONString, -} from "../../utils"; -import TypedEnum from "./typed-enum"; +} from '../../utils'; +import TypedEnum from './typed-enum'; export default function withBase64(klass) { const name = `withBase64(${klass.name})`; @@ -70,6 +70,6 @@ export default function withBase64(klass) { } return withFrom(res, function from(value, fromFn) { - return typeof value === "string" ? this.fromBase64(value) : fromFn(value); + return typeof value === 'string' ? this.fromBase64(value) : fromFn(value); }); } diff --git a/packages/credential-sdk/src/types/generic/with-qualifier.js b/packages/credential-sdk/src/types/generic/with-qualifier.js index ef063c296..64e6301a2 100644 --- a/packages/credential-sdk/src/types/generic/with-qualifier.js +++ b/packages/credential-sdk/src/types/generic/with-qualifier.js @@ -1,12 +1,12 @@ -import TypedBytes from "./typed-bytes"; +import TypedBytes from './typed-bytes'; import { withExtendedStaticProperties, withExtendedPrototypeProperties, -} from "../../utils/inheritance"; -import { maybeFrom } from "../../utils/interfaces"; -import withFrom from "./with-from"; -import { fmtIter } from "../../utils"; -import TypedString from "./typed-string"; +} from '../../utils/inheritance'; +import { maybeFrom } from '../../utils/interfaces'; +import withFrom from './with-from'; +import { fmtIter } from '../../utils'; +import TypedString from './typed-string'; /** * Extends supplied class. diff --git a/packages/credential-sdk/src/utils/interfaces.js b/packages/credential-sdk/src/utils/interfaces.js index 0dca70239..9c2775561 100644 --- a/packages/credential-sdk/src/utils/interfaces.js +++ b/packages/credential-sdk/src/utils/interfaces.js @@ -4,10 +4,9 @@ * @param {T} value * @returns {object} */ -export const maybeToJSON = (value) => - typeof value?.toJSON === "function" - ? value.toJSON() - : JSON.parse(JSON.stringify(value)); +export const maybeToJSON = (value) => (typeof value?.toJSON === 'function' + ? value.toJSON() + : JSON.parse(JSON.stringify(value))); /** * Stringifies the provided value converted to JSON. @@ -22,14 +21,13 @@ export const maybeToJSONString = (value) => JSON.stringify(maybeToJSON(value)); * @param {*} value * @returns {object} */ -export const maybeToCheqdPayloadOrJSON = (obj) => - typeof obj?.toCheqdPayload === "function" - ? obj.toCheqdPayload() - : typeof obj?.apply === "function" +export const maybeToCheqdPayloadOrJSON = (obj) => (typeof obj?.toCheqdPayload === 'function' // eslint-disable-line no-nested-ternary + ? obj.toCheqdPayload() + : typeof obj?.apply === 'function' // eslint-disable-line no-nested-ternary ? obj.apply(maybeToCheqdPayloadOrJSON) - : typeof value !== "object" && typeof value !== "function" - ? obj - : maybeToJSON(obj); + : typeof value !== 'object' && typeof value !== 'function' + ? obj + : maybeToJSON(obj)); /** * Returns bytes of the value converted to a stringified JSON. @@ -37,10 +35,9 @@ export const maybeToCheqdPayloadOrJSON = (obj) => * @param {T} value * @returns {string} */ -export const maybeToJSONStringBytes = (value) => - typeof value?.maybeToJSONStringBytes === "function" - ? value.toJSONStringBytes() - : Uint8Array.from(Buffer.from(maybeToJSONString(value))); +export const maybeToJSONStringBytes = (value) => (typeof value?.maybeToJSONStringBytes === 'function' + ? value.toJSONStringBytes() + : Uint8Array.from(Buffer.from(maybeToJSONString(value)))); /** * Attempts to compare two values using `value.eq(other)`, returns `boolean`. @@ -49,8 +46,7 @@ export const maybeToJSONStringBytes = (value) => * @param {T} other * @returns {boolean} */ -export const maybeEq = (value, other) => - typeof value?.eq === "function" ? value.eq(other) : value === other; +export const maybeEq = (value, other) => (typeof value?.eq === 'function' ? value.eq(other) : value === other); /** * Attempts to call `value.toHuman()` or `value.toJSON`, returns `value` if methods don't exist. @@ -58,8 +54,7 @@ export const maybeEq = (value, other) => * @param {T} value * @returns {object} */ -export const maybeToHuman = (obj) => - obj && typeof obj.toHuman === "function" ? obj.toHuman() : maybeToJSON(obj); +export const maybeToHuman = (obj) => (obj && typeof obj.toHuman === 'function' ? obj.toHuman() : maybeToJSON(obj)); /** * Attempts to call `value.toNumber()`, returns `+value` if method doesn't exist. @@ -67,14 +62,13 @@ export const maybeToHuman = (obj) => * @param {T} value * @returns {number} */ -export const maybeToNumber = (value) => - typeof value?.toNumber === "function" ? value.toNumber() : +value; +export const maybeToNumber = (value) => (typeof value?.toNumber === 'function' ? value.toNumber() : +value); /** * Marks function that it can't be used as a constructor. */ export const NotAConstructor = Symbol.for( - "@docknetwork/credential-sdk/NotAConstructor" + '@docknetwork/credential-sdk/NotAConstructor', ); /** @@ -82,16 +76,14 @@ export const NotAConstructor = Symbol.for( * @param Class * @param args */ -export const maybeNew = (Class, args) => - !Class[NotAConstructor] ? new Class(...args) : Class.apply(Class, args); +export const maybeNew = (Class, args) => (!Class[NotAConstructor] ? new Class(...args) : Class.apply(Class, args)); /** * Attempts to create new instance of the supplied class using `Class.from(obj)`, instantiates class if `from` doesn't exist. * @param Class * @param args */ -export const maybeFrom = (klass, obj) => - typeof klass.from === "function" ? klass.from(obj) : maybeNew(klass, [obj]); +export const maybeFrom = (klass, obj) => (typeof klass.from === 'function' ? klass.from(obj) : maybeNew(klass, [obj])); /** * Error thrown when the provided function was executed more than once or wasn't executed at all. @@ -145,18 +137,18 @@ export class MustBeExecutedOnce extends Error { export const applyToValue = (check, fn, value) => { if (check(value)) { return fn(value); - } else if (typeof value?.apply === "function") { + } else if (typeof value?.apply === 'function') { let res; MustBeExecutedOnce.ensure( (obj) => { res = applyToValue(check, fn, obj); }, - (wrapped) => value.apply(wrapped) + (wrapped) => value.apply(wrapped), ); return res; } throw new Error( - `\`fn\` can't be applied because value \`${value}\` didn't pass the check \`${check}\`` + `\`fn\` can't be applied because value \`${value}\` didn't pass the check \`${check}\``, ); }; From b8e0de0a322de8179392b628419a9171d65f1f02 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 18 Dec 2024 16:14:33 +0400 Subject: [PATCH 3/5] Fix --- .../src/types/did/document/verification-method-ref.js | 4 ++++ .../src/types/did/document/verification-method.js | 4 ++++ packages/credential-sdk/src/types/generic/typed-string.js | 4 ++++ packages/credential-sdk/src/types/generic/typed-uuid.js | 4 ++++ 4 files changed, 16 insertions(+) diff --git a/packages/credential-sdk/src/types/did/document/verification-method-ref.js b/packages/credential-sdk/src/types/did/document/verification-method-ref.js index a157317bc..35f780818 100644 --- a/packages/credential-sdk/src/types/did/document/verification-method-ref.js +++ b/packages/credential-sdk/src/types/did/document/verification-method-ref.js @@ -35,4 +35,8 @@ export default class VerificationMethodRef extends withQualifier(TypedTuple) { toCheqdPayload() { return this.toEncodedString(); } + + toJSON() { + return this.toEncodedString(); + } } diff --git a/packages/credential-sdk/src/types/did/document/verification-method.js b/packages/credential-sdk/src/types/did/document/verification-method.js index 5576a45b9..728eb2faa 100644 --- a/packages/credential-sdk/src/types/did/document/verification-method.js +++ b/packages/credential-sdk/src/types/did/document/verification-method.js @@ -172,6 +172,10 @@ export class CheqdVerificationMethodAssertion extends CheqdVerificationMethod { ); } + toJSON() { + return this.toCheqdPayload(); + } + static from(obj) { return typeof obj === 'string' ? super.fromJSON(JSON.parse(JSON.parse(obj))) diff --git a/packages/credential-sdk/src/types/generic/typed-string.js b/packages/credential-sdk/src/types/generic/typed-string.js index 19875ce8d..a52cafcdd 100644 --- a/packages/credential-sdk/src/types/generic/typed-string.js +++ b/packages/credential-sdk/src/types/generic/typed-string.js @@ -11,6 +11,10 @@ class TypedString extends TypedBytes { return u8aToString(this.bytes); } + toJSON() { + return String(this); + } + toString() { return this.value; } diff --git a/packages/credential-sdk/src/types/generic/typed-uuid.js b/packages/credential-sdk/src/types/generic/typed-uuid.js index 19531e03f..4d190a393 100644 --- a/packages/credential-sdk/src/types/generic/typed-uuid.js +++ b/packages/credential-sdk/src/types/generic/typed-uuid.js @@ -21,6 +21,10 @@ export default class TypedUUID extends TypedBytes { return this.value; } + toJSON() { + return String(this); + } + static fromBytesAdapt(bytesOrString) { let bytes = normalizeOrConvertStringToU8a(bytesOrString); if (bytes.length < 16) { From 84c3d784e19a033169fad821b8fd937df43c93fe Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 18 Dec 2024 16:18:36 +0400 Subject: [PATCH 4/5] Bump up repo version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2fb59dd6b..ea654059d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "root", - "version": "0.21.0", + "version": "0.22.0", "private": true, "workspaces": [ "packages/*", From 0d440738cc1648e87a3f18bb425cd4e4cd0567d3 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 18 Dec 2024 17:11:40 +0400 Subject: [PATCH 5/5] Fix `IdentRef` --- packages/credential-sdk/src/types/did/document/ident-ref.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/credential-sdk/src/types/did/document/ident-ref.js b/packages/credential-sdk/src/types/did/document/ident-ref.js index 1df694d3a..446d41b60 100644 --- a/packages/credential-sdk/src/types/did/document/ident-ref.js +++ b/packages/credential-sdk/src/types/did/document/ident-ref.js @@ -43,4 +43,8 @@ export default class IdentRef extends withQualifier(TypedTuple) { toCheqdPayload() { return this.toString(); } + + toJSON() { + return this.toString(); + } }