# Usage

### **What is KRNL SDK?**

The **KRNL SDK** is a developer toolkit for interacting with the **KRNL Protocol**, enabling seamless workflow execution, delegated account management, and real-time monitoring. With the SDK, you can:

* Execute workflows using a simple DSL (domain-specific language)
* Track step-by-step workflow progress off-chain
* Monitor workflow status and on-chain settlement
* Integrate smart account functionality with **delegated authority**

The SDK provides **React hooks, utilities, and type definitions** to simplify development of KRNL-native dApps.

{% hint style="warning" %}

### **Important: Privy Wallet Requirement**

The KRNL SDK requires **Privy** for wallet integration and must be used with `@privy-io/react-auth`.

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 via delegation
* Enhanced security without deploying separate smart contracts

*Without Privy and EIP-7702 support, the SDK cannot enable the smart account features required for KRNL workflow execution.*
{% endhint %}

### **Configure KRNL Protocol Connection**

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

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

***

### **Setup Providers**

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

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

***

### **Authorize KRNL Delegated Account**

```javascript
import { useKRNL } from '@krnl/react-sdk';

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

const authorizeAccount = async () => {
  if (!embeddedWallet) return; // Connect wallet via Privy first

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

**Authorization Process:**

1. User signs an EIP-7702 authorization message via Privy
2. Delegates specific permissions to the KRNL contract
3. Account gains smart account capabilities **without deploying a new contract**
4. Delegation is temporary and revocable

***

### **Execute KRNL Workflows**

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

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

#### **Execute a Basic Workflow**

```javascript
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);

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

#### **Execute Workflow From Template**

```javascript
const runTemplateWorkflow = async () => {
  if (!isAuthorized) return;

  const template = {
    action: "transfer_tokens",
    params: {
      from: "{{SENDER_ADDRESS}}",
      to: "{{RECIPIENT_ADDRESS}}",
      amount: "{{AMOUNT}}"
    }
  };

  const params = {
    "{{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:** DSL sent to nodes → `PENDING`
2. **Admission Control:** Workflow validated & queued → `PENDING`
3. **Processing:** Execution off-chain → `PROCESSING`
4. **Completion:** Success or failure → `SUCCESS` / `FAILED` / `ERROR_CODES`
5. **On-chain Settlement:** Results trigger transaction intent on-chain
6. **Confirmation:** Transaction hash & block number returned

***

### **Step-by-Step Progress Tracking**

#### **Steps Array Structure**

```ts
interface WorkflowStep {
  id: number;             // Step ID (1, 2, 3)
  title: string;          // Step name
  status: 'pending' | 'running' | 'completed' | 'error';
  error?: string;         // If error occurs
  result?: any;           // Step result
}
```

#### **Workflow Steps**

1. **Submit:** Send workflow to KRNL node
2. **Execute:** Off-chain execution (PENDING → PROCESSING → SUCCESS)
3. **On-chain Status:** Monitor blockchain transaction confirmation

#### **Current Step Values**

* `0` = Idle
* `1` = Submitting workflow
* `2` = Executing workflow
* `3` = Monitoring on-chain transaction

***

### **Workflow Status Codes**

| Code | Meaning                                            |
| ---- | -------------------------------------------------- |
| 0    | PENDING – Workflow queued                          |
| 1    | PROCESSING – Workflow executing                    |
| 2    | SUCCESS – Workflow completed successfully          |
| 3    | FAILED – Execution failed                          |
| 4    | INTENT\_NOT\_FOUND – Intent ID missing             |
| 5    | WORKFLOW\_NOT\_FOUND – Workflow definition missing |
| 6    | INVALID – Invalid request                          |

***

### **`useKRNL()` Hook**

```ts
const {
  // Status
  isAuthorized,
  isAuthenticated,
  embeddedWallet,

  // Workflow Execution
  executeWorkflow,
  executeWorkflowFromTemplate,

  // Step Management
  resetSteps,
  initializeSteps,
  steps,
  currentStep,

  // Account Management
  enableSmartAccount,

  // State
  statusCode,
  error
} = useKRNL();
```

***

### **Template Utilities**

```ts
import {
  WorkflowObject,
  WorkflowValue,
  processWorkflowTemplate,
  validateTemplateParameters,
  WorkflowStatusCode,
  ERROR_MESSAGES
} from '@krnl/react-sdk';

type WorkflowValue = string | number | boolean | `0x${string}` | WorkflowObject | WorkflowValue[];
```

#### **Processing Templates**

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

### Development

```bash
# Install dependencies
npm install

# Build SDK
npm run build

# Run tests
npm test

# Type checking
npm run type-check
```


---

# 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.krnl.xyz/krnl-sdk/usage.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.
