npm package: @krnl-dev/sdk-react-7702
Description: React SDK for KRNL Protocol - Build dApps with EIP-7702 account abstraction, decentralized workflow execution, and step-by-step progress tracking
Author: KRNL Labs
Latest version: 0.1.4

# @krnl-dev/sdk-react-7702

React SDK for KRNL Protocol - EIP-7702 account abstraction and decentralized workflow execution.

## Features

- EIP-7702 account abstraction with Privy integration
- Step-by-step workflow progress tracking
- Template-based workflow execution
- Full TypeScript support

## Installation

```bash
npm install @krnl-dev/sdk-react-7702
```

## Quick Start

> **Important**: This SDK requires [Privy](https://www.privy.io/) for wallet integration and must be used with `@privy-io/react-auth`.
>
> **Why Privy?** Privy is currently one of the few wallet providers that fully supports **EIP-7702 account abstraction**, which is essential for KRNL Protocol's delegated account functionality. EIP-7702 enables:
> - Temporary delegation of account authority
> - Smart account capabilities on existing EOAs
> - Gasless transactions through delegation
> - Enhanced security without deploying separate smart contracts
>
> Without EIP-7702 support, the SDK cannot enable the smart account features required for KRNL workflow execution.

### 1. Configure KRNL Protocol Connection

```typescript
import { createConfig } from '@krnl-dev/sdk-react-7702';
import { sepolia } from 'viem/chains';

const krnlConfig = createConfig({
  chain: sepolia,
  delegatedContractAddress: '0x...', // KRNL delegated account contract
  privyAppId: 'your-privy-app-id'
  // krnlNodeUrl is optional - defaults to 'https://node.krnl.xyz'
  // rpcUrl is optional - uses KRNL-optimized Privy RPC if not provided
});
```

### 2. Setup Providers

```typescript
import { PrivyProvider } from '@privy-io/react-auth';
import { KRNLProvider } from '@krnl-dev/sdk-react-7702';

function App() {
  return (
    <PrivyProvider appId="your-privy-app-id">
      <KRNLProvider config={krnlConfig}>
        <YourDApp />
      </KRNLProvider>
    </PrivyProvider>
  );
}
```

### 3. Authorize KRNL Delegated Account

```typescript
import { useKRNL } from '@krnl-dev/sdk-react-7702';

const { isAuthorized, enableSmartAccount, embeddedWallet } = useKRNL();

// Authorize account for KRNL workflow execution
const authorizeAccount = async () => {
  if (!embeddedWallet) {
    // User needs to connect wallet via Privy first
    return;
  }

  if (!isAuthorized) {
    const success = await enableSmartAccount();
    // Account is now authorized for KRNL workflows
  }
};
```

**What happens during authorization:**
1. User signs an EIP-7702 authorization message via Privy
2. The authorization delegates specific permissions to the KRNL contract
3. Your account gains smart account capabilities without deploying a new contract
4. The delegation is temporary and can be revoked at any time

### 4. Get Node Configuration

```typescript
import { useNodeConfig } from '@krnl-dev/sdk-react-7702';

const { getConfig } = useNodeConfig();

// Fetch node configuration to use in workflow templates
const nodeConfig = await getConfig();
// Returns:
// {
//   workflow: {
//     node_address: "0xF090B7794A47d9cAF080F17c68e6FeA88A85CBD9",
//     executor_images: [...]
//   }
// }
```

### 5. Execute KRNL Workflows

```typescript
import { useKRNL, useNodeConfig, WorkflowStatusCode } from '@krnl-dev/sdk-react-7702';

const {
  executeWorkflow,
  executeWorkflowFromTemplate,
  resetSteps,
  isAuthorized,
  statusCode,
  error,
  steps,
  currentStep
} = useKRNL();

const { getConfig } = useNodeConfig();

// Execute a basic workflow
const runWorkflow = async () => {
  if (!isAuthorized) return;

  resetSteps(); // Clear previous workflow state

  const workflowDSL = {
    action: "transfer_tokens",
    params: {
      from: "0x123...",
      to: "0x456...",
      amount: "1000"
    }
  };

  const result = await executeWorkflow(workflowDSL);

  // Handle result based on statusCode
  if (statusCode === WorkflowStatusCode.SUCCESS) {
    // ✅ Workflow completed successfully
  } else if (error) {
    // ❌ Handle error based on statusCode
  }
};

// Execute workflow from template with node config
const runTemplateWorkflow = async () => {
  if (!isAuthorized) return;

  // Get node configuration for dynamic values
  const nodeConfig = await getConfig();

  const template = {
    action: "execute_workflow",
    params: {
      node_address: "{{NODE_ADDRESS}}",
      executor_image: "{{EXECUTOR_IMAGE}}",
      from: "{{SENDER_ADDRESS}}",
      to: "{{RECIPIENT_ADDRESS}}",
      amount: "{{AMOUNT}}"
    }
  };

  const params = {
    "{{NODE_ADDRESS}}": nodeConfig.workflow.node_address,
    "{{EXECUTOR_IMAGE}}": nodeConfig.workflow.executor_images[0],
    "{{SENDER_ADDRESS}}": "0x123...",
    "{{RECIPIENT_ADDRESS}}": "0x456...",
    "{{AMOUNT}}": "1000"
  };

  await executeWorkflowFromTemplate(template, params);

  // Monitor progress via steps, currentStep, and statusCode
};
```

**Workflow Execution Flow:**
1. **Submit to KRNL**: Workflow DSL sent to KRNL Protocol nodes (status: PENDING)
2. **Admission Control**: KRNL validates and queues the workflow (status: PENDING)
3. **Processing**: Workflow executes off-chain with AI/compute resources (status: PROCESSING)
4. **Completion**: Workflow completes successfully or fails (status: SUCCESS/FAILED/ERROR_CODES)
5. **On-chain Settlement**: If successful, results trigger the transaction intent on-chain
6. **Confirmation**: Transaction hash and block number returned

**Step-by-Step Progress Tracking:**
The SDK provides detailed progress tracking through the `steps` array and `currentStep` field:

**Steps Array Structure:**
```typescript
interface WorkflowStep {
  id: number;           // Step ID (1, 2, 3)
  title: string;        // Human-readable step name
  status: 'pending' | 'running' | 'completed' | 'error';
  error?: string;       // Error message if status is 'error'
  result?: any;         // Step result data when completed
}
```

**Workflow Steps:**
- **Step 1**: "Submit" - Submit workflow to KRNL node
- **Step 2**: "Execute" - Workflow execution (PENDING → PROCESSING → SUCCESS)
- **Step 3**: "On-chain Status" - Monitor blockchain transaction confirmation

**Current Step Values:**
- `0`: Idle (not running)
- `1`: Currently submitting workflow
- `2`: Currently executing workflow
- `3`: Currently monitoring on-chain transaction

**Monitoring Workflow Status:**
The SDK provides real-time status updates through the `statusCode` field:
- `0 (PENDING)`: Workflow is queued for execution
- `1 (PROCESSING)`: Workflow is actively executing
- `2 (SUCCESS)`: Workflow completed successfully, awaiting on-chain settlement
- `3 (FAILED)`: Workflow execution failed
- `4 (INTENT_NOT_FOUND)`: The specified intent ID was not found
- `5 (WORKFLOW_NOT_FOUND)`: The workflow definition was not found
- `6 (INVALID)`: Invalid workflow request or parameters

## KRNL Protocol Integration


## API Reference

### `useKRNL()` Hook

```typescript
const {
  // Status
  isAuthorized: boolean;          // Ready to execute workflows
  isAuthenticated: boolean;       // Wallet connected
  embeddedWallet: PrivyEmbeddedWallet | null;

  // Workflow Execution
  executeWorkflow: (dsl: WorkflowObject) => Promise<WorkflowExecutionResult>;
  executeWorkflowFromTemplate: (template: WorkflowObject, params: Record<string, any>) => Promise<WorkflowExecutionResult>;

  // Step Management
  resetSteps: () => void;         // Reset workflow state
  initializeSteps: () => void;    // Initialize steps
  steps: WorkflowStep[];          // Progress steps
  currentStep: number;            // Current step (0=idle, 1-3=active)

  // Account Management
  enableSmartAccount: () => Promise<boolean>;

  // State
  statusCode: WorkflowStatusCode | null;
  error: string | null;
} = useKRNL();
```

### `useNodeConfig()` Hook

```typescript
const { getConfig } = useNodeConfig();

// Fetch KRNL node configuration
const config: NodeConfig = await getConfig();
// Returns: { workflow: { node_address: string, executor_images: string[] } }
```

### `getNodeConfig()` Function

```typescript
import { getNodeConfig, DEFAULT_KRNL_NODE_URL } from '@krnl-dev/sdk-react-7702';

// Fetch node config with custom URL
const config = await getNodeConfig('https://custom-node.url');

// Use default KRNL node URL (https://node.krnl.xyz)
const config = await getNodeConfig();
// or explicitly
const config = await getNodeConfig(DEFAULT_KRNL_NODE_URL);
```

### Types

```typescript
import {
  WorkflowObject,
  WorkflowValue,
  WorkflowStatusCode,
  NodeConfig,
  NodeConfigResponse,
  processWorkflowTemplate,
  validateTemplateParameters,
  ERROR_MESSAGES,
  DEFAULT_KRNL_NODE_URL
} from '@krnl-dev/sdk-react-7702';

// Template processing
type WorkflowValue = string | number | boolean | `0x${string}` | WorkflowObject | WorkflowValue[];
interface WorkflowObject {
  [key: string]: WorkflowValue;
}

// Node configuration
interface NodeConfig {
  workflow: {
    node_address: string;
    executor_images: string[];
  };
}

// Template utilities
const template: WorkflowObject = { action: "{{ACTION}}", amount: "{{AMOUNT}}" };
const params = { "{{ACTION}}": "transfer", "{{AMOUNT}}": "1000" };
const processed = processWorkflowTemplate(template, params);

// Node config usage in templates
const nodeConfig = await getNodeConfig();
const nodeParams = {
  "{{NODE_ADDRESS}}": nodeConfig.workflow.node_address,
  "{{EXECUTOR_IMAGE}}": nodeConfig.workflow.executor_images[0]
};
```

## Status Codes

```typescript
enum WorkflowStatusCode {
  PENDING = 0,           // Workflow queued
  PROCESSING = 1,        // Workflow executing
  SUCCESS = 2,           // Workflow completed successfully
  FAILED = 3,            // Workflow execution failed
  INTENT_NOT_FOUND = 4,  // Intent ID not found
  WORKFLOW_NOT_FOUND = 5,// Workflow not found
  INVALID = 6            // Invalid request
}
```


## Development

```bash
# Install dependencies
npm install

# Build SDK
npm run build

# Run tests
npm test

# Type checking
npm run type-check
```

## Compatibility

### Requirements

- **Node.js**: >=18.0.0
- **React**: ^18.0.0 (React 19 not yet supported due to Privy dependencies)
- **TypeScript**: ^5.0.0 (optional but recommended)
- **Browser**: Modern browsers supporting ES2020


### Peer Dependencies

```json
{
  "@privy-io/react-auth": "^3.0.1",
  "react": "^18.0.0",
  "react-dom": "^18.0.0",
  "viem": "^2.0.0"
}
```


## License

MIT License