From 31d9604135eb9addca75d1169a70f20b7aa9334b Mon Sep 17 00:00:00 2001 From: tipusinghaw <126460794+tipusinghaw@users.noreply.github.com> Date: Tue, 4 Jun 2024 13:42:18 +0530 Subject: [PATCH] refactor: removed previous file and updated packages (#43) --- README.md | 38 ++--- package.json | 4 +- pnpm-lock.yaml | 22 +-- src/config.ts | 10 -- src/index.ts | 3 - src/polygon-did-delete.ts | 43 ------ src/polygon-did-registrar.ts | 177 ------------------------ src/polygon-did-update.ts | 57 -------- src/registry-contract-initialization.ts | 26 ---- src/utils/did.ts | 5 - 10 files changed, 22 insertions(+), 363 deletions(-) delete mode 100644 src/config.ts delete mode 100644 src/polygon-did-delete.ts delete mode 100644 src/polygon-did-registrar.ts delete mode 100644 src/polygon-did-update.ts delete mode 100644 src/registry-contract-initialization.ts diff --git a/README.md b/README.md index c32a0d6..db1b06b 100644 --- a/README.md +++ b/README.md @@ -43,15 +43,6 @@ did:polygon:testnet:0xdce5306fb5f9ba6797546dcd2e11eb5c5201bfeb Every DID on chain has the same structure, defined as: -```js -struct PolyDID{ - address controller; - uint created; - uint updated; - string doc; - } -``` - Where, - controller : the address of the person who creates and manages the DID @@ -63,44 +54,33 @@ Where, ## Create -Creating a DID refers to generation of a DID uri, based on either a newly generated wallet or user's existing wallet. Note that the wallet should hold Matic tokens. - -Can be invoked using 2 methods - -Method 1: With user's personal privateKey and network type(mainnet/testnet) - -```js -import { createDID } from 'polygon-did-registrar' -const txHash = await createDID(network, privateKey) -``` - -Method 2: With only network type(mainnet/testnet) +Creating a createKeyPair refers to generation of a DID uri, based on a newly generated wallet. ```js -import { createDID } from 'polygon-did-registrar' -const txHash = await createDID(network) +import { createKeyPair } from 'polygon-did-registrar' +const keys = await createKeyPair(network) ``` -The function returns, address, publicKey (base58 format), privateKey, and DID uri. +The function returns address, privateKey, publicKeyBase58, did ## Register Register of DID is done by logging the transaction on the polygon-register smart contract, by invoking ```js -import { registerDID } from "polygon-did-registrar"; -const txHash = await registerDID(did, privateKey, url?, contractAddress?); +import { create } from 'polygon-did-registrar' +const txHash = await create(did, didDoc) ``` -The function returns a txhash and DID uri on successful execution. +The function returns a txnHash and DID and didDoc on successful execution. ## Update The DID controller requests for the update functionality, if the controller wishes to edit the did doc store on the ledger using : ```js -import { updateDidDoc } from "polygon-did-registrar"; -const txHash = await updateDidDoc(did, didDoc, privateKey, url?, contractAddress?); +import { update } from 'polygon-did-registrar' +const txHash = await update(did, didDoc) ``` ## Add Resource diff --git a/package.json b/package.json index 6a7d350..56f4ed8 100644 --- a/package.json +++ b/package.json @@ -20,8 +20,8 @@ "license": "MIT", "dependencies": { "@credo-ts/core": "0.5.3", - "@ayanworks/polygon-did-registry-contract": "2.0.1-alpha.8", - "@ayanworks/polygon-did-resolver": "^0.0.16-alpha.16", + "@ayanworks/polygon-did-registry-contract": "3.0.0", + "@ayanworks/polygon-did-resolver": "1.0.0", "did-resolver": "^4.1.0", "@ethersproject/basex": "^5.7.0", "@ethersproject/signing-key": "^5.7.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c6e4e23..601fc75 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,11 +9,11 @@ importers: .: dependencies: '@ayanworks/polygon-did-registry-contract': - specifier: 2.0.1-alpha.8 - version: 2.0.1-alpha.8 + specifier: 3.0.0 + version: 3.0.0 '@ayanworks/polygon-did-resolver': - specifier: ^0.0.16-alpha.16 - version: 0.0.16-alpha.16 + specifier: 1.0.0 + version: 1.0.0 '@credo-ts/core': specifier: 0.5.3 version: 0.5.3(expo@50.0.6(@babel/core@7.23.9)(@react-native/babel-preset@0.73.21(@babel/core@7.23.9)(@babel/preset-env@7.23.9(@babel/core@7.23.9))))(react-native@0.73.4(@babel/core@7.23.9)(@babel/preset-env@7.23.9(@babel/core@7.23.9))(react@18.2.0))(web-streams-polyfill@3.2.1) @@ -70,11 +70,11 @@ packages: '@astronautlabs/jsonpath@1.1.2': resolution: {integrity: sha512-FqL/muoreH7iltYC1EB5Tvox5E8NSOOPGkgns4G+qxRKl6k5dxEVljUjB5NcKESzkqwnUqWjSZkL61XGYOuV+A==} - '@ayanworks/polygon-did-registry-contract@2.0.1-alpha.8': - resolution: {integrity: sha512-5PI/poy+zWrT3iAQGc4w4hsj39lATIv2ucWeRwMq5uwu1NRQAYRWfoIez4bF/HxBMgI5dYuXWIqLtksLBmTiag==} + '@ayanworks/polygon-did-registry-contract@3.0.0': + resolution: {integrity: sha512-RnW31nkDIMG1YzuOycxGGrJFpgTcpBwS/UZR6/wMPrsJBKBEN28k2CZImwXkbgaknyTfL7xe1u3C8NxfDvhI4Q==} - '@ayanworks/polygon-did-resolver@0.0.16-alpha.16': - resolution: {integrity: sha512-+UdFk8/OAItRNx1soKt2DKhR+1RKDcMDVenoaHgcTbEUc3XVcmvqo622BLy2Kqo/VPugHzGpCmaBIOV1JIqM6g==} + '@ayanworks/polygon-did-resolver@1.0.0': + resolution: {integrity: sha512-mzYh3XNQ4HJ0GakP1QD7UOW8PjMAhdtu/TXzeOqMtHLhWktFMQcgJuqNMNxMGbJFdIe12qFJROlle6p1BjF01g==} '@babel/code-frame@7.10.4': resolution: {integrity: sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==} @@ -5293,11 +5293,11 @@ snapshots: dependencies: static-eval: 2.0.2 - '@ayanworks/polygon-did-registry-contract@2.0.1-alpha.8': {} + '@ayanworks/polygon-did-registry-contract@3.0.0': {} - '@ayanworks/polygon-did-resolver@0.0.16-alpha.16': + '@ayanworks/polygon-did-resolver@1.0.0': dependencies: - '@ayanworks/polygon-did-registry-contract': 2.0.1-alpha.8 + '@ayanworks/polygon-did-registry-contract': 3.0.0 did-resolver: 4.1.0 ethers: 5.7.2 transitivePeerDependencies: diff --git a/src/config.ts b/src/config.ts deleted file mode 100644 index 1992edf..0000000 --- a/src/config.ts +++ /dev/null @@ -1,10 +0,0 @@ -export const networkConfig = { - testnet: { - URL: 'https://rpc-mumbai.maticvigil.com/', - CONTRACT_ADDRESS: '0x8B335A167DA81CCef19C53eE629cf2F6291F2255', - }, - mainnet: { - URL: 'https://polygon-rpc.com', - CONTRACT_ADDRESS: '0x98bF771e1E93Db917A89986bcdaBa3b43643F367', - }, -} diff --git a/src/index.ts b/src/index.ts index 83a84bb..dee81c8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,3 @@ -export { deleteDidDoc } from './polygon-did-delete' -export { createDID, registerDID } from './polygon-did-registrar' -export { updateDidDoc } from './polygon-did-update' export { PolygonDID, PolygonDidInitOptions, diff --git a/src/polygon-did-delete.ts b/src/polygon-did-delete.ts deleted file mode 100644 index 5de5a09..0000000 --- a/src/polygon-did-delete.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { BaseResponse } from './base-response' -import { RegistryContractInitialization } from './registry-contract-initialization' -import { ethers } from 'ethers' -import { parseDid, validateDid } from './utils/did' - -/** - * Delete DID Document. - * @param did - * @param privateKey - * @param url - * @param contractAddress - * @returns Return transaction hash after deleting DID Document on chain. - */ -export async function deleteDidDoc( - did: string, - privateKey: string, -): Promise { - try { - const registryContractInitialization: RegistryContractInitialization = - new RegistryContractInitialization() - - const isValidDid = validateDid(did) - if (!isValidDid) { - throw new Error('invalid did provided') - } - - const parsedDid = parseDid(did) - - const registry: ethers.Contract = - await registryContractInitialization.instanceCreation( - privateKey, - parsedDid.networkUrl, - parsedDid.contractAddress, - ) - - const txnHash = await registry.deleteDIDDoc(parsedDid.didAddress) - - return BaseResponse.from(txnHash, 'Delete DID document successfully') - } catch (error) { - console.log(`Error occurred in deleteDidDoc function ${error}`) - throw error - } -} diff --git a/src/polygon-did-registrar.ts b/src/polygon-did-registrar.ts deleted file mode 100644 index 7b6abb0..0000000 --- a/src/polygon-did-registrar.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { Wallet } from '@ethersproject/wallet' -import { computeAddress } from '@ethersproject/transactions' -import { computePublicKey } from '@ethersproject/signing-key' -import { BaseResponse } from './base-response' -import { RegistryContractInitialization } from './registry-contract-initialization' -import { getDidFromAddress, parseDid, validateDid } from './utils/did' -import { Base58 } from '@ethersproject/basex' - -/** - * Create DID Document. - * @param did - * @param address - * @returns Returns the DID Document. - */ -export async function wrapDidDocument( - did: string, - publicKeyBase58: string, - serviceEndpoint?: string, -) { - return { - '@context': [ - 'https://w3id.org/did/v1', - 'https://w3id.org/security/suites/secp256k1-2019/v1', - ], - id: did, - verificationMethod: [ - { - id: `${did}#key-1`, - type: 'EcdsaSecp256k1VerificationKey2019', // external (property value) - controller: did, - publicKeyBase58: publicKeyBase58, - }, - ], - authentication: [ - did, - { - id: `${did}#key-1`, - type: 'EcdsaSecp256k1VerificationKey2019', // external (property value) - controller: did, - publicKeyBase58: publicKeyBase58, - }, - ], - assertionMethod: [ - did, - { - id: `${did}#key-1`, - type: 'EcdsaSecp256k1VerificationKey2019', // external (property value) - controller: did, - publicKeyBase58: publicKeyBase58, - }, - ], - ...(serviceEndpoint - ? { - service: [ - { - id: `${did}#linked-domain`, - type: 'LinkedDomains', - serviceEndpoint: `${serviceEndpoint}`, - }, - ], - } - : {}), - } -} - -/** - * Create public and private key and generate address. - * @param privateKey - * @returns Returns the address and public key of type base58. - */ -export async function createKeyPair(privateKey: string) { - try { - const publicKey = computePublicKey(privateKey, true) - - const bufferPublicKey = Buffer.from(publicKey) - const publicKeyBase58 = Base58.encode(bufferPublicKey) - - const address = computeAddress(privateKey) - - return { address, publicKeyBase58 } - } catch (error) { - console.log(`Error occurred in createKeyPair function ${error}`) - throw error - } -} - -/** - * Creates a DID Uri. - * @param privateKey - * @returns Returns the address, public key of type base58, private key and DID Uri. - */ -export async function createDID(network: string, privateKey?: string) { - try { - let _privateKey: string - - if (privateKey) { - _privateKey = privateKey - } else { - const wallet = Wallet.createRandom() - _privateKey = wallet.privateKey - } - - const { address, publicKeyBase58 } = await createKeyPair(_privateKey) - - if (network !== ('testnet' || 'mainnet')) { - throw new Error('Invalid network provided') - } - - const did = getDidFromAddress(address, network) - - return BaseResponse.from( - { address, publicKeyBase58, _privateKey, did }, - 'Created DID uri successfully', - ) - } catch (error) { - console.log(`Error occurred in createDID function ${error}`) - throw error - } -} - -/** - * Registers DID document on matic chain. - * @param did - * @param privateKey - * @param url - * @param contractAddress - * @returns Returns DID and transaction hash. - */ -export async function registerDID( - did: string, - privateKey: string, - serviceEndpoint?: string, -) { - try { - const registryContractInitialization = new RegistryContractInitialization() - - const isValidDid = validateDid(did) - if (!isValidDid) { - throw new Error('invalid did provided') - } - - const parsedDid = parseDid(did) - - const keyPair = await createKeyPair(privateKey) - - const registry = await registryContractInitialization.instanceCreation( - privateKey, - parsedDid.networkUrl, - parsedDid.contractAddress, - ) - - const resolveDidDoc = await registry.getDIDDoc(parsedDid.didAddress) - - if (!resolveDidDoc) { - throw new Error('The DID document already registered!') - } - - // Get DID document - const didDoc = await wrapDidDocument( - did, - keyPair.publicKeyBase58, - serviceEndpoint, - ) - - const stringDidDoc = JSON.stringify(didDoc) - - const txnHash = await registry.createDID(parsedDid.didAddress, stringDidDoc) - - return BaseResponse.from( - { did, txnHash }, - 'Registered DID document successfully.', - ) - } catch (error) { - console.log(`Error occurred in registerDID function ${error}`) - throw error - } -} diff --git a/src/polygon-did-update.ts b/src/polygon-did-update.ts deleted file mode 100644 index 10e3295..0000000 --- a/src/polygon-did-update.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { BaseResponse } from './base-response' -import { RegistryContractInitialization } from './registry-contract-initialization' -import { parseDid, validateDid } from './utils/did' - -/** - * Update DID document on matic chain. - * @param did - * @param didDocJson - * @param privateKey - * @param url - * @param contractAddress - * @returns Returns transaction hash after updating DID Document on chain. - */ -export async function updateDidDoc( - did: string, - didDoc: string, - privateKey: string, // Todo: look for better way to address private key passing mechanism -): Promise { - try { - const registryContractInitialization = new RegistryContractInitialization() - - const isValidDid = validateDid(did) - if (!isValidDid) { - throw new Error('invalid did provided') - } - - const parsedDid = parseDid(did) - - const registry = await registryContractInitialization.instanceCreation( - privateKey, - parsedDid.networkUrl, - parsedDid.contractAddress, - ) - - if (!didDoc && !JSON.parse(didDoc)) { - throw new Error('Invalid DID has been entered!') - } - - const didDocJson = JSON.parse(didDoc) - - if ( - !didDocJson['@context'] || - !didDocJson['id'] || - !didDocJson['verificationMethod'] - ) { - throw new Error('Invalid DID doc') - } - - // Calling smart contract with update DID document on matic chain - const txnHash = await registry.updateDIDDoc(parsedDid.didAddress, didDoc) - - return BaseResponse.from(txnHash, 'Update DID document successfully') - } catch (error) { - console.log(`Error occurred in updateDidDoc function ${error}`) - throw error - } -} diff --git a/src/registry-contract-initialization.ts b/src/registry-contract-initialization.ts deleted file mode 100644 index e40c54c..0000000 --- a/src/registry-contract-initialization.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Contract, JsonRpcProvider, Wallet } from 'ethers' -import DidRegistryContract from '@ayanworks/polygon-did-registry-contract' - -export class RegistryContractInitialization { - /** - * Creates an instance of the polygon DID registry smart contract. - * @param url - * @param privateKey - * @param contractAddress - * @returns Returns the instance created. - */ - async instanceCreation( - privateKey: string, - url: string, - contractAddress: string, - ) { - const provider = new JsonRpcProvider(url) - const wallet = new Wallet(privateKey, provider) - const registry = new Contract( - contractAddress, - DidRegistryContract.abi, - wallet, - ) - return registry - } -} diff --git a/src/utils/did.ts b/src/utils/did.ts index 60b5f29..5bccc3e 100644 --- a/src/utils/did.ts +++ b/src/utils/did.ts @@ -1,4 +1,3 @@ -import { networkConfig } from '../config' import { POLYGON_DID_REGEX } from './helpers' export function getNetworkFromDid(did: string) { @@ -14,13 +13,9 @@ export function parseDid(did: string) { const network = getNetworkFromDid(did) const didAddress = network === 'testnet' ? did.split(':')[3] : did.split(':')[2] - const contractAddress = networkConfig[network].CONTRACT_ADDRESS - const networkUrl = networkConfig[network].URL return { network, - contractAddress, - networkUrl, didAddress, } }