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
.envfile: Store your Hedera account ID and private key securely in a.envfile 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
createDIDfunction from the@hiero-did-sdk/registrarpackage. -
Invoke the
createDIDfunction with aprovidersobject 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
resolveDIDfunction 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.registerSchemafunction 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/v1/SCHEMA/0.0.7121291';
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.getSchemafunction 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 theresolveDIDfunction to understand its parameters, error handling, and advanced usage. -
Manage DIDs: Learn how to use
createDID,updateDID, anddeactivateDIDto effectively manage DIDs on Hedera. -
Implement the
Signer: Practice generating key pairs, signing messages, and verifying signatures using theSignerclass. -
Utilize the
Publisher: Integrate thePublisherclass into your application for seamless transaction submission. -
Manage AnonCreds resources: Learn how to use
HederaAnoncredsRegistryto effectively manage AnonCreds resources on Hedera. -
Leverage convenient HCS integration API: Explore use cases for
HcsServiceAPI 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.