# @gvnrdao/dh-sdk

TypeScript SDK for Diamond Hands Protocol - Bitcoin-backed lending with LIT Protocol PKPs

## Description

The official TypeScript SDK for the Diamond Hands Protocol, enabling developers to interact with Bitcoin-backed lending smart contracts using LIT Protocol's Programmable Key Pairs (PKPs) for secure asset management.

## Installation

```bash
npm install @gvnrdao/dh-sdk
```

### Browser vs server (PKP mint / `PKP_MINT_PRIVATE_KEY`)

- **Default export** (`import { DiamondHandsSDK } from "@gvnrdao/dh-sdk"` and `import { loadSDKConfig } from "@gvnrdao/dh-sdk"` via constants) resolves **browser-safe** environment helpers (`environment.browser`) — suitable for frontends, read-only flows, and user-signed transactions. Do **not** put `PKP_MINT_PRIVATE_KEY` in client bundles.
- **Server / Node scripts** (lit-ops-server, CI, PKP mint wallets) should import Node env + optional mint key from the dedicated subpath:

```typescript
import {
  loadSDKConfig,
  validateSDKEnvironment,
} from "@gvnrdao/dh-sdk/server";

validateSDKEnvironment({ requiresPrivateKey: true });
const cfg = loadSDKConfig(); // may include cfg.pkpMintPrivateKey when env is set
```

See [`docs/security/SECRETS-POLICY.md`](../docs/security/SECRETS-POLICY.md). The repo enforces that only `src/server.ts` may import Node `environment.ts` (ESLint + `npm run lint:server-boundary`).

## Usage

### Basic Setup

```typescript
import { DiamondHandsSDK } from "@gvnrdao/dh-sdk";

const sdkResult = await DiamondHandsSDK.create({
  mode: "service", // or 'standalone'
  serviceEndpoint: "http://localhost:3001",
  contractAddresses: {
    positionManager: "0x...",
    ucdToken: "0x...",
    // ... other contract addresses
  },
});
if (!sdkResult.success) {
  throw sdkResult.error;
}
const sdk = sdkResult.value;
```

### Creating a Loan

```typescript
const loanRequest = {
  collateralAmount: 25000, // UCD equivalent
  collateralRatio: 150, // 150%
  selectedTerm: 3, // 3 months
};

const result = await sdk.createLoan(loanRequest);
if (result.success) {
  console.log("Loan created:", result.transactionHash);
  console.log("Position ID:", result.positionId);
  console.log("PKP Address:", result.pkpData.ethAddress);
}
```

### UCD mint gas (`requestMintUCD`)

`mintUCD` can consume very high gas. The SDK runs **`eth_estimateGas`** on the final calldata, adds **25% headroom**, and caps the limit at **10M**. Fees use **`getFeeData()`** when available, with fallbacks. Broadcasting uses **`signer.sendTransaction`** (EIP-1559 type 2), not manual `signDigest` / raw RPC.

If **estimateGas** fails but a **static call** succeeds, on **Sepolia (chain ID 11155111)** the SDK **automatically** sends with the **fixed ceiling**; on other chains it throws unless estimation succeeds.

### Smart wallets and same-block limits (`PositionManager`)

The on-chain `PositionManager` applies a **flash-loan protection** modifier to **`createPosition`** and **`extendPosition`**: it rate-limits by **`tx.origin`** (the top-level EOA or account that sent the outer transaction), not by `msg.sender`. This is intentional (anti-abuse); it is **not** used for access control.

**Implications for integrators:**

- **Contract wallets (e.g. Safe)** can create and extend positions: the protocol sees `msg.sender` as the wallet. Ensure you do **not** put **two** guarded calls (`create` **or** `extend`) in **one** outer transaction (e.g. a Safe multicall batch), or the second can revert with `SameBlockInteraction`.
- At most **one successful** `createPosition` **or** `extendPosition` per **block** per **`tx.origin`**. Split operations across separate transactions/blocks if needed.
- Flows where **many users** share the **same** outer submitter in the **same block** (e.g. some **account-abstraction / bundler** setups) can **collide** on that limit because they share `tx.origin`. EOA-submitted Safe transactions are typically unaffected.

### Liquidating Positions (MEV-Protected)

The SDK provides MEV-protected liquidation using a commit-reveal system:

```typescript
// MEV-protected liquidation (recommended)
const liquidationResult = await sdk.liquidatePosition({
  positionId: "0x...",
  forceContractCall: false, // Use LIT action validation
});

// Legacy admin-only liquidation (faster, for testing)
const adminResult = await sdk.liquidatePositionAdmin({
  positionId: "0x...",
  forceContractCall: true, // Bypass LIT action
});
```

#### MEV Protection Features

- **Commit-Reveal System**: Prevents front-running by separating intent from execution
- **Randomized Delays**: 60-300 second delays to avoid predictable timing attacks
- **Quantum Timestamps**: LIT Protocol signed timestamps prevent replay attacks
- **Role-Based Access**: Uses LIQUIDATOR_ROLE instead of admin privileges

#### Liquidation Process

1. **Commit Phase**: Submit liquidation intent with LIT Action validation
2. **MEV Protection**: Wait randomized delay (60-300 seconds)
3. **Reveal Phase**: Execute liquidation with deadline enforcement

**Note**: The commit-reveal process takes 1-5 minutes due to MEV protection. Use `liquidatePositionAdmin()` for immediate execution during testing or emergency situations.

## Features

- ✅ **Service & Standalone Modes**: Flexible deployment options
- ✅ **Browser & Node.js Support**: Works in both environments
- ✅ **TypeScript Support**: Full type definitions included
- ✅ **PKP Integration**: Secure key management with LIT Protocol
- ✅ **Smart Contract Integration**: Direct interaction with Diamond Hands contracts
- ✅ **Bitcoin Operations**: Support for Bitcoin deposit verification
- ✅ **MEV-Protected Liquidations**: Commit-reveal system prevents front-running
- ✅ **Telegram Notifications**: Optional event notifications (Node.js only)

## API Reference

### Core Methods

- `initialize()` - Initialize the SDK
- `createLoan(request)` - Create a new loan position
- `repayLoan(positionId, amount)` - Repay an existing loan
- `liquidatePosition(request)` - Liquidate an undercollateralized position (MEV-protected)
- `liquidatePositionAdmin(request)` - Liquidate position using admin-only access (backward compatibility)

### Configuration Options

See the full API documentation for detailed configuration options and method signatures.
- API Reference (TSDoc source): [`src/index.ts`](src/index.ts)

## Telegram Notifications

The SDK supports optional Telegram notifications for loan events (minting, payments, renewals, etc.). These notifications only work in Node.js environments due to browser security restrictions.

### Enabling Telegram Notifications

Add the `telegram` configuration when initializing the SDK:

```typescript
const sdk = new DiamondHandsSDK({
  mode: "service",
  serviceEndpoint: "http://localhost:3001",
  telegram: {
    chatId: "your-chat-id",
    chatToken: "your-bot-token",
    threadId: 123 // Optional: for group threads
  },
  // ... other config
});
```

### Browser Behavior

**Important**: Telegram notifications are automatically disabled in browser environments to avoid CORS errors. The SDK detects browser environments and silently skips notification attempts without breaking your application flow.

- ✅ **Node.js**: Notifications sent via Telegram Bot API
- ✅ **Browser**: Notifications silently skipped (no errors)
- ✅ **Development**: Console logs in localhost for debugging

### Supported Events

The SDK sends notifications for:
- Loan creation
- UCD minting
- Partial payments
- Loan renewals
- Position liquidations
- Balance confirmations
- BTC withdrawals
- Operation failures

### Security Note

Never expose your Telegram bot token in frontend code. If you need notifications from browser applications, use a backend webhook endpoint instead.

## Development — TypeChain

After changing Solidity contracts that the SDK consumes:

1. `cd contracts && npm run compile` (or from `sdk/`: `npm run sync:typechain`).
2. Commit updated `contracts/typechain-types/**` with the contract changes.
3. Update [`sdk/src/contracts/typechain-contracts.ts`](src/contracts/typechain-contracts.ts) re-exports if new contracts need SDK-facing types.

Full details: [`docs/TYPECHAIN_IMPLEMENTATION.md`](docs/TYPECHAIN_IMPLEMENTATION.md) (regeneration, commit policy, npm publish behavior).

## License

MIT
