# DID Generation

Did is a basic secp256k1 key generated ethereum address which is written in format

`did:pkh:{address_key}` e.g `did:pkh:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`

#### Generating Ethereum Compatible DiD

**Install Protocol SDK and Viem**

{% tabs %}
{% tab title="NPM" %}

```javascript
npm install viem @permission-io/protocol-sdk
```

{% endtab %}

{% tab title="Yarn" %}

```python
yarn add viem @permission-io/protocol-sdk
```

{% endtab %}

{% tab title="Bun" %}

```ruby
bun add viem @permission-io/protocol-sdk
```

{% endtab %}
{% endtabs %}

```
import { generatePrivateKey, privateKeyToDid, defaultPermissionDIDDocument } from "@permission-io/protocol-sdk/did";

// 1. Generate a random private key
const privateKey = generatePrivateKey();

// 2. Derive the DID (did:pkh:...)
const did = await privateKeyToDid(privateKey);
console.log(`Generated DID: ${did}`);

// 3. Create a default DID Document
const didDoc = defaultPermissionDIDDocument(privateKey);
console.log(didDoc);
```

### DID Document Structure

A DID Document (Decentralized Identifier Document) is a fundamental component of the Decentralized Identifiers architecture, serving as the digital identity profile for a DID subject

DID Document structure for permission protocol requirements is as follows

```json
{
  "@context": ["https://w3id.org/security/suites/secp256k1recovery-2020/v2", "https://www.w3.org/ns/cid/v1"],
  "id": "did:pkh:0x998b41de68d45d452e248478a98cc803c097094f",
  "verificationMethod": [
    {
      "id": "did:pkh:0x998b41de68d45d452e248478a98cc803c097094f#verify-signature",
      "type": "EcdsaSecp256k1RecoveryMethod2020",
      "controller": "did:pkh:0x998b41de68d45d452e248478a98cc803c097094f",
      "blockchainAccountId": "eip155:1:0x998b41de68d45d452e248478a98cc803c097094f"
    },
    {
      "id": "did:pkh:0x998b41de68d45d452e248478a98cc803c097094f#encryption-key",
      "type": "Multikey",
      "controller": "did:pkh:0x998b41de68d45d452e248478a98cc803c097094f",
      "publicKeyMultibase": "z6MkmM42vxfqZQsv4ehtTjFFxQ4sQKS2w6WR7emozFAn5cxu"
    }
  ],
  "authentication": ["did:pkh:0x998b41de68d45d452e248478a98cc803c097094f#verify-signature"],
  "assertionMethod": ["did:pkh:0x998b41de68d45d452e248478a98cc803c097094f#verify-signature"],
  "keyAgreement": ["did:pkh:0x998b41de68d45d452e248478a98cc803c097094f#encryption-key"]
}

```

{% hint style="info" %}
**Multikey** verification method is required for encrypted data access through IPFS

[More on this in Data Access Patterns](/permission-protocol/v1-protocol/data-access-patterns.md#ipfs-encrypted-mode)
{% endhint %}

## Permission Protocol SDK

### Quick Start

#### 1. Generate an Identity

Create a new private key and derived DID.

```typescript
import { generatePrivateKey, privateKeyToDid, defaultPermissionDIDDocument } from "@permission-io/protocol-sdk/did";

// 1. Generate a random private key
const privateKey = generatePrivateKey();

// 2. Derive the DID (did:pkh:...)
const did = await privateKeyToDid(privateKey);
console.log(`Generated DID: ${did}`);

// 3. Create a default DID Document
const didDoc = defaultPermissionDIDDocument(privateKey);
console.log(didDoc);
```

### Usage Guide

#### Prerequisites

Initialize a `viem` Client (Wallet and Public) to interact with the blockchain.

```typescript
import { createWalletClient, createPublicClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains"; // or your target chain

const account = privateKeyToAccount(YOUR_PRIVATE_KEY);

const walletClient = createWalletClient({
  account,
  chain: base,
  transport: http()
});

const publicClient = createPublicClient({
  chain: base,
  transport: http()
});
```

#### Registering a DID

**Method A: Self-Registration**

Register your own DID directly on-chain.

```typescript
import { publishDIDDocument, defaultPermissionDIDDocument } from "@permission-io/protocol-sdk/did";

// Prepare the DID Document
const didDoc = defaultPermissionDIDDocument(YOUR_PRIVATE_KEY);

// Publish to the registry
const txHash = await publishDIDDocument(didDoc, walletClient);
console.log(`DID Registered. Tx Hash: ${txHash}`);
```

**Method B: Delegated Registration (Meta-Transaction)**

Allow a third party (relayer) to pay for the gas fees while you sign the intent.

**Signer (Identity Owner):**

```typescript
import { signDIDDocumentOf, defaultPermissionDIDDocument } from "@permission-io/protocol-sdk/did";
import { base } from "viem/chains";

const didDoc = defaultPermissionDIDDocument(signerPrivateKey);
const chainId = base.id; // Target Chain ID

// Sign the document
const { didDocumentStruct, signature } = await signDIDDocumentOf(didDoc, chainId, signerWalletClient);
```

**Relayer (Gas Payer):**

```typescript
import { publishDIDDocumentOf } from "@permission-io/protocol-sdk/did";

// Relayer submits the signed payload
const txHash = await publishDIDDocumentOf(
  didDoc,            // The original JSON DID Document
  signerAddress,     // Address of the identity owner
  signature,         // The signature generated by the owner
  relayerWalletClient // Relayer's wallet client pays for gas
);
```

#### Updating a DID

**Method A: Self-Update**

Update your existing DID Document.

```typescript
import { updateDIDDocument } from "@permission-io/protocol-sdk/did";

// Modify your DID Document (e.g., add a new service or key)
const updatedDoc = { ...oldDoc, nonce: oldDoc.nonce + 1 }; 

const txHash = await updateDIDDocument(updatedDoc, account.address, walletClient);
```

**Method B: Delegated Update**

Update a DID Document via a relayer.

```typescript
import { updateDIDDocumentOf } from "@permission-io/protocol-sdk/did";

// 1. Owner signs the update
// ... (similar signing process as registration)

// 2. Relayer submits
const txHash = await updateDIDDocumentOf(
  updatedDoc,
  ownerAddress,
  signature,
  relayerWalletClient
);
```

#### Resolving a DID

Fetch and decode a DID Document from the blockchain.

```typescript
import { fetchDidDocument } from "@permission-io/protocol-sdk/did";

const did = "did:pkh:0x123...";
const document = await fetchDidDocument(did, publicClient);

if (document) {
  console.log("DID Document:", document);
} else {
  console.log("DID not found");
}
```

> **🚧 Content in Progress 🚧**\
> This documentation page is currently being created and is incomplete. Please check back later for updates.

W3C DiD Spec: <https://www.w3.org/TR/did-1.0/>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.permission.ai/permission-protocol/concepts/did-generation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
