npm package: @krnl-dev/sdk-react-4337
Description: React SDK for KRNL Protocol - Build dApps with decentralized workflow execution, ERC-4337 account abstraction, and seamless blockchain integration
Author: KRNL Labs
Latest version: 0.1.4

# @krnl-dev/sdk-react-4337


A React SDK for building decentralized applications with KRNL Protocol - featuring ERC-4337 account abstraction, decentralized workflow execution, and seamless blockchain integration.

## Overview

KRNL Protocol enables decentralized workflow execution across multiple blockchains. This React SDK provides developers with easy-to-use hooks and components to integrate KRNL workflow capabilities into their dApps.

## Features

- **🚀 KRNL Workflow Integration**: Submit and monitor workflows on KRNL Protocol
- **🔐 ERC-4337 Account Abstraction**: Smart account functionality with account abstraction
- **⚡ Dual-Phase Monitoring**: Status API polling + event-based transaction tracking
- **📦 Optimized Bundle**: ~24KB lightweight package
- **🛡️ Type Safety**: Full TypeScript support with comprehensive type definitions
- **⚙️ React Hooks**: Clean, composable API following React best practices

## Installation

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

## Quick Start

### 1. Configuration

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

const krnlConfig = createConfig({
  chain: sepolia,
  factoryAddress: '0x...', // ERC-4337 factory contract
  krnlNodeUrl: 'https://node.krnl.xyz',
  appSecret: 'your-app-secret-key'
});
```

### 2. Provider Setup

```typescript
import { KRNLProvider } from '@krnl-dev/sdk-react-4337';

<KRNLProvider config={krnlConfig}>
  <YourApp />
</KRNLProvider>
```

### 3. Execute Workflows

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

const { executeWorkflow, executeWorkflowFromTemplate, isReady, statusCode, error } = useKRNL();

// Method 1: Direct execution
const workflow = {
  action: "transfer_tokens",
  params: { from: "0x...", to: "0x...", amount: 1000 }
};
await executeWorkflow(workflow);

// Method 2: Template-based execution with placeholders
const template = {
  action: "{{ACTION}}",
  params: { amount: "{{AMOUNT}}", enabled: "{{ENABLED}}" }
};
const replacements = {
  "{{ACTION}}": "transfer",
  "{{AMOUNT}}": 1000,
  "{{ENABLED}}": true
};
await executeWorkflowFromTemplate(template, replacements);

// Check status
if (statusCode === WorkflowStatusCode.SUCCESS) {
  console.log('✅ Workflow completed');
} else if (error) {
  console.log('❌ Error:', error);
}
```

## KRNL Protocol Integration


## API Reference

### Main Hook

```typescript
const {
  // Workflow execution
  executeWorkflow: (dsl: WorkflowObject) => Promise<WorkflowExecutionResult>;
  executeWorkflowFromTemplate: (template: WorkflowObject, replacements: Record<string, string | number | boolean | `0x${string}`>) => Promise<WorkflowExecutionResult>;

  // State management
  resetSteps: () => void;
  isReady: boolean;
  error: string | null;
  statusCode: WorkflowStatusCode | null;

  // Progress tracking
  steps: WorkflowStep[];
  currentStep: number; // 0=idle, 1=submit, 2=execute, 3=onchain

  // Smart account
  smartAccountAddress: string | null;
} = useKRNL();
```

### Node Configuration

```typescript
// Get node configuration (node address, executor images, etc.)
const config = await getNodeConfig('https://node.krnl.xyz');
// Returns: { nodeAddress: '0x...', executorImages: [...], ... }

// Using React hook
const { getConfig } = useNodeConfig();
const config = await getConfig();
```

### Types

```typescript
// Workflow data structure
type WorkflowValue = string | number | boolean | `0x${string}` | WorkflowObject | WorkflowValue[];
interface WorkflowObject { [key: string]: WorkflowValue; }

// Status codes: PENDING(0), PROCESSING(1), SUCCESS(2), FAILED(3), etc.
enum WorkflowStatusCode { ... }

// Template utilities
processWorkflowTemplate(template: WorkflowObject, replacements: Record<string, WorkflowValue>): WorkflowObject;
validateTemplateParameters(template: WorkflowObject, replacements: Record<string, WorkflowValue>): string[];
```


## How It Works

**Execution Flow:**
1. **Submit**: Workflow sent to KRNL nodes
2. **Process**: Off-chain execution with AI/compute resources
3. **Execute**: On-chain transaction if successful
4. **Confirm**: Transaction hash and block confirmation

**Monitoring:**
- Status polling every 5 seconds (PENDING → PROCESSING → SUCCESS)
- Real-time event monitoring for on-chain confirmation
- Step-by-step progress tracking with error details

## Progress Monitoring

Track workflow execution in real-time:

```typescript
const { steps, currentStep, resetSteps } = useKRNL();

// Monitor current step (0=idle, 1=submit, 2=execute, 3=onchain)
useEffect(() => {
  if (currentStep === 1) console.log('📤 Submitting...');
  else if (currentStep === 2) console.log('⚡ Executing...');
  else if (currentStep === 3) console.log('⛓️ Confirming...');
}, [currentStep]);

// Access step details
steps.forEach(step => {
  console.log(`${step.title}: ${step.status}`); // pending, running, completed, error
});
```

## Error Handling

```typescript
const { error, statusCode, executeWorkflow } = useKRNL();

const result = await executeWorkflow(workflow);

if (error) {
  switch (statusCode) {
    case WorkflowStatusCode.FAILED:
      console.log('Workflow execution failed');
      break;
    case WorkflowStatusCode.INVALID:
      console.log('Invalid workflow parameters');
      break;
    default:
      console.log('Unknown error:', error);
  }
} else if (statusCode === WorkflowStatusCode.SUCCESS) {
  console.log('✅ Success!');
}
```


## 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 or ^19.0.0
- **TypeScript**: ^5.0.0 (optional but recommended)
- **Browser**: Modern browsers supporting ES2020


### Peer Dependencies

```json
{
  "@wagmi/core": "^2.0.0",
  "react": "^18.0.0",
  "react-dom": "^18.0.0",
  "viem": "^2.0.0",
  "wagmi": "^2.0.0"
}
```


## License

MIT License