npm package: @permid/sdk
Description: Official SDK for integrating with the Permid Identity Protocol
Author: Permid Team
Latest version: 1.0.2

# @permid/sdk

Official TypeScript/JavaScript SDK for integrating with the Permid Identity Protocol.

## Installation

```bash
npm install @permid/sdk ethers fhevmjs
```

## Quick Start

### Basic Setup

```typescript
import { createPermidClient, PERMID_NETWORKS, PermidFieldType } from '@permid/sdk';
import { ethers } from 'ethers';

// Connect to provider
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();

// Create Permid client
const permid = createPermidClient({
  network: PERMID_NETWORKS.sepolia,
  signer,
  provider,
});

// Initialize FHEVM for encryption/decryption (required before setting/getting fields)
await permid.initializeFHEVM(); // Automatically uses Zama gateway for the network
```

### Create Profile

```typescript
// Create a new profile
const tx = await permid.createProfile();
await tx.wait();

// Set encrypted profile fields
await permid.setField(PermidFieldType.EMAIL, 'john@example.com');
await permid.setField(PermidFieldType.NAME, 'John Doe');
await permid.setField(PermidFieldType.DOB, new Date('1990-01-15'));
await permid.setField(PermidFieldType.EXPERIENCE, 5);

// All values are automatically encrypted using FHEVM before being sent to the contract
```

### Request Access

```typescript
// Request access to someone's profile
const ownerAddress = '0x...';
await permid.requestAccess(
  ownerAddress,
  'I need to verify your credentials for job application #123'
);
```

### Grant Access

```typescript
// Grant access to specific fields
const requesterAddress = '0x...';
await permid.grantAccess(requesterAddress, [
  PermidFieldType.NAME,
  PermidFieldType.EMAIL,
  PermidFieldType.EXPERIENCE,
]);
```

### Read Granted Data

```typescript
// Read fields you have access to
const ownerAddress = '0x...';
const name = await permid.getField(ownerAddress, PermidFieldType.NAME);
const email = await permid.getField(ownerAddress, PermidFieldType.EMAIL);

console.log(`Name: ${name}, Email: ${email}`);
```

### Revoke Access

```typescript
// Revoke access from a requester
await permid.revokeAccess(requesterAddress);
```

## React Hooks

The SDK includes React hooks for easy integration:

```typescript
import { usePermid, useProfile, useAccessControl } from '@permid/sdk/react';

function MyComponent() {
  // Initialize client
  const { client, isInitialized } = usePermid(config);

  // Manage profile
  const { profile, createProfile, setField, loading } = useProfile(client);

  // Manage access control
  const { requestAccess, grantAccess, revokeAccess } = useAccessControl(client);

  // Check if profile exists
  const { hasProfile } = useHasProfile(client, address);

  return (
    <div>
      {loading ? 'Loading...' : null}
      {profile ? <div>Profile: {profile.owner}</div> : null}
      <button onClick={() => createProfile()}>Create Profile</button>
    </div>
  );
}
```

## API Reference

### PermidClient

#### Profile Management

- `createProfile(): Promise<TransactionResult>` - Create a new profile
- `hasProfile(address: string): Promise<boolean>` - Check if profile exists
- `setField(fieldType: PermidFieldType, value: FieldValue): Promise<TransactionResult>` - Set a field
- `getField(owner: string, fieldType: PermidFieldType): Promise<FieldValue>` - Get and decrypt a field
- `getMyProfile(): Promise<PermidProfile>` - Get your own profile

#### Access Control

- `requestAccess(owner: string, justification: string): Promise<TransactionResult>` - Request access
- `grantAccess(requester: string, fields: PermidFieldType[]): Promise<TransactionResult>` - Grant access
- `revokeAccess(requester: string): Promise<TransactionResult>` - Revoke access
- `getAccessStatus(owner: string, requester: string): Promise<AccessStatus>` - Get access status
- `getMyIncomingRequests(): Promise<string[]>` - Get incoming access requests
- `getMyOutgoingRequests(): Promise<string[]>` - Get outgoing access requests

#### Events

- `on(event: PermidEventType, callback: EventCallback): void` - Subscribe to events
- `off(event: PermidEventType, callback: EventCallback): void` - Unsubscribe from events

### Field Types

```typescript
enum PermidFieldType {
  // Personal
  EMAIL = 0,
  DOB = 1,
  NAME = 2,
  ID_NUMBER = 3,
  LOCATION = 4,
  EXPERIENCE = 5,
  COUNTRY = 6,
  PHONE = 7,
  ADDRESS = 8,
  POSTAL_CODE = 9,
  CITIZENSHIP = 10,

  // Professional
  EMPLOYMENT_STATUS = 100,
  INCOME_RANGE = 101,
  EDUCATION_LEVEL = 102,
  PROFESSIONAL_LICENSE = 103,
  JOB_TITLE = 104,
  COMPANY = 105,

  // Financial
  KYC_STATUS = 200,
  ACCREDITED_INVESTOR = 201,
  CREDIT_SCORE = 202,
  TAX_ID = 203,

  // Blockchain
  WALLET_AGE = 300,
  TRANSACTION_HISTORY = 301,
  NFT_HOLDINGS = 302,
  DAO_MEMBERSHIPS = 303,
}
```

## Examples

### DeFi Integration

```typescript
// Check if user has verified KYC
const hasProfile = await permid.hasProfile(userAddress);
if (!hasProfile) {
  throw new Error('User must create Permid profile first');
}

// Request KYC fields
await permid.requestAccess(userAddress, 'DeFi protocol compliance check');

// After user grants access, verify data
const kycStatus = await permid.getField(userAddress, PermidFieldType.KYC_STATUS);
const country = await permid.getField(userAddress, PermidFieldType.COUNTRY);

if (kycStatus && !isRestrictedCountry(country)) {
  // Allow user to use protocol
  await allowUserAccess(userAddress);
}
```

### HR Verification

```typescript
// Request employment credentials
await permid.requestAccess(
  candidateAddress,
  'Background check for Software Engineer position'
);

// After approval, verify credentials
const name = await permid.getField(candidateAddress, PermidFieldType.NAME);
const experience = await permid.getField(candidateAddress, PermidFieldType.EXPERIENCE);
const education = await permid.getField(candidateAddress, PermidFieldType.EDUCATION_LEVEL);

// Verify and proceed with hiring decision
if (experience >= 3) {
  // Schedule interview
}
```

### Event Monitoring

```typescript
// Listen for new access requests
permid.on(PermidEventType.AccessRequested, (event) => {
  console.log(`New access request from ${event.requester}`);
  // Show notification to user
  showNotification({
    title: 'New Access Request',
    message: event.justification,
  });
});

// Listen for access grants
permid.on(PermidEventType.AccessGranted, (event) => {
  console.log(`Access granted to ${event.requester} for fields:`, event.fields);
});
```

## Type Safety

The SDK is fully typed with TypeScript for excellent developer experience:

```typescript
import type {
  PermidProfile,
  AccessStatus,
  AccessPolicy,
  PermidFieldType,
} from '@permid/sdk';

function handleProfile(profile: PermidProfile) {
  console.log(`Profile owner: ${profile.owner}`);
  console.log(`Created at: ${new Date(profile.createdAt)}`);
}
```

## Error Handling

```typescript
import {
  PermidError,
  ProfileNotFoundError,
  AccessDeniedError,
  EncryptionError,
} from '@permid/sdk';

try {
  await permid.getField(address, PermidFieldType.EMAIL);
} catch (error) {
  if (error instanceof ProfileNotFoundError) {
    console.log('Profile does not exist');
  } else if (error instanceof AccessDeniedError) {
    console.log('You do not have permission to access this field');
  } else if (error instanceof EncryptionError) {
    console.log('Encryption/decryption failed');
  }
}
```

## Network Support

Currently supported networks:

- Sepolia (Testnet) - `PERMID_NETWORKS.sepolia`
- Ethereum (Coming soon)
- Arbitrum (Coming soon)
- Optimism (Coming soon)
- Polygon (Coming soon)
- Base (Coming soon)

## Development

### Running Tests

The SDK includes comprehensive test coverage (68 tests, 65%+ coverage):

```bash
# Run tests once
npm test

# Watch mode
npm run test:watch

# With coverage report
npm run test:coverage
```

**Test Coverage:**
- PermidClient: 89.43% coverage
- Encoding utilities: 100% coverage
- 68 tests covering core functionality

### Building

```bash
# Build CJS, ESM, and TypeScript definitions
npm run build

# Watch mode for development
npm run dev
```

### Type Checking

```bash
npm run typecheck
```

### Linting

```bash
npm run lint
```

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.

## License

MIT

## Links

- [Documentation](https://docs.permid.io)
- [Protocol Specification](../../SPECIFICATION.md)
- [GitHub](https://github.com/permid/permid)
- [Website](https://permid.io)