Hiero DID SDK: Getting Started

Introduction

Welcome to the Hiero DID SDK! This guide provides a quick and practical introduction to creating and managing Decentralized Identifiers (DIDs) and AnonCreds resources on the Hedera network.

The Hiero DID SDK empowers you to leverage decentralized identity concepts for your applications, providing:

  • Enhanced Security: give users greater control over their digital identities and reduce the reliance on centralized authorities.

  • Improved Privacy: decentralized identity can be used to selectively disclose information, minimizing the data shared with third parties.

  • Increased Trust: DIDs and AnonCreds resources are anchored to the Hedera ledger, providing a tamper-proof and auditable record of identity information.

This guide will walk you through the essential steps to get you started with the Hiero DID SDK. You’ll learn how to install the SDK, create and resolve your first DID and AnonCreds credential schema.

Prerequisites:

  • Node.js and npm: Ensure you have Node.js and npm (or yarn) installed on your system.

  • Hedera Account: You’ll need a Hedera account with some hbars to pay for transaction fees. You can create one on the Hedera Portal: https://portal.hedera.com/

  • (Optional) Basic understanding of DIDs: Familiarity with the concept of DIDs is helpful but not required. If you’re new to DIDs, you can learn more here: https://www.w3.org/TR/did-core/

Let’s get started!

1. Install the SDK

Use npm to install the necessary packages:

npm install @hashgraph/sdk @hiero-did-sdk/registrar @hiero-did-sdk/resolver

2. Set up your environment

  • Create a .env file: Store your Hedera account ID and private key securely in a .env file in your project directory.

# .env
HEDERA_ACCOUNT_ID=0.0.12345
HEDERA_PRIVATE_KEY=your_private_key_here
  • Import and configure the SDK:

import { Client, PrivateKey } from "@hashgraph/sdk";

require("dotenv").config();

const myAccountId = process.env.HEDERA_ACCOUNT_ID;
const myPrivateKey = PrivateKey.fromString(process.env.HEDERA_PRIVATE_KEY);

const client = Client.forTestnet(); // Use Client.forMainnet() for mainnet
client.setOperator(myAccountId, myPrivateKey);

3. Create your first DID

import { createDID } from "@hiero-did-sdk/registrar";

async function main() {
  try {
    const { did, didDocument } = await createDID({
      client,
    });

    console.log(`DID: ${did}`);
    console.log(`DID Document: ${JSON.stringify(didDocument, null, 2)}`);
  } catch (error) {
    console.error("Error creating DID:", error);
  }
}

main().finally(() => client.close());

This code will:

  • Import the createDID function from the @hiero-did-sdk/registrar package.

  • Invoke the createDID function with a providers object containing your configured Hedera client.

  • Generate a new DID with default settings.

  • Output the generated DID string (e.g., did:hedera:testnet:z6Mkhj…​) and its associated DID document, which contains important information about the DID.

4. Resolve a DID Document

import { resolveDID } from "@hiero-did-sdk/resolver";

async function main() {
  const did = "did:hedera:testnet:z6Mkhj..."; // Replace with the DID you want to resolve

  try {
    const didDocument = await resolveDID(did);
    console.log(`DID Document: ${JSON.stringify(didDocument, null, 2)}`);
  } catch (error) {
    console.error("Error resolving DID:", error);
  }
}

main().finally(() => client.close());

This code demonstrates how to:

  • Use the resolveDID function from the resolver package.

  • Fetch and display the DID document associated with a given DID string. This allows you to verify the authenticity and retrieve information linked to the DID.

5. Create AnonCreds schema

import { HederaAnoncredsRegistry } from '@hiero-did-sdk/anoncreds';
import { HederaClientConfiguration } from '@hiero-did-sdk/client';

const config: HederaClientConfiguration = {
  networks: [
    {
      network: 'testnet',
      operatorId,
      operatorKey
    }
  ]
};

const schema = {
  issuerId: 'did:example:issuer1',
  name: 'Example Schema',
  version: '1.0',
  attrNames: ['attr1', 'attr2']
};

async function main() {
  const registry = new HederaAnoncredsRegistry(config);

  try {
    const result = await registry.registerSchema({ networkName: 'testnet', schema });
    console.log('Schema register result:', result);
  } catch (error) {
    console.error('Failed to register schema:', error);
  }
}

main();

This code demonstrates how to:

  • Use the HederaAnoncredsRegistry.registerSchema function to register AnonCreds schema on Hedera ledger.

  • Display the AnonCreds schema registration result to verify the status of the operation (success/failure).

6. Resolve AnonCreds schema

import { HederaAnoncredsRegistry } from '@hiero-did-sdk/anoncreds';
import { HederaClientConfiguration } from '@hiero-did-sdk/client';

const config: HederaClientConfiguration = {
  networks: [
    {
      network: 'testnet',
      operatorId,
      operatorKey
    }
  ]
};

// Specify the existing schemaId on the testnet here
const schemaId = 'did:hedera:testnet:zFAeKMsqnNc2bwEsC8oqENBvGqjpGu9tpUi3VWaFEBXBo_0.0.5896419/anoncreds/v0/SCHEMA/0.0.6557796';

async function main() {
  const registry = new HederaAnoncredsRegistry(config);

  try {
    const result = await registry.getSchema(schemaId);
    console.log('Schema resolution result:', result);
  } catch (error) {
    console.error('Failed to resolve schema:', error);
  }
}

main();

This code demonstrates how to:

  • Use the HederaAnoncredsRegistry.getSchema function to resolve AnonCreds schema from Hedera ledger.

  • Fetch and display the AnonCreds schema object associated with a given AnonCreds identifier.

Next Steps

  • Explore resolveDID: Dive deeper into the resolveDID function to understand its parameters, error handling, and advanced usage.

  • Manage DIDs: Learn how to use createDID, updateDID, and deactivateDID to effectively manage DIDs on Hedera.

  • Implement the Signer: Practice generating key pairs, signing messages, and verifying signatures using the Signer class.

  • Utilize the Publisher: Integrate the Publisher class into your application for seamless transaction submission.

  • Manage AnonCreds resources: Learn how to use HederaAnoncredsRegistry to effectively manage AnonCreds resources on Hedera.

  • Leverage convenient HCS integration API: Explore use cases for HcsService API for advanced integration with Hedera Consensus Service (HCS).

  • Handling Exceptions: Explore best practices for handling exceptions and errors when working with the Hiero DID SDK: Handling Exceptions Guide.