# Introduction

Welcome to the KRNL docs, we are so excited to help you build your first KRNL integrated app.

### What is the KRNL Protocol?

KRNL is a plug-and-play protocol that extends enterprise systems with secure, cryptographically verifiable access to external APIs, AI systems, blockchain data, and traditional business applications. Every workflow step is executed off-chain in an isolated sandbox, cryptographically signed, timestamped, and delivered with a verifiable proof, enabling your systems to confirm authenticity before any state change, payment, or compliance action occurs.

### Why does it matter?

Enterprise systems face a critical gap: how do you prove that an off-chain event: an API call, a data transformation, or an AI-generated output, actually happened as claimed before it triggers a financial transaction, compliance action, or record update?\
\
Traditional middleware requires trust in centralized operators. Logs can be altered. APIs can fail silently. AI outputs cannot be audited retroactively. KRNL closes this gap by providing cryptographically verifiable proof of every external interaction, creating immutable audit trails that satisfy regulatory requirements and internal risk controls.\
\
When a system record triggers a payment, a document requires tamper-evident verification, or an AI model produces a decision, KRNL delivers the cryptographic evidence that proves the trigger was legitimate, the data was unaltered, and the execution occurred exactly as defined.

### What Can You Build?

As a flexible middleware layer, KRNL powers enterprise-grade use cases across compliance, security, and cross-system automation:\
\
**Secure Document Management** Upload, share, and view sensitive documents with cryptographically anchored fingerprints and identity-bound watermarking. Every viewer receives a personalized watermark tied to their identity, ensuring full accountability and leak traceability. Even if a document is screenshotted or exported, the watermark remains tied to the viewer.\
\
**CRM Workflow Automation** Connect customer relationship management systems to verifiable actions: loyalty programs triggered by deal stage changes, verifiable credential issuance on customer onboarding, or reputation scores updated from engagement data. Every trigger is cryptographically signed and auditable.\
\
**Pre-Transaction Compliance** Screen every action against regulatory, AML, and policy rules before execution. Validate sender provenance, sanctions exposure, and license constraints at the intent stage with verifiable, deterministic enforcement that auditors can independently verify.\
\
**Verifiable AI Decisioning** Run AI models off-chain for credit scoring, risk assessment, or fraud detection. KRNL signs the inference result and model version, delivering a proof that your compliance team can audit and your systems can trust before acting on the output.\
\
**Cross-System Orchestration** Bridge enterprise systems with settlement, identity verification, or asset tokenization—all through a single integration layer with end-to-end cryptographic proof.\
\
**Supply Chain & Provenance** Track goods, documents, or digital assets across multiple systems with tamper-evident verification at every handoff. Each step generates a cryptographic receipt that proves when, where, and by whom the transfer occurred.

### Getting Started

Choose your path based on your goals:

* **Platform Integrations** — Jump to [Enterprise Integrations](https://www.kimi.com/chat/19e1549c-9682-8edf-8000-0932619ab22b?chat_enter_method=history#) to explore pre-built connectors for popular enterprise platforms.
* **Custom Enterprise Workflow** — Open [KRNL Studio](https://studio.krnl.xyz/) to visually construct workflows connecting your existing APIs and systems without writing DSL by hand.

### Need Help? <a href="#need-help" id="need-help"></a>

If you feel stuck somewhere, or if you have any feedback or even if you want to say hello, you can reach out to Discord:

* Join the [KRNL Discord Server](https://discord.gg/krnl-labs).

### What's next?

{% content-ref url="/pages/5Wf7JaZ8RRXkzSWLMabk" %}
[Getting Started](/getting-started/getting-started-with-krnl)
{% endcontent-ref %}


# Getting Started

This guide will help you start developing applications that leverage KRNL.

There are **two primary options** for developing using KRNL:

* Our Command-Line Interface (CLI)
* Local development environment

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="image">Cover image</th></tr></thead><tbody><tr><td><strong>Command-line Interface (CLI)</strong></td><td>Use the KRNL command-line interface (CLI) for a flexible local development experience with full control over deployment.</td><td><a href="/pages/Fus9r2Eqo41yTO6CjY7u">/pages/Fus9r2Eqo41yTO6CjY7u</a></td><td><a href="/files/vzMwvaU5qk3WAaSIhCKp">/files/vzMwvaU5qk3WAaSIhCKp</a></td></tr><tr><td><strong>Local Development</strong></td><td>Get started immediately with a local development environment with minimal installation.</td><td><a href="/pages/zQ3nxByVR8cA4m702PgN">/pages/zQ3nxByVR8cA4m702PgN</a></td><td><a href="/files/vEJHJF4smbMGmDbeWTap">/files/vEJHJF4smbMGmDbeWTap</a></td></tr></tbody></table>

Both options support the complete workflow development lifecycle for utilizing the KRNL Protocol.

For additional help and resources, [join our community](https://discord.gg/krnl-labs).


# Local Dev

Goal: To complete the integration of KRNL into your application and to be able to execute verifiable workflows within your environment.

**Read time - 30 minutes**

This guide contains the instructions for deploying relevant components and using the KRNL SDK. For this demo we will use a mock business application where you can submit data, analyze it using a combination of external APIs, run this dataset through an AI model, and get a final verified result to use in your application and the best part is we will do all of this in a single atomic transaction with cryptographic proof. This demo will help you understand the steps to follow to integrate the KRNL Protocol into your application and create a KRNL-powered workflow.

***

### Preparations

* **Install Foundry**
  * Go to <https://getfoundry.sh/>
  * Follow the installation process and run `forge --version` to verify the installation
* **Install Docker**
  * Go to <https://www.docker.com/get-started/> and install Docker Desktop
  * Make sure you sign in/create an account for docker desktop
* **Etherscan (for verifying smart contracts on Sepolia network)** - Find the API key [here](https://etherscan.io/)
* **Sepolia testnet** - "Add a custom network" on your MetaMask wallet (You can download and install using this [link](https://metamask.io/en-GB/download))
* **Funds** - make sure you have a **SepoliaETH** by claiming them from [faucets here](/helpful-resources/testnet-faucets).
  * Sepolia token ≈ **0.1 SepoliaETH**
* **Privy App ID and Secret**
  * Go to [dashboard.privy.io](https://dashboard.privy.io/)
  * Create an app
  * Copy the App ID and secret

<figure><img src="/files/hhmYi2OSudy0Nd8oAG4E" alt=""><figcaption></figcaption></figure>

* **Pimlico API Key**
  * Go to <https://dashboard.pimlico.io/sign-in> and create an account/sign in with your existing account
  * Then navigate to <https://dashboard.pimlico.io/apikeys> and create your api key
  * Keep this API key for later use

### Deploy the Target Contract

#### 1. Clone the repo

Go to your terminal and run this command:

```
git clone https://github.com/KRNL-Labs/poc-dapp-realestateinvestment-7702.git hello-krnl
```

#### 2. Go to contract folder

Run this command:

```
cd hello-krnl/contracts
```

#### 3. Create the .env file

3.1 Copy .env.example to .env

```
cp .env.example .env
```

3.2 Fill the .env file with these values:

```
PRIVATE_KEY=<your_wallet_private_key> //Add your private key with 0x like 0x.....

MOCK_USDC_ADDRESS=0xF2Ea67F83b58225edF11F3Af4A5733B3E0844509 //We have already deployed a mock USD for testing

DELEGATED_ACCOUNT_ADDRESS=0x9969827E2CB0582e08787B23F641b49Ca82bc774 //This is the SCA you will be authorizing to interact with KRNL

# Optional: Etherscan API key for contract verification
ETHERSCAN_API_KEY=<your_etherscan_api>

SEPOLIA_RPC_URL=https://ethereum-sepolia-rpc.publicnode.com //Use any Ethereum Sepolia RPC you have
```

3.3 Run this command in your terminal to set these values for the current session:

```
source .env
```

{% hint style="warning" %}
Make sure you are in the contract folder where we have the .env file or else this command will throw an error
{% endhint %}

{% hint style="info" %}
Follow [this](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key) guide to export MetaMask private key
{% endhint %}

#### 4. Deploy the contract

4.1 Run the following command to install the forge dependencies:

```
forge install OpenZeppelin/openzeppelin-contracts --no-commit
forge install eth-infinitism/account-abstraction@v0.7.0 --no-commit
forge install foundry-rs/forge-std --no-commit
```

{% hint style="warning" %}
If you are using Foundry >=1.2, Make sure to exclude the --no-commit flag
{% endhint %}

4.2 Run the following command to deploy the contract:

```
forge script script/Deploy.s.sol --rpc-url sepolia --broadcast
```

4.3 After the deployment you get screen like this:

<figure><img src="/files/tucZBeIbCgnvgjO7Q87Z" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You have to deploy your own target contract where your EOA will be used as the master key for signature verification, you will learn about this later in the docs
{% endhint %}

### Setup the Attestor Image

Attestor is a component which will attest and also resolve the secrets in your DSL workflow (don't worry we will learn about all of this in the core concepts)

#### 1. Download the `create-attestor` script

```
curl https://public.mypinata.cloud/ipfs/bafkreifvezdhwvmi6psqqk6vxalazp56ovx3fmgqkmfu5ih5xyxsdbfixi -o create-attestor-standalone.sh
chmod +x create-attestor-standalone.sh
```

#### 2. Run the Attestor&#x20;

```
./create-attestor-standalone.sh
```

#### 3. Follow the onscreen instruction

3.1 Enter your project name:

<figure><img src="/files/KMrZhWseV8AfVlAaUqZD" alt=""><figcaption></figcaption></figure>

3.2 Enter Docker registry, it should `docker.io`&#x20;

<figure><img src="/files/4JE3B3S9fHThpWynXeTa" alt=""><figcaption></figcaption></figure>

3.3 Enter your docker username

<figure><img src="/files/5yyHkrzjEUOsNxlfAtAY" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
The script pushes an attestor image to your docker hub so make sure to sign in and ensure that your docker desktop is running in the background while this script is being executed
{% endhint %}

3.4 Enter your private key

<figure><img src="/files/kOylgUh7OLIHh4GVYTzZ" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
This is the same private key which you have derived from your MetaMask wallet
{% endhint %}

3.5 Create a encryption secret which is a password to the safe carrying your private key to make your private key is handled safely. Press enter to auto generate

<figure><img src="/files/RzvB3eRwTszksNq3Cs6s" alt=""><figcaption></figcaption></figure>

3.6 Pass the secrets to resolve in the DSL workflow during execution. For our real estate workflow example, we need:

* rpcSepoliaURL=\<ethereum\_sepolia\_rpc>
* pimlico-apikey=\<api\_key\_of\_your\_pimlico\_account>
* OPENAI\_API\_KEY=mock-api (We are using a mock api in our DSL for the sake of the demo)

<figure><img src="/files/Kxw6vDbr9RoiDKP8p4KO" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
Make sure to replace '<>' with actual values
{% endhint %}

{% hint style="info" %}
We will learn more about workflow DSL later in [Workflows](/core-concepts/workflows). For now make sure to add the exact key pair as a part of creating attestor image
{% endhint %}

3.7 Wait for few seconds and you will see a success screen with your attestor image&#x20;

<figure><img src="/files/MtGdJZTfxJyFfeXJjptS" alt=""><figcaption></figcaption></figure>

### Setup the dApp

#### 1. Go to frontend folder from the contract folder

```
cd ../frontend
```

#### 2. Create the .env file

3.1 Copy .env.example to .env

```
cp .env.example .env
```

3.2 Fill the .env file with these values:

```
VITE_PRIVY_APP_ID=<your_privy_app_id>
VITE_PRIVY_APP_SECRET=<your_privy_secret>

VITE_CHAIN_ID=11155111 //Chain ID for Ethereum Sepolia

VITE_DELEGATED_ACCOUNT_ADDRESS=0x9969827E2CB0582e08787B23F641b49Ca82bc774 // Do not change this

VITE_DELEGATE_OWNER=<your_eoa_address> // This should be the same address you used to create your attestor
VITE_REAL_ESTATE_INVESTMENT_ADDRESS=0x038b5f24FF651d174411F15f8cc64C4156A9a6D0 //Replace this with the target contract address we just deployed
VITE_MOCK_USDC_ADDRESS=0xaC66E9916dCe765405E4A4297DdDF61729CbDFF9

VITE_ATTESTOR_IMAGE=image://docker.io/ash20pk20/attestor-realestate:latest //Replace this image with your attestor image link, make to keep the image:// prefix

VITE_RPC_URL=https://ethereum-sepolia-rpc.publicnode.com //Use any Ethereum Sepolia RPC you have
```

#### 3. Install the dependencies

```
npm install
```

#### 4. Run the application

```
npm run dev
```

{% hint style="info" %}
Your app will be available at <http://localhost:5173/>
{% endhint %}

#### 5. Run your KRNL workflow&#x20;

{% hint style="info" %}
We are running this workflow from your user's point of view&#x20;
{% endhint %}

5.1 Connect your wallet

<figure><img src="/files/qehwakx9Ij2CgW1EB43Y" alt=""><figcaption></figcaption></figure>

5.2 Fund the embedded wallet with Sepolia ETH token

<figure><img src="/files/JhwGXlIgwKzayOhSokoi" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
This wallet is different from your external wallet and this is created automatically as soon as you sign in.
{% endhint %}

5.3 Delegate execution to KRNL smart contract account

<figure><img src="/files/kVf03XlOcQUVRQwhx6xL" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
This embedded wallet is completely independent of your external wallet to make sure your users' personal wallets are safe when delegating execution to our delegated account.
{% endhint %}

5.4 Run the workflow DSL

<figure><img src="/files/O394Aiu5NYthV0xEzV5x" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
The time taken for the execution depends on the latency of the external services being used in the workflow.
{% endhint %}

5.5 Verify the execution in your target contract

<figure><img src="/files/9lJdMgLZUMg9XA4zTsCd" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
The event signifies that the function was called with the KRNL response, the response signature was verified by the modifier and the response was decoded for the application.
{% endhint %}

These steps signify the happy path to deploying your first KRNL-powered application which lets you use functions across multiple environments as well as external APIs, letting you build applications without being limited by existing system design.

### What's next?

Congrats on completing your first hands-on tutorial using KRNL now it's time to learn the [Core Concepts](/core-concepts/workflows) to understand all the concepts and flows in detail.


# CLI

Goal: To complete the integration of KRNL into your application and to be able to execute verifiable workflows within your environment.

**Read time - 30 minutes**

This guide contains the instructions for deploying relevant components and using the KRNL SDK and KRNL CLI. For this demo we will use a mock business application where you can submit data, analyze it using a combination of external APIs, run this dataset through an AI model, and get a final verified result to use in your application and the best part is we will do all of this in a single atomic transaction with cryptographic proof. This demo will help you understand the steps to follow to integrate the KRNL Protocol into your application and create a KRNL-powered workflow.

***

### Preparations

* **Install Docker**
  * Go to <https://www.docker.com/get-started/> and install Docker Desktop
  * Make sure you sign in/create an account for docker desktop
* **Etherscan (for verifying smart contracts on Sepolia network)** - Find the API key [here](https://etherscan.io/)
* **Sepolia testnet** - "Add a custom network" on your MetaMask wallet (You can download and install using this [link](https://metamask.io/en-GB/download))
* **Funds** - make sure you have a **SepoliaETH** by claiming them from [faucets here](/helpful-resources/testnet-faucets).
  * Sepolia token ≈ **0.1 SepoliaETH**
* **Privy App ID and Secret**
  * Go to [dashboard.privy.io](https://dashboard.privy.io/)
  * Create an app
  * Copy the App ID and secret

<figure><img src="/files/hhmYi2OSudy0Nd8oAG4E" alt=""><figcaption></figcaption></figure>

* **Pimlico API Key**
  * Go to <https://dashboard.pimlico.io/sign-in> and create an account/sign in with your existing account
  * Then navigate to <https://dashboard.pimlico.io/apikeys> and create your api key
  * Keep this API key for later use

### Deploy the Target Contract

#### 1. Install the KRNL CLI

Go to your terminal and run this command:

```bash
npm install -g @krnl-dev/krnl-cli
```

#### 2. Clone the repo

Go to your terminal and run this command:

```bash
git clone https://github.com/KRNL-Labs/poc-dapp-realestateinvestment-7702.git hello-krnl
```

#### 3. Go to contract folder

Run this command:

```bash
cd hello-krnl/contracts
```

#### Create the .env file

1.1 Copy .env.example to .env

```bash
cp .env.example .env
```

1.2 Fill the .env file with these values:

```bash
PRIVATE_KEY=<your_wallet_private_key> //Add your private key with 0x like 0x.....

MOCK_USDC_ADDRESS=0x038b5f24FF651d174411F15f8cc64C4156A9a6D0 //We have already deployed a mock USD for testing

DELEGATED_ACCOUNT_ADDRESS=0x9969827E2CB0582e08787B23F641b49Ca82bc774 //This is the SCA you will be authorizing to interact with KRNL

# Optional: Etherscan API key for contract verification
ETHERSCAN_API_KEY=<your_etherscan_api>

SEPOLIA_RPC_URL=https://ethereum-sepolia-rpc.publicnode.com //Use any Ethereum Sepolia RPC you have
```

{% hint style="info" %}
Follow [this](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key) guide to export MetaMask private key
{% endhint %}

#### Deploy the contract

1.1 Run the following command to install the forge dependencies:

```bash
forge install OpenZeppelin/openzeppelin-contracts 
forge install eth-infinitism/account-abstraction@v0.7.0 
forge install foundry-rs/forge-std 
```

1.2 Run the following command to deploy the contract:

```bash
krnl deploy --network sepolia --contract RealEstateInvestment --verify
```

1.3 After the deployment you get screen like this:

<figure><img src="/files/tucZBeIbCgnvgjO7Q87Z" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You have to deploy your own target contract where your EOA will be used as the master key for signature verification, you will learn about this later in the docs
{% endhint %}

### Setup the Attestor Image

Attestor is a component which will attest and also resolve the secrets in your DSL workflow (don't worry we will learn about all of this in the core concepts)

#### 1. Run the Attestor&#x20;

```
krnl create-attestor
```

#### 2. Follow the onscreen instruction

2.1 Enter your project name:

<figure><img src="/files/KMrZhWseV8AfVlAaUqZD" alt=""><figcaption></figcaption></figure>

2.2 Enter Docker registry, it should `docker.io`&#x20;

<figure><img src="/files/4JE3B3S9fHThpWynXeTa" alt=""><figcaption></figcaption></figure>

2.3 Enter your docker username

<figure><img src="/files/5yyHkrzjEUOsNxlfAtAY" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
The script pushes an attestor image to your docker hub so make sure to sign in and ensure that your docker desktop is running in the background while this script is being executed
{% endhint %}

2.4 Enter your private key

<figure><img src="/files/kOylgUh7OLIHh4GVYTzZ" alt=""><figcaption></figcaption></figure>

2.5 Create a encryption secret which is a password to the safe carrying your private key to make your private key is handled safely. Press enter to auto generate

<figure><img src="/files/RzvB3eRwTszksNq3Cs6s" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
This is the same private key which you have derived from your MetaMask wallet
{% endhint %}

2.6 Pass the secrets to resolve in the DSL workflow during execution. For our real estate workflow example, we need:

* rpcSepoliaURL=\<ethereum\_sepolia\_rpc>
* pimlico-apikey=\<api\_key\_of\_your\_pimlico\_account>
* OPENAI\_API\_KEY=mock-api (We are using a mock api in our DSL for the sake of the demo)

<figure><img src="/files/Kxw6vDbr9RoiDKP8p4KO" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
Make sure to replace '<>' with actual values
{% endhint %}

{% hint style="info" %}
We will learn more about workflow DSL later in [Workflows](/core-concepts/workflows). For now make sure to add the exact key pair as a part of creating attestor image
{% endhint %}

2.7 Wait for few seconds and you will see a success screen with your attestor image&#x20;

<figure><img src="/files/MtGdJZTfxJyFfeXJjptS" alt=""><figcaption></figcaption></figure>

### Setup the dApp

#### 1. Go to frontend folder from the contract folder

```
cd ../frontend
```

#### 2. Create the .env file

2.1 Copy .env.example to .env

```
cp .env.example .env
```

2.2 Fill the .env file with these values:

```
VITE_PRIVY_APP_ID=<your_privy_app_id>
VITE_PRIVY_APP_SECRET=<your_privy_secret>

VITE_CHAIN_ID=11155111 //Chain ID for Ethereum Sepolia

VITE_DELEGATED_ACCOUNT_ADDRESS=0x9969827E2CB0582e08787B23F641b49Ca82bc774 // Do not change this

VITE_DELEGATE_OWNER=<your_eoa_address> // This should be the same address you used to create your attestor
VITE_REAL_ESTATE_INVESTMENT_ADDRESS=0x038b5f24FF651d174411F15f8cc64C4156A9a6D0 //Replace this with the target contract address we just deployed
VITE_MOCK_USDC_ADDRESS=0xaC66E9916dCe765405E4A4297DdDF61729CbDFF9

VITE_ATTESTOR_IMAGE=image://docker.io/ash20pk20/attestor-realestate:latest //Replace this image with your attestor image link, make to keep the image:// prefix

VITE_RPC_URL=https://ethereum-sepolia-rpc.publicnode.com //Use any Ethereum Sepolia RPC you have
```

#### 3. Install the dependencies

```
npm install
```

#### 4. Run the application

```
npm run dev
```

{% hint style="info" %}
Your app will be available at <http://localhost:5173/>
{% endhint %}

#### 5. Run your KRNL workflow&#x20;

{% hint style="info" %}
We are running this workflow from your user's point of view&#x20;
{% endhint %}

5.1 Connect your wallet

<figure><img src="/files/qehwakx9Ij2CgW1EB43Y" alt=""><figcaption></figcaption></figure>

5.2 Fund the embedded wallet with Sepolia ETH token

<figure><img src="/files/JhwGXlIgwKzayOhSokoi" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
This wallet is different from your external wallet and this is created automatically as soon as you sign in.
{% endhint %}

5.3 Delegate execution to KRNL smart contract account

<figure><img src="/files/kVf03XlOcQUVRQwhx6xL" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
This embedded wallet is completely independent of your external wallet to make sure your users' personal wallets are safe when delegating execution to our delegated account.
{% endhint %}

5.4 Run the workflow DSL

<figure><img src="/files/O394Aiu5NYthV0xEzV5x" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
The time taken for the execution depends on the latency of the external services being used in the workflow.
{% endhint %}

5.5 Verify the execution in your target contract

<figure><img src="/files/9lJdMgLZUMg9XA4zTsCd" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
The event signifies that the function was called with the KRNL response, the response signature was verified by the modifier and the response was decoded for the application.
{% endhint %}

These steps signify the happy path to deploying your first KRNL-powered application which lets you use functions across multiple environments as well as external APIs, letting you build applications without being limited by existing system design.

### What's next?

Congrats on completing your first hands-on tutorial using KRNL now it's time to learn the [Core Concepts](/core-concepts/workflows) to understand all the concepts and flows in detail.


# How Does the KRNL Protocol Work?

This page is dedicated to illustrating how the KRNL Protocol works when an application submits a transaction to a system, and how systems receive responses from the execution layer. This is the high level architecture:

#### Step 1 — User interacts with dApp

The user initiates an action (e.g., submit data, verify a record, trigger a workflow) through the application frontend, which is integrated with KRNL.

<figure><img src="/files/8U3vIBdTq8Qy9TNcmyhc" alt=""><figcaption></figcaption></figure>

#### Step 2 — User Account (EOA) Authorizes a smart contract account

The user's account delegates execution rights to their delegated account via programmable authorization, enabling automated workflow execution.

<figure><img src="/files/WKeCheQbdJcsXBiUmta0" alt=""><figcaption></figcaption></figure>

#### Step 3 — dApp uses KRNL SDK (fetch metadata)

The application backend uses the KRNL SDK to retrieve workflow definitions and registry metadata, ensuring the correct execution steps and logic are loaded.

<figure><img src="/files/ghxBxVi5l6PM9rEb4zM7" alt=""><figcaption></figcaption></figure>

#### Step 4 — SDK sends JSON-RPC request to KRNL Node

The execution request (workflow definition + parameters) is transmitted to the KRNL Node over a secure protocol for processing.

<figure><img src="/files/GkRCHgz02iCtESYZk3E8" alt=""><figcaption></figcaption></figure>

#### Step 5 — Workflow Engine loads the workflow

The KRNL Node parses the workflow into an execution graph, allocates resources, and prepares execution in an isolated sandbox environment.

<figure><img src="/files/HZ2YxkasnAw8YS1AYFxW" alt=""><figcaption></figcaption></figure>

#### Step 6 — Executor runs steps (sandboxed) and calls externals

Each execution step (API call, database query, data transformation, AI inference) is executed by an Executor within a secure sandbox.

<figure><img src="/files/G7kwK7PxIEPTlQwfTA2P" alt=""><figcaption></figcaption></figure>

#### Step 7 — Attestor signs the final result

The Attestor monitors network traffic, derives ephemeral keys, and cryptographically signs the final execution result, producing a verifiable proof.

<figure><img src="/files/SsmYDICI1KlBIw17Mdrf" alt=""><figcaption></figcaption></figure>

#### Step 8 — KRNL Node sends the UserOps to the Relayer/Bundler&#x20;

The signed execution proof is wrapped into a structured request and handed off to the external bundler for settlement.

<figure><img src="/files/soOmnkfm4ctPsdnnNtAF" alt=""><figcaption></figcaption></figure>

#### Step 9 — Bundler forwards the UserOps after validation to designated SCA

The bundler checks proof validity, batches requests if needed, optimizes resource usage, and submits the request to the delegated account for final processing.

<figure><img src="/files/c2RAUWTIWC6XVWFyZ4Ut" alt=""><figcaption></figcaption></figure>

#### Step 10 — SCA sends the fees to KRNL Vault & Execute the target smart contract

The delegated account verifies the attestor's signature, atomically transfers execution fees to the KRNL Vault, and calls the target system with the verified response.

<figure><img src="/files/BnxbltCM1Lwtt9NruXiq" alt=""><figcaption></figcaption></figure>

#### Step 11 — Target Contract updates state / business logic

The target contract executes its logic (e.g., update records, trigger payments, issue credentials) only after validating the KRNL proof, ensuring verified execution is logged on a tamper proof blockchain.

<figure><img src="/files/QvmBCNS6xTg0LExj4dsO" alt=""><figcaption></figcaption></figure>

<br>


# Overview

## Enterprise Integrations

KRNL provides pre-built integration patterns for popular enterprise platforms, enabling you to add cryptographic verification, audit trails, and automated workflows to your existing systems without replacing your infrastructure.

### Available Integrations

| Platform                                            | Capability                                                                                   |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| [Salesforce](/enterprise-integration/salesforce)    | Secure document management with identity-bound watermarking and cryptographic fingerprinting |
| [HubSpot](/enterprise-integration/hubspot)          | Secure document management with identity-bound watermarking and cryptographic fingerprinting |
| [Custom](/enterprise-integration/custom-connectors) | Build your own connector using the KRNL SDK and Studio                                       |

### Common Integration Patterns

All enterprise integrations follow the same underlying pattern:

1. **Connect** — Authenticate to your platform via standard OAuth or API keys
2. **Define** — Map platform events (record updates, file uploads, stage changes) to KRNL workflow triggers
3. **Execute** — KRNL runs the workflow in a sandboxed environment with full attestation
4. **Verify** — Results are cryptographically signed and delivered back to your platform
5. **Audit** — Every action is logged with an immutable proof for compliance reporting

### Security Considerations

* Platform credentials are resolved at runtime by your Attestor, never stored in workflow definitions
* All platform API calls are intercepted, logged, and signed by the Attestor
* Watermarks, fingerprints, and proofs are generated server-side, not client-side
* Delegated accounts ensure user wallets are never exposed to integration logic


# Salesforce

The KRNL Secure Document Manager for Salesforce brings cryptographically verifiable document integrity and identity-bound watermarking directly into your Salesforce record pages. It is a managed package that adds a layer of trust and accountability to document workflows without replacing your existing Salesforce infrastructure.

### What It Does

* **Upload** — Users upload documents directly from any Salesforce record page. The system generates a unique cryptographic fingerprint and anchors it for tamper-evident verification.
* **Watermark** — Every viewer receives a personalized watermark tied to their Salesforce identity. If a document is screenshotted, shared, or leaked, the watermark identifies the source.
* **Verify** — The system can confirm at any time whether a document matches its original fingerprint, detecting alterations or substitutions.
* **Audit** — All uploads, views, and verification checks are logged with immutable proofs, creating a complete compliance trail inside Salesforce.

### How It Works

The integration follows a simple four-step flow that runs behind the familiar Salesforce interface:

#### 1. Upload and Fingerprint

When a user uploads a document through the KRNL Lightning component:

* The document is sent to a secure processing service
* A cryptographic fingerprint (hash) is generated from the document content
* The fingerprint is anchored via the KRNL Protocol, creating a permanent, verifiable record
* The document is stored in secure storage; only the fingerprint is anchored, not the document itself

#### 2. Identity Confirmation

When a user requests to view a document:

* The system confirms the user's Salesforce identity
* Access permissions are checked against the record and document settings
* Unauthorized access attempts are denied and logged

#### 3. Watermarked Delivery

For authorized viewers:

* The original document is retrieved from secure storage
* A personalized watermark is applied in real time, tied to the viewer's Salesforce user ID
* A secure viewing session is created
* The watermarked document is delivered to the user

#### 4. Audit and Compliance

Every action is logged:

* Who uploaded the document and when
* Who viewed the document and when
* Whether the document was verified against its original fingerprint
* All events are stored with cryptographic proofs for independent audit

### Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│  Salesforce Platform                                        │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │ Record Page │  │ Lightning   │  │ Access Logs         │  │
│  │ (Account,   │──│ Component   │──│ (Audit Trail)       │  │
│  │ Opportunity)│  │ (Upload/View)│  │                    │  │
│  └─────────────┘  └──────┬──────┘  └─────────────────────┘  │
└───────────────────────────┬─────────────────────────────────┘
                            │
┌───────────────────────────▼───────────────────────────────────┐
│  KRNL Integrated Backend                                      │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐    │
│  │ Fingerprint │  │ Anchor      │  │ Watermark Engine    │    │
│  │ Generation  │──│ Proof       │──│ (Identity-Bound)    │    │
│  │             │  │             │  │                     │    │
│  └─────────────┘  └─────────────┘  └─────────────────────┘    │
│                                                               │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │ Attestor (Developer-Controlled)                         │  │
│  │ • Signs all fingerprints and access events              │  │
│  │ • Resolves secrets (API keys, storage credentials)      │  │
│  │ • Generates cryptographic proofs for every action       │  │
│  └─────────────────────────────────────────────────────────┘  │ 
└───────────────────────────────────────────────────────────────┘
                            │
┌───────────────────────────▼───────────────────────────────────┐
│  Infrastructure                                               │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐    │
│  │ Secure      │  │ Blockchain  │  │ Identity Provider   │    │
│  │ Storage     │  │ Anchor      │  │ (Salesforce Auth)   │    │
│  └─────────────┘  └─────────────┘  └─────────────────────┘    │
└───────────────────────────────────────────────────────────────┘
```

### Key Capabilities

| Capability                              | What It Means for Your Organization                                                                                                          |
| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| **Blockchain-anchored integrity**       | Every document receives an immutable fingerprint that cannot be altered. If the document changes, the fingerprint no longer matches.         |
| **Lightning-based upload and delivery** | Users interact through a native Salesforce component. No external portals, no context switching, no training required.                       |
| **Identity-bound watermarking**         | Every viewer's identity is embedded into the document they receive. Leaked documents are traceable to the individual who viewed them.        |
| **Leak prevention by design**           | Screenshots, recordings, and shared copies always contain traceable identifiers. There is no anonymous way to extract a clean document.      |
| **Authenticity enforcement**            | Any modification to a document invalidates its fingerprint. Verification fails if the document has been tampered with.                       |
| **Full auditability inside Salesforce** | Admins can see who uploaded each document, who viewed it, when, and whether the document passed verification—all without leaving Salesforce. |

### Security Model

#### Data Handling

* **Document content never touches the blockchain.** Only the cryptographic fingerprint is anchored. The document itself remains in your secure storage.
* **Watermarks are applied server-side.** The client receives an already-watermarked image or PDF. There is no clean original delivered to the browser.
* **All access routes through the protected pipeline.** There are no direct URLs to stored documents that could bypass identity checks.

#### Identity and Access

* **Salesforce authentication is the gate.** The system relies on your existing Salesforce identity provider, roles, and permission sets.
* **Access is record-scoped.** A user must have access to the parent Salesforce record to see documents attached to it.
* **Session-bound viewing.** Each document view creates a time-limited session. Watermarks include session identifiers for additional traceability.

#### Cryptographic Assurance

* **Developer-controlled attestor.** Your organization controls the attestation policy and signing keys. KRNL does not hold or operate your attestor.
* **Every action is signed.** Uploads, views, and verifications each produce a cryptographic proof that can be independently verified.
* **Immutable audit trail.** Event logs are structured and signed. They can be exported for external audit or compliance review.

### Installation

The Secure Document Manager is distributed as a Salesforce managed package. Installation requires:

1. **Salesforce admin privileges** to install the package and assign permission sets
2. **A KRNL attestor image** configured with your organization's secrets (API keys, storage credentials, signing keys)
3. **Lightning App Builder access** to add the component to your record pages

For detailed installation steps, configuration options, and troubleshooting, refer to the repository below.

### Repository and Resources

| Resource                           | Link                                                                                 |
| ---------------------------------- | ------------------------------------------------------------------------------------ |
| Source code and installation guide | [github.com/KRNL-Labs/salesforce-krnl](https://github.com/KRNL-Labs/salesforce-krnl) |
| Managed package installation       | See repository README                                                                |
| Configuration documentation        | See repository README                                                                |

### Common Questions

<details>

<summary>Does this replace our existing document storage?</summary>

No. The integration works with your existing storage. KRNL adds a verification and watermarking layer on top.

</details>

<details>

<summary>Can we use this with custom Salesforce objects?</summary>

Yes. The Lightning component can be added to any record page, including custom objects

</details>

<details>

<summary>Where are the documents actually stored?</summary>

Document storage is configurable. The default uses secure cloud storage; enterprise deployments can route to private storage or VPC-resident systems.

</details>

<details>

<summary>What happens if the KRNL service is unavailable?</summary>

Document uploads and views are queued gracefully. The Salesforce UI continues to function; verification and watermarking resume when connectivity is restored.

</details>

<details>

<summary>How do we prove compliance to auditors? </summary>

All events are logged with signed proofs. Export the audit log and provide the attestation hashes. Auditors can independently verify the proofs without KRNL's involvement.

</details>

### Next Steps

* Install the managed package from the repository
* Configure your attestor with storage and API credentials
* Add the Lightning component to your record pages
* Review the [Building Custom Enterprise Connectors](https://www.kimi.com/chat/19e1549c-9682-8edf-8000-0932619ab22b?chat_enter_method=history#) guide to extend this pattern to other platforms


# HubSpot

The KRNL Secure Document Manager for HubSpot brings cryptographically verifiable document integrity and identity-bound watermarking directly into your HubSpot deal and contact workflows. It is a dedicated application that adds a layer of trust and accountability to document sharing with prospects, customers, and partners, without replacing your existing HubSpot infrastructure.

### What It Does

* **Upload** — Users upload documents directly from the HubSpot application. The system generates a unique cryptographic fingerprint and anchors it for tamper-evident verification.
* **Watermark** — Every viewer receives a personalized watermark tied to their HubSpot identity. If a document is screenshotted, shared, or leaked, the watermark identifies the source.
* **Verify** — The system can confirm at any time whether a document matches its original fingerprint, detecting alterations or substitutions.
* **Audit** — All uploads, views, and verification checks are logged with immutable proofs, creating a complete compliance trail.

### How It Works

The integration follows a simple four-step flow that runs behind the familiar HubSpot-connected interface:

#### 1. Upload and Fingerprint

When a user uploads a document through the application:

* The document is sent to a secure processing service
* A cryptographic fingerprint (hash) is generated from the document content
* The fingerprint is anchored via the KRNL Protocol, creating a permanent, verifiable record
* The document is stored in secure storage; only the fingerprint is anchored, not the document itself

#### 2. Identity Confirmation

When a user requests to view a document:

* The system confirms the user's identity through HubSpot authentication
* Access permissions are checked against the associated deal, contact, or company record
* Unauthorized access attempts are denied and logged

#### 3. Watermarked Delivery

For authorized viewers:

* The original document is retrieved from secure storage
* A personalized watermark is applied in real time, tied to the viewer's HubSpot user identity
* A secure viewing session is created
* The watermarked document is delivered to the user

#### 4. Audit and Compliance

Every action is logged:

* Who uploaded the document and when
* Who viewed the document and when
* Whether the document was verified against its original fingerprint
* All events are stored with cryptographic proofs for independent audit

### Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│  HubSpot Platform                                           │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │ Deals       │  │ Contacts    │  │ Activity Timeline   │  │
│  │ (Records)   │──│ (Records)   │──│ (Event Log)         │  │
│  │             │  │             │  │                     │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
└───────────────────────────┬─────────────────────────────────┘
                            │
┌───────────────────────────▼───────────────────────────────────┐
│  HubSpot Application                                        │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐   │
│  │ OAuth Login │  │ Document    │  │ Access Logs         │   │
│  │ (HubSpot    │──│ Upload/View │──│ (Audit Trail)       │   │
│  │  Identity)  │  │ Interface   │  │                     │   │
│  └─────────────┘  └──────┬──────┘  └─────────────────────┘   │
└──────────────────────────┬────────────────────────────────────┘
                           │
┌──────────────────────────▼────────────────────────────────────┐
│  Backend Integrated with KRNL                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐    │
│  │ Fingerprint │  │ Anchor      │  │ Watermark Engine    │    │
│  │ Generation  │──│ Proof       │──│ (Identity-Bound)    │    │
│  │             │  │             │  │                     │    │
│  └─────────────┘  └─────────────┘  └─────────────────────┘    │
│                                                               │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │ Attestor (Developer-Controlled)                         │  │
│  │ • Signs all fingerprints and access events              │  │
│  │ • Resolves secrets (API keys, storage credentials)      │  │
│  │ • Generates cryptographic proofs for every action       │  │
│  └─────────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────────┘
                            │
┌───────────────────────────▼───────────────────────────────────┐
│  Infrastructure                                               │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐    │
│  │ Secure      │  │ Blockchain  │  │ Identity Provider   │    │
│  │ Storage     │  │ Anchor      │  │ (HubSpot Auth)      │    │
│  └─────────────┘  └─────────────┘  └─────────────────────┘    │
└───────────────────────────────────────────────────────────────┘
```

### Key Capabilities

| Capability                        | What It Means for Your Organization                                                                                                      |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| **Blockchain-anchored integrity** | Every document receives an immutable fingerprint that cannot be altered. If the document changes, the fingerprint no longer matches.     |
| **HubSpot-native identity**       | Users authenticate with their existing HubSpot credentials. No separate accounts, no password fatigue.                                   |
| **Identity-bound watermarking**   | Every viewer's identity is embedded into the document they receive. Leaked documents are traceable to the individual who viewed them.    |
| **Leak prevention by design**     | Screenshots, recordings, and shared copies always contain traceable identifiers. There is no anonymous way to extract a clean document.  |
| **Authenticity enforcement**      | Any modification to a document invalidates its fingerprint. Verification fails if the document has been tampered with.                   |
| **Full auditability**             | Admins can see who uploaded each document, who viewed it, when, and whether the document passed verification—all within the application. |

### Security Model

#### Data Handling

* **Document content never touches the blockchain.** Only the cryptographic fingerprint is anchored. The document itself remains in your secure storage.
* **Watermarks are applied server-side.** The client receives an already-watermarked image or PDF. There is no clean original delivered to the browser.
* **All access routes through the protected pipeline.** There are no direct URLs to stored documents that could bypass identity checks.

#### Identity and Access

* **HubSpot authentication is the gate.** The system relies on your existing HubSpot identity provider, teams, and permissions.
* **Access is record-scoped.** A user must have access to the associated HubSpot deal, contact, or company to see documents attached to it.
* **Session-bound viewing.** Each document view creates a time-limited session. Watermarks include session identifiers for additional traceability.

#### Cryptographic Assurance

* **Developer-controlled attestor.** Your organization controls the attestation policy and signing keys. KRNL does not hold or operate your attestor.
* **Every action is signed.** Uploads, views, and verifications each produce a cryptographic proof that can be independently verified.
* **Immutable audit trail.** Event logs are structured and signed. They can be exported for external audit or compliance review.

### Installation

The Secure Document Manager is deployed as a standalone web application with HubSpot OAuth integration. Installation requires:

1. **HubSpot App configuration** — Register your app in the HubSpot Developer Portal to obtain a Client ID and Secret
2. **A publicly accessible application** — Hosted backend and frontend for OAuth callbacks and user access
3. **A KRNL attestor image** — Configured with your organization's secrets (storage credentials, signing keys)
4. **Permission setup** — Configure HubSpot scopes for deals, contacts, and companies as needed

For detailed installation steps, OAuth configuration, and deployment guidance, refer to the repository below.

### Repository and Resources

Table

| Resource                           | Link                                                                           |
| ---------------------------------- | ------------------------------------------------------------------------------ |
| Source code and installation guide | [github.com/KRNL-Labs/hubspot-krnl](https://github.com/KRNL-Labs/hubspot-krnl) |
| OAuth setup                        | See repository README                                                          |
| Configuration documentation        | See repository README                                                          |

### Common Questions

<details>

<summary>Does this replace our existing document storage?</summary>

No. The integration works with your existing storage. KRNL adds a verification and watermarking layer on top.

</details>

<details>

<summary>Can we use this with custom HubSpot objects?</summary>

Yes. The application can associate documents with any HubSpot object that supports API access, including custom objects.

</details>

<details>

<summary>Where are the documents actually stored?</summary>

Document storage is configurable. The default uses secure cloud storage; enterprise deployments can route to private storage or VPC-resident systems.

</details>

<details>

<summary>What happens if the KRNL service is unavailable?</summary>

Document uploads and views are queued gracefully. The application UI continues to function; verification and watermarking resume when connectivity is restored.

</details>

<details>

<summary>How do we prove compliance to auditors?</summary>

All events are logged with signed proofs. Export the audit log and provide the attestation hashes. Auditors can independently verify the proofs without KRNL's involvement.

</details>

### Next Steps

* Clone the repository and configure HubSpot OAuth in the Developer Portal
* Set up your attestor with storage and API credentials
* Deploy the application backend and frontend
* Authenticate with HubSpot and upload your first document
* Review the [Building Custom Enterprise Connectors](https://www.kimi.com/chat/19e1549c-9682-8edf-8000-0932619ab22b?chat_enter_method=history#) guide to extend this pattern to other platforms


# Custom Connectors

### Overview

You can build a custom connector using the KRNL SDK, KRNL Studio, and standard HTTP workflow steps. This page walks you through the architecture, patterns, and implementation details based on how we built the Salesforce and HubSpot connectors.

### Integration Architecture Pattern

1. **Authenticate** — Use the HTTP executor to connect to your platform's API
2. **Trigger** — Define what events should initiate a KRNL workflow
3. **Transform** — Map platform data formats to KRNL workflow inputs
4. **Attest** — Let the Attestor sign all platform API calls and responses
5. **Respond** — Deliver signed results back to your platform or to downstream systems

### Building Your Own Connector: Step-by-Step

#### Step 1: Define the Integration Boundary

Ask these questions before writing code:

| Question                                            | Example Answers                                                       |
| --------------------------------------------------- | --------------------------------------------------------------------- |
| What platform event triggers the workflow?          | Record created, file uploaded, stage changed, form submitted          |
| What data does the workflow need from the platform? | User identity, record fields, file content, timestamps                |
| What external services does the workflow call?      | Internal APIs, third-party verification, AI models                    |
| What is the final verified output?                  | A hash, a status, a transformed record, a credential                  |
| Where does the proof get consumed?                  | Back to the platform, to a downstream system, to a compliance archive |

#### Step 2: Build the Platform Interface

**For UI-driven integrations** (like Salesforce):

* Create a native component using the platform's component framework
* Handle authentication via OAuth or API keys
* Capture user actions and forward to your backend

**For event-driven integrations** (like HubSpot):

* Register a webhook endpoint in the platform
* Validate incoming webhooks (signature, timestamp, nonce)
* Queue the request for async processing

#### Step 3: Build the Backend Bridge

Your backend acts as a translator between platform conventions and KRNL workflow inputs:

```typescript
// Example: Transform platform webhook to KRNL workflow request
function transformHubSpotWebhook(payload: HubSpotWebhook): WorkflowRequest {
  return {
    chain_id: 11155111,
    sender: payload.objectId,
    target: {
      contract: process.env.TARGET_CONTRACT,
      function: "submitComplianceCheck((uint256,string,string,uint256,string),string)",
      authData_result: "${construct-compliance-proof.result}",
      parameters: [
        { name: "dealId", type: "string", value: payload.objectId }
      ]
    },
    workflow: {
      name: "hubspot-compliance-check",
      steps: [
        // ... steps defined above
      ]
    }
  };
}
```

#### Step 4: Define the KRNL Workflow

Use KRNL Studio or write DSL directly. Follow these patterns: **Store platform credentials as Attestor secrets, never in workflow definitions.** Follow [this page](/krnl-studio/how-to-construct-a-workflow) to build a KRNL workflow

Your backend should:

1. Trigger the KRNL workflow using the RPC link
2. Update the platform record with the verified result
3. Emit an audit event with the attestation hash for compliance
4. Handle failures gracefully (retry, alert, fallback)

### Security Best Practices

#### Credential Management

| Do                                          | Don't                                        |
| ------------------------------------------- | -------------------------------------------- |
| Store platform API keys as Attestor secrets | Hardcode credentials in workflow definitions |
| Rotate secrets via Attestor updates         | Share secrets across multiple workflows      |
| Use environment variables for URLs          | Expose internal endpoints in public repos    |
| Validate webhook signatures                 | Trust webhook payloads without verification  |

#### Data Handling

| Do                                      | Don't                                                 |
| --------------------------------------- | ----------------------------------------------------- |
| Hash sensitive content before anchoring | Store raw PII on-chain or in attestor logs            |
| Apply watermarks server-side            | Rely on client-side watermarking that can be bypassed |
| Log access events with user identity    | Log anonymous events that cannot be audited           |
| Encrypt data in transit and at rest     | Send sensitive data over unencrypted channels         |

#### Error Handling

| Scenario                   | Response                                                      |
| -------------------------- | ------------------------------------------------------------- |
| Platform API timeout       | Retry with exponential backoff; alert after 3 failures        |
| KRNL Node unavailable      | Queue request; notify operations team on Discord              |
| Attestor signature invalid | Reject result; do not update platform state; trigger incident |
| Webhook replay detected    | Deduplicate by intent ID; log and alert                       |

### Example Repositories

| Platform   | Pattern                          | Repository                                                                |
| ---------- | -------------------------------- | ------------------------------------------------------------------------- |
| Salesforce | Document-centric UI integration  | [KRNL-Labs/salesforce-krnl](https://github.com/KRNL-Labs/salesforce-krnl) |
| HubSpot    | Event-driven workflow automation | [KRNL-Labs/hubspot-krnl](https://github.com/KRNL-Labs/hubspot-krnl)       |

### Best Practices

* Store platform credentials as Attestor secrets, never in workflow definitions
* Use environment variables for endpoint URLs
* Include replay protection with intent IDs and deadlines
* Emit events for all platform interactions for auditability

### Need Help?

Contact our enterprise team for architecture reviews and custom connector development on [Discord](https://discord.gg/krnl-labs).


# Workflows

***

### Introduction

A **workflow** is a **directed acyclic graph (DAG)** of execution steps that combine Web2 services, blockchain interactions, and AI logic into a single verifiable process. Each step is isolated, cryptographically attested, and connected through explicit input/output bindings.

### Structure of a Workflow

A **workflow** is divided logical checkpoints. This segmentation makes it easier for developers to design, audit, and verify workflows while ensuring all mandatory protocol components are in place.

```json
{
  //Basic info for the execution content
  "chain_id": <chain id>,                       // Chain ID of the target chain
  "sender": "<address>",                        // Wallet address initiating execution
  "delegate": "<delegate-address>",             // Optional delegated account
  "attestor": "<attestor-url>",                 // IPFS or signed attestor config
  
  // Details of the Target contract
  "target": {
    "contract": "{{ENV.TARGET_CONTRACT}}",      // Address of the target contract (passed as env)
    "function": "<function signature>",         // Function signature to call on the target contract
    "authData_result": "${construct-property-analysis-evm.result}", // Referencing the result of the EVM CONSTRUCT STEP
    "parameters": [] // If there are any extra param other than the AuthData tuple can be handled here
  },
  "sponsor_execution_fee": true, // If you want to sponsor the execution fee for the user
  "value": "0", // If the target function signature is payable
  "intent": {
    "id": "{{TRANSACTION_INTENT_ID}}",                // Unique identifier for intent
    "signature": "{{USER_SIGNATURE}}",                // User signature over intent
    "deadline": "{{TRANSACTION_INTENT_DEADLINE}}"     // Expiry timestamp
  },
  
  // RPC and Bundler config
  "rpc_url": "${_SECRETS.rpcSepoliaURL}",
  "bundler_url": "https://api.pimlico.io/v2/sepolia/rpc?apikey=${_SECRETS.pimlico-apikey}",
  "paymaster_url": "https://api.pimlico.io/v2/sepolia/rpc?apikey=${_SECRETS.pimlico-apikey}",
  "gas_limit": "100000",
  "max_fee_per_gas": "20000000000",
  "max_priority_fee_per_gas": "2000000000",
  
  // Workflow steps
  "workflow": {
    "name": "<workflow-name>",
    "version": "1.0.0",
    "steps": [
      {
        "name": "<step-name>",
        "type": "<step-type>",                  // HTTP, EVM_READ, EVM_ENCODER, BUNDLE
        "image": "<executor-image>",            // Containerized executor image
        "attestor": "<attestor-url>",           // Attestor configuration
        "next": "<next-step>",                  // Optional link to next step
        "config": { },                          // Step-specific configuration
        "inputs": { },                          // Data from user or previous step
        "outputs": [ ]                          // Data exported for next steps
      }
    ]
  }
}

```

A workflow definition contains 4 logical checkpoints:

1️⃣ Basic Info&#x20;

2️⃣ Target Contract Details&#x20;

3️⃣ RPC and Bundler Config

4️⃣ Workflow Steps

#### 1. Basic Info&#x20;

Defines the the context for execution.&#x20;

```json
{
  "chain_id": <chain id>,                       // Chain ID of the target chain
  "sender": "<address>",                        // Wallet address initiating execution
  "delegate": "<delegate-address>",             // Optional delegated account
  "attestor": "<attestor-url>",                 // IPFS or signed attestor config
}
```

#### Field-by-field explanation:

* **`chain_id`**
  * Identifies the blockchain network where the transaction/workflow will execute.
  * Examples:
    * `1` → Ethereum mainnet
    * `11155111` → Ethereum Sepolia testnet
  * Prevents replay attacks across chains (so the intent is valid only on the specified network).
* **`sender`**
  * The **EOA (Externally Owned Account)** or **contract account** that originates the workflow.
  * This is the primary identity responsible for initiating execution.
  * Typically signs the intent to prove authorization.
* **`delegate`** *(optional)*
  * An alternate account that executes on behalf of the `sender`.
  * Useful for:
    * **Delegated accounts** (EIP-7702 / Account Abstraction patterns).
    * Letting a smart contract wallet or sponsor pay fees and submit the transaction.
  * If unset, the `sender` executes directly.
* **`attestor`**
  * Points to the **attestation policy** that validates this execution.
  * Could be:
    * An **IPFS hash** storing attestor configuration.
    * A **container image reference** (`image://…`) that encapsulates attestation logic.
  * Ensures that every workflow step is **verifiable** and comes from a trusted source.

***

#### 2. Target Contract Details&#x20;

Defines the the context for execution.&#x20;

```json
{
  //basic info above (chain_id, sender, etc.)

  "target": {
    "contract": "{{ENV.TARGET_CONTRACT}}",      // Address of the target contract (passed as env)
    "function": "<function signature>",         // Function signature to call on the target contract
    "authData_result": "${construct-property-analysis-evm.result}", 
                                                // Reference to the encoded data produced 
                                                // by a previous EVM_CONSTRUCT step
    "parameters": []                            // Any additional parameters beyond AuthData tuple
  },
  "sponsor_execution_fee": true,                // If true, execution gas is covered by sponsor
  "value": "0",                                 // ETH or native token value sent along (if payable)
  "intent": {
    "id": "{{TRANSACTION_INTENT_ID}}",          // Unique identifier for this execution intent
    "signature": "{{USER_SIGNATURE}}",          // User’s cryptographic signature authorizing execution
    "deadline": "{{TRANSACTION_INTENT_DEADLINE}}" 
                                                // Expiry timestamp after which intent is invalid
  }
}

```

#### Field-by-field breakdown

* **`target`**
  * **`contract`**
    * The on-chain smart contract address you want to call.
      * Typically passed as an environment variable so it can change across deployments (testnet vs. mainnet).
  * **`function`**
    * The **ABI function signature** (e.g., `submitPropertyAnalysis((uint256,string))`).
      * Defines exactly what function of the contract will be executed.
  * **`authData_result`**
    * Refers to output from a previous workflow step — specifically an **EVM ENCODER/CONSTRUCT step** that builds the calldata (like ABI encoding).
      * Keeps the pipeline composable: workflow steps generate data, and this field consumes it.
  * **`parameters`**
    * Holds any **extra arguments** that the contract function might need, besides the primary `AuthData`.
      * Empty array `[]` if not needed.

***

* **`sponsor_execution_fee`**
  * Boolean flag:
    * `true` → A **sponsor (e.g., paymaster)** covers the gas fees for this execution.
      * `false` → The **user pays** fees directly.
  * Implements **gasless transactions** or meta-transactions.

***

* **`value`**
  * The **amount of native token** (e.g., ETH, MATIC) sent along with the contract call.
  * `0` if the function is not payable.
  * Non-zero when the function requires value transfer.

***

* **`intent`**
  * Encapsulates **user authorization** for the execution.
    * **`id`** → A globally unique identifier for this execution request. Prevents replay and duplication.
      * **`signature`** → The cryptographic signature from the `sender` proving they approved this intent.
      * **`deadline`** → Expiration timestamp. After this point, the intent can no longer be executed, even if signed

***

#### 3. RPC and Bundler Config

Defines the the context for execution.&#x20;

```json
{
  //basic info above (chain_id, sender, etc.)
  //target contract details

  "rpc_url": "${_SECRETS.rpcSepoliaURL}",                   // RPC endpoint for chain interaction
  "bundler_url": "https://api.pimlico.io/v2/sepolia/rpc?apikey=${_SECRETS.pimlico-apikey}", 
                                                            // Bundler service for Account Abstraction txs
  "paymaster_url": "https://api.pimlico.io/v2/sepolia/rpc?apikey=${_SECRETS.pimlico-apikey}", 
                                                            // Paymaster service (for sponsored gas)
  "gas_limit": "100000",                                    // Upper bound on gas consumption for tx
  "max_fee_per_gas": "20000000000",                         // Absolute max gas fee user is willing to pay
  "max_priority_fee_per_gas": "2000000000"                  // Miner/validator tip to prioritize tx
}

```

#### Field-by-field explanation

* **`rpc_url`**
  * The **Ethereum JSON-RPC endpoint** used to interact with the target chain (Sepolia in this case).
  * Provided via a secret (`_SECRETS.rpcSepoliaURL`) for security.
  * Required for submitting transactions and reading chain state.
* **`bundler_url`**
  * The **ERC-4337 bundler service endpoint**.
  * A bundler collects multiple **user operations (UserOps)** and submits them as transactions.
  * This enables **Account Abstraction workflows** where EOAs don’t directly broadcast transactions.
* **`paymaster_url`**
  * Endpoint for a **paymaster service**, which can sponsor or subsidize gas fees.
  * Lets dApps or protocols offer **gasless user experiences**.
  * Works in conjunction with the bundler.
* **`gas_limit`**
  * The maximum amount of gas this transaction is allowed to consume.
  * Prevents runaway execution and ensures cost predictability.
* **`max_fee_per_gas`**
  * Defines the **absolute maximum fee per unit of gas** the user is willing to pay.
  * Denominated in **wei** (here: `20 gwei`).
  * Protects the user from sudden fee spikes.
* **`max_priority_fee_per_gas`**
  * The **tip paid to validators/miners** on top of the base fee.
  * Incentivizes faster inclusion of the transaction.
  * Here: `2 gwei`.

#### 2. Workflow Steps (Business Logic)

The core business logic, expressed as a DAG of steps. Each step is executed by an **executor** and verified by an **attestor**. We categorize workflow steps into five major types:

#### 2.1. HTTP Request Steps

**What it is:** Perform Web2 API requests (GET, POST).\
**When to use:** Fetch off-chain data (prices, telemetry, compliance feeds) or write to external APIs/databases.

**Example – GET:**

```json
{
  "name": "fetch-telemetry",
  "image": "ghcr.io/krnl-labs/executor-http@sha256:7ea7eae002f173aab994444e9e0863f8a8fd8255c7ed3a234218e66c3e1f3c60",
  "attestor": "https://public.mypinata.cloud/ipfs/bafybeid3msoebov6o54rtvjtrdwv7fg6tkeye2skrxh6jis25zok6pavzi",
  "next": "write-db",
  "config": {},
  "inputs": {
    "url": "https://doc.platform.lat/metacube/telemetry",
    "method": "GET"
  },
  "outputs": [
    {
      "name": "cpu_usage_percent",
      "value": "response.body.cpu_usage_percent",
      "export": true
    }
  ]
}
```

#### Field-by-field Explanation

* **`name`**: Human-readable label (`fetch-telemetry`).
* **`image`**: Executor container image – this one is a specific digest of the HTTP executor.
* **`attestor`**: Cryptographic attestation source (IPFS file/image link with verification metadata).
* **`next`**: Defines the step to run after this (`write-db`).
* **`config`**: Reserved for step-specific tuning (empty here).
* **`inputs`**:
  * `url`: Endpoint to fetch telemetry data from.
  * `method`: `"GET"` since it’s just retrieving.
* **`outputs`**:
  * Maps a value from the HTTP response → workflow variable.
  * Here: `"response.body.cpu_usage_percent"` is extracted and exported as `cpu_usage_percent` for downstream steps.

**Example – POST:**

```json
{
  "name": "write-db",
  "image": "ghcr.io/krnl-labs/executor-http@sha256:...",
  "attestor": "ipfs://.../attestor.json",
  "next": "construct-evm",
  "config": {},
  "inputs": {
    "url": "https://doc.platform.lat/zetaabc/telemetry",
    "method": "POST",
    "headers": {
      "Content-Type": "application/json"
    },
    "body": {
      "cpu": "80",
      "mem": "85"
    }
  },
  "outputs": [
    {
      "name": "status",
      "value": "response.body.status",
      "export": true
    }
  ]
}
```

#### Field-by-field Explanation

* **`name`**: Step identifier (`write-db`).
* **`image`**: Again the HTTP executor container (different digest).
* **`attestor`**: IPFS link to its attestation metadata.
* **`next`**: Next step is `construct-evm` (likely assembling a transaction).
* **`inputs`**:
  * `url`: Target API for database write.
  * `method`: `"POST"`.
  * `headers`: Standard JSON content type.
  * `body`: JSON payload with telemetry (`cpu`, `mem`).
* **`outputs`**:
  * Extracts `"response.body.status"` and exports as `status`.

{% hint style="warning" %}
The executor and attestor image should remain constant, rest the config, inputs and outputs can change according to your use case
{% endhint %}

***

#### 2.2. EVM Read Steps

**What it is:** Query smart contract state via read-only calls.\
**When to use:** Fetch balances, interest rates, prices, or other on-chain data without modifying state.

**Example:**

```json
{
  "name": "EVM-data-fetcher",
  "image": "ghcr.io/krnl-labs/executor-evm-read@sha256:9c15f3e004352f1062a22b8bf7d7fa80498449b9407bc6efc107dbdd7acce5a4",
  "attestor": "https://public.mypinata.cloud/ipfs/bafybeid3msoebov6o54rtvjtrdwv7fg6tkeye2skrxh6jis25zok6pavzi",
  "next": "construct-evm",
  "config": {
    "function_signature": "balanceOf(address)",
    "input_parameters": [
      {
        "name": "account",
        "type": "address"
      }
    ],
    "output_parameters": [
      {
        "name": "balance",
        "type": "uint256"
      }
    ]
  },
  "inputs": {
    "value": {
      "account": "0x907089fC3966f52dB446345451Ad9aE3B164D94c"
    },
    "url": "https://lb.drpc.org/optimism-sepolia/",
    "chainid": 11155420,
    "contractAddress": "0xB9467B24117FD79D56F396ADC3cCDB695D905ae4"
  },
  "outputs": [
    {
      "name": "balance",
      "value": "response.0",
      "export": true
    }
  ]
}
```

#### Field-by-field Explanation

* **`name`**
  * Step identifier = `"EVM-data-fetcher"`.
  * Labels this as the on-chain query node.
* **`image`**
  * Executor container: **EVM Read executor**.
  * Specialized runtime that can encode calls, query RPC endpoints, and decode results.
* **`attestor`**
  * IPFS link to the attestation config.
  * Ensures this step’s execution is cryptographically verifiable.
* **`next`**
  * Workflow link → next step is `"construct-evm"` (likely assembling a transaction).

***

**`config` (call definition)**

* **`function_signature`**: `"balanceOf(address)"`
  * The ABI function to call on the smart contract.
  * Standard ERC-20 balance check.
* **`input_parameters`**:
  * Defines the inputs schema — here:
    * `account` (type: `address`).
* **`output_parameters`**:
  * Defines the expected return values — here:
    * `balance` (type: `uint256`).

***

**`inputs` (runtime values)**

* **`value`**:
  * Passes the actual arguments for the call.
  * `"account"` = `0x9070...D94c`.
* **`url`**:
  * RPC endpoint to query (Optimism Sepolia via DRPC load balancer).
* **`chainid`**:
  * Numeric chain ID = `11155420` (Optimism Sepolia).
* **`contractAddress`**:
  * The contract instance being queried (`0xB9467...5ae4`).

***

**`outputs` (exported result)**

* Defines what values are extracted from the RPC response.
* **`value`: `"response.0"`**
  * Means: take the first returned value from the call (the `balance`).
* **`name`: `"balance"`**
  * Store it under this variable name.
* **`export: true`**
  * Makes it available to subsequent workflow steps (e.g., `construct-evm`).

***

#### 2.3. EVM Construct

Encodes raw workflow data into ABI-compliant **calldata**. This represents the response expected by your target smart contract.

* Takes workflow results as inputs.
* Outputs a `bytes` payload ready for target contract consumption.

**Example:**

<pre class="language-javascript"><code class="lang-javascript"><a data-footnote-ref href="#user-content-fn-1">// PART 1: SMART CONTRACT</a>

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./TargetBase.sol"; // Import base contract that provides AuthData struct + requireAuth modifier

contract TelemetryContract is TargetBase {

    // Expected response struct from the KRNL Node 
    // Fields must be in alphabetic order (to match encoding/decoding consistency)
    struct ExpectedResponse {
        string cpu_usage_percent;   // Telemetry: CPU usage
        string mem_usage_percent;   // Telemetry: Memory usage
    }
    
    // Target Function Signature (called by workflows after KRNL attestation)
    function submitTelemetry(AuthData calldata authData) 
        external 
        requireAuth(authData) // Ensures KRNL attestation &#x26; signature are valid
    {
        // Decode the KRNL response (AuthData.result is a raw ABI-encoded payload)
        ExpectedResponse memory krnlResponse = abi.decode(
            authData.result, // Workflow-encoded calldata
            (ExpectedResponse) // Decode into ExpectedResponse struct
        );
        
        // TODO: Application-specific logic goes here
        // e.g. store telemetry, trigger alerts, reward nodes, etc.
        ....
        ....
    }
}

</code></pre>

<pre class="language-json"><code class="lang-json"><a data-footnote-ref href="#user-content-fn-1">// PART 2: KRNL DSL</a>

{
  "name": "construct-evm", // Step name: encode telemetry into ABI-compliant calldata
  "image": "ghcr.io/krnl-labs/executor-encoder-evm@sha256:...", // Executor image for EVM ABI encoding
  "attestor": "https://public.mypinata.cloud/ipfs/.../attestor.json", // Attestor verifying correct encoding
  "next": "prepare-authdata", // Next system step in pipeline (adds cryptographic proofs)

  "config": {
    "parameters": [
      {
        "name": "telemetry",   // Top-level tuple name
        "type": "tuple",       // Encoded as Solidity struct
        "components": [        // Must align with ExpectedResponse struct in Solidity
          {
            "name": "cpuUsagePercent", // Matches struct field
            "type": "string"
          },
          {
            "name": "memUsagePercent", // Matches struct field
            "type": "string"
          }
        ]
      }
    ]
  },

  "inputs": {
    "value": {
      "telemetry": {
        // Internal references pull results from earlier workflow steps
        "cpuUsagePercent": "${workflow_step_1.result}", 
        "memUsagePercent": "${workflow_step_2.result}"
      }
    }
  },

  "outputs": [
    {
      "name": "result",   // Encoded ABI payload
      "value": "result",  // Standard output from encoder
      "export": true      // Make available to next step (prepare-authdata)
    }
  ]
}

</code></pre>

{% hint style="warning" %} <mark style="color:blue;">${workflow\_step\_1.result}</mark> and <mark style="color:blue;">${workflow\_step\_2.result}</mark> represent internal referencing within the DSL steps, where every step can reference a value from any of its previous steps in the format <mark style="color:blue;">`${`</mark><mark style="color:red;">`<name_of_the_step>`</mark>`.`<mark style="color:red;">`<name_of_the_output_field>`</mark><mark style="color:blue;">`}`</mark>
{% endhint %}

### Best Practices

* **Keep `authData_result` separate from extra parameters**
  * Protocol-level info (`nonce`, `expiry`, `signature`) → `authData_result`.
  * dApp-specific parameters → `parameters` array.
* **Explicit function signature**
  * Include full ABI signature in `target.function` for clarity.
  * Example:

    ```json
    "function": "purchaseTokens((uint256,uint256,bytes32,(bytes32,bytes,bytes)[],bytes,bool,bytes),uint256,address)"
    ```
* **Use environment variables**
  * Sensitive info like contract addresses, RPC URLs → `${ENV.*}` or `${_SECRETS.*}`.
  * Example:

    ```json
    "contract": "${ENV.TARGET_CONTRACT}"
    ```
* **Include replay & intent protection**
  * Always provide `intent.id`, `intent.signature`, `intent.deadline`.
  * Prevents replay attacks across chains or repeated execution.
* **Explicit data binding**
  * Outputs from previous steps → referenced using `${step-name.output}`.
  * Avoid implicit assumptions; makes workflows auditable.
* **Validation in DSL**
  * Simple type checks (`string`, `uint256`, `address`) in the workflow before contract call.
  * Helps catch issues off-chain before execution.

### What's next?

{% content-ref url="/pages/Rb93ZSknjGVjZr4bPDKl" %}
[KRNL Node](/core-concepts/krnl-node)
{% endcontent-ref %}

[^1]:


# KRNL Node

### Introduction

The KRNL Node is the heart of the KRNL Protocol—a decentralized orchestration engine that enables cryptographically verifiable workflows bridging Web2 services, blockchain interactions, and AI agents. Built as a non-invasive extension to go-ethereum (Geth), it allows developers to execute secure off-chain computations without compromising Ethereum’s consensus or relying on trusted third parties.

Whether you're building a DeFi yield optimizer, a compliance tool for real-world assets, or an AI-driven dApp, the KRNL Node handles complex workflows with end-to-end cryptographic proof, ensuring smart contracts can trust off-chain data as if it were on-chain.

{% hint style="success" %}

> **New to development? No worries, here are some of the terms to keep in mind while reading this page:**
>
> * ***Workflow/DSL***: A plan with tasks, like a recipe.
> * ***Sandbox/gVisor***: A safe isolated space where tasks run within a controlled environment.
> * ***Proof***: A digital stamp showing the task was done right. This stamp is created using a key only known to the one requesting the execution and one executing it
> * ***Geth***: It's a software which let's you run the Ethreum blockchain on your system
> * ***Executor:*** Open-source, community-audited code that runs a workflow step like calling an API or calling the balanceOf() on a contract.
> * ***Attestor*****:** Developer-controlled component that signs and verifies execution like a check if things are good to go
> * ***Bundler/Relayer:*** Think of it as parcel delivery system which deliver your parcel (KRNL response) to the recipient (Target Smart Contract) where a may or may not paymaster pays for the cost of the delivery (Gas fees)
>   {% endhint %}

### How it works

The KRNL-Node works as follow on a high level:

1. **Receives** a workflow request (via KRNL SDK or Smart Contract Account).
2. **Parses** the workflow DSL into a Directed Acyclic Graph (DAG).
3. **Executes** each step in an isolated gVisor sandbox.
4. **Signs** all network traffic (HTTP/HTTPS, DNS) for full attestation.
5. **Generates** a cryptographic proof using ephemeral keys.
6. **Bundles** results into a UserOp for on-chain execution via a relayer.

### Architecture Overview

The KRNL Node extends Geth without modifying its core codebase, running workflow orchestration as parallel services. This "additive-only" design preserves 100% Ethereum Foundation compliance.

At its foundation:

* **Core Geth Integration**: The node leverages Geth's battle-tested Ethereum client for blockchain interactions.&#x20;
* **Workflow Engine**: Processes KRNL DSL-defined workflows as DAGs, where each step (or "kernel") is an isolated task like an HTTP request, EVM query, or AI inference.
* **Security Layer**: Uses gVisor for sandboxing, ephemeral keys for signing, and a novel executor-attestor separation model to ensure trustless execution.
* **Network Attestation**: Monitors and cryptographically signs all outbound/inbound traffic (HTTP/HTTPS, DNS), providing forensic-level transparency.

Here's a high-level diagram of the architecture:

```
KRNL Node
├── Workflow Orchestrator
│   ├── DAG Parser (from KRNL DSL)
│   ├── Step Scheduler
│   └── Input/Output Binding
├── gVisor Sandbox Manager
│   ├── Executor Loader (Open-Source, Community-Verified)
│   └── Attestor Loader (Closed-Source, Developer-Controlled)
└── Proof Generator
    ├── Ephemeral Key Derivation
    └── Network Interceptor (HTTP/HTTPS + DNS)
```

The node receives workflow requests executes them in isolated environments, attests to the results, and bundles outputs for on-chain delivery.

### Key Capabilities

The KRNL Node isn't just a runner—it's a verifiable execution platform. Here's what it enables:

1. **Workflow Orchestration as DAGs** execute multi-step logic defined in KRNL DSL. For example, a workflow might fetch telemetry from a Web2 API, read an EVM balance, encode results into calldata, and bundle it into an ERC-4337 UserOp.
   * **When to Use**: For complex automation like cross-chain yield farming or pre-transaction compliance checks.
   * **Example DSL Snippet**&#x20;

     ```json
     {
       "name": "fetch-telemetry",
       "type": "HTTP",
       "image": "ghcr.io/krnl-labs/executor-http@sha256:...",
       "attestor": "https://public.mypinata.cloud/ipfs/...",
       "inputs": {
         "url": "https://api.example.com/telemetry",
         "method": "GET"
       },
       "outputs": [{ "name": "data", "value": "response.body" }]
     }
     ```
2. **gVisor Sandbox Isolation** Each workflow step runs in a user-space kernel sandbox with syscall interception. This provides multi-dimensional isolation to prevent escapes or tampering.
3. **Executor & Attestor Management**
   * **Executors**: Community-reviewed, open-source containers for task logic. These are the doers which will go the do the task specified in the DSL workflow
   * **Attestors**: Developer-controlled for signing results and monitoring traffic.&#x20;
4. **Cryptographic Proof Generation** Every execution produces composable proofs using ephemeral keys (derived from master secrets + context). This prevents replays and binds proofs to specific workflows.
   * **Network Attestation**: Signs full HTTP/HTTPS requests/responses and DNS resolutions for transparency.
5. **Bundling & Relaying** Outputs are ABI-encoded, wrapped in AuthData structs, and bundled into UserOps for relayers (e.g., Pimlico). The node signs and sends these to external bundlers for on-chain execution.

In summary KRNL node is the heart of the KRNL protocol, which orchestrates the end-to-end flow in a decentralized architecture

### What's next?

{% content-ref url="/pages/P3sPXvk8Vlh9yWOkEkDe" %}
[Executors](/core-concepts/executors)
{% endcontent-ref %}


# Executors

### Introduction

Executors are the open-source, community-driven components that power the execution logic within the KRNL Protocol. They are the skilled workers who carry out tasks defined in your workflows, such as fetching data from a website, querying blockchain states, or running AI computations. Built for transparency and flexibility, executors are containerized, auditable, and deployed using reproducible builds, operating within the secure gVisor sandboxes of the KRNL Node.

### Key Features

* **Open-Source and Community-Reviewed**: Developed by the community with openly available source code for peer review to ensure correctness, interface compliance, and high code quality.
* **Containerized Execution**: Packaged as container images (e.g., ghcr.io/krnl-labs/executor-http\@sha256:...) for consistent deployment.
* **Task Versatility**: Support HTTP requests, EVM calls, and AI inference, adaptable to use cases like DeFi or compliance.
* **Reproducible Builds**: Identified by SHA256 hashes for verifiable integrity.

### Core Responsibilities

1. **Workflow Execution**
   * Runs individual **kernels** (workflow steps) inside a gVisor-based sandbox.
   * Executes API calls, blockchain interactions, AI inference, or arbitrary computation.
   * Supports conditional branching, loops, and decision-making logic in workflows.
2. **Isolation & Compliance**
   * Every executor runs in a **sandboxed environment** to contain faults or malicious behavior.
   * Enforces deterministic builds and container digest verification to prevent supply chain attacks.
3. **Standardized Interfaces**
   * Implements a consistent interface so any executor can plug into the KRNL workflow engine.
   * Ensures outputs can be consumed by attestors and verified by smart contracts.
4. **Community Contribution**
   * Executors are open-source and undergo peer review, security audits, and reproducible build verification.
   * Multiple independent builders can produce identical binaries, ensuring no hidden changes.

### How Executors Work

Invoked by the KRNL Node, executors execute workflow steps. Example DSL:

```
{
  "name": "fetch-telemetry",
  "type": "HTTP",
  "image": "ghcr.io/krnl-labs/executor-http@sha256:07ef35b261014304a0163502a7f1dec5395c5cac1fc381dc1f79b052389ab0d5",
  "inputs": {
    "url": "https://api.example.com/telemetry",
    "method": "GET"
  },
  "outputs": [
    {
      "name": "data",
      "value": "response.body",
      "export": true
    }
  ]
}
```

The executor loads the image, performs the task, and exports results within a sandbox.

### What's next?

{% content-ref url="/pages/f7hbTBN89RRNvYMPGI1U" %}
[Attestor](/core-concepts/attestor)
{% endcontent-ref %}


# Attestor

The **Attestor** is the cryptographic heart of the KRNL Protocol. While executors run workflow logic, the attestor ensures that every step is secure, verifiable, and policy-compliant. It acts as the developer’s private guardian, responsible for attesting to the integrity of execution and safeguarding master secrets, without ever becoming a centralized point of trust.

### Role in the Protocol

At a high level:

* **Executor** = runs the workflow logic (open-source, community-audited).
* **Attestor** = enforces trust boundaries and signs off on the results (developer-controlled, security-hardened).

***

### Core Responsibilities

1. **Cryptographic Signing**
   * Generates execution signatures using **ephemeral keys** derived from a master secret.
   * Guarantees that every workflow run is uniquely bound to its execution context, preventing replay or forgery.
   * Signs both raw execution outputs and the **network attestation hash**, producing end-to-end verifiable proofs.
2. **Network Monitoring**
   * Acts as a **transparent interceptor** for all network traffic (HTTP, HTTPS, DNS).
   * Detects tampering, MITM attempts, or injection by monitoring every request and response.
   * Produces cryptographically sealed logs that provide forensic-grade auditability.
3. **Secret Management**
   * Safely holds the developer’s master key material.
   * Derives one-time-use ephemeral keys per execution, minimizing exposure.
   * Optionally integrates with external **Remote Signers** or hardware-based Trusted Execution Environments (TEEs) for heightened security.
4. **Execution Environment Validation**
   * Verifies that executors run in correct, reproducibly built sandbox environments (e.g., gVisor containers).
   * Enforces policies on which executors are authorized and under what conditions.
   * Provides an auditable chain of custody for every workflow step.

{% hint style="info" %}
Every attestor is anchored by a **developer-controlled master key**.

* **Who generates it?** The dApp developer (or organization) creates the master key when setting up their attestor.
* **How is it used?**
  * Never directly for signing.
  * Instead, it serves as the cryptographic seed from which **ephemeral execution keys** are derived per workflow run.
* **Where is it stored?**
  * Typically compiled into the attestor binary with advanced protections against reverse engineering.
  * Optionally isolated in a **Remote Signer** or **TEE (Intel SGX, AMD SEV, ARM TrustZone)** for hardware-backed security.

This means the master key never leaves the attestor environment, never appears on-chain, and is never reused. It exists purely as a local root of trust, bound to the developer’s attestor deployment.
{% endhint %}

***

### Attestation Data Structures

The attestor doesn’t just sign results, it builds a **multi-layered proof system**:

* **Request Attestation:** Every outbound API call is logged with full method, endpoint, headers, payload, and a timestamp.
* **DNS Attestation:** All DNS queries and responses are cryptographically recorded, ensuring transparency at the lowest layer.
* **Response Attestation:** Each inbound response (status, headers, payload, TLS metadata) is bound to its request and signed.
* **Network Summary:** A cryptographic digest of the entire execution session, aggregating request/response patterns into a compact verifiable proof.

Together, these structures transform the “black box” of off-chain execution into a **glass box,** anyone can independently verify exactly what happened, when, and under which conditions.

***

### Security Model

* **Isolation:** Attestors run in isolated gVisor environments, with optional TEE deployment for hardware-backed guarantees.
* **Ephemeral Keying:** No key reuse, no persistent signing keys exposed; every run is cryptographically unique.
* **Developer Authority:** dApp developers own their attestor, meaning only they define the policies, whitelists, and trust boundaries.
* **Auditability:** The attestor’s signed outputs can be verified both **on-chain** (via standard signature recovery) and **off-chain** (via forensic inspection of attestation logs).

***

### Why It Matters

Traditional oracles or middleware rely on trust in third-party operators. The attestor eliminates that dependency by giving developers full control over verification. This unlocks:

* **Regulatory-grade compliance** – produce audit-ready reports of every API call and signature.
* **User confidence** – end users can see verifiable evidence, not just promises.
* **Security resilience** – even if an executor is compromised, the attestor prevents forged results from entering the workflow.

In short: **Executors compute, attestors prove.** This clear division of responsibility is what makes KRNL’s architecture uniquely trustworthy.

### What's next?

{% content-ref url="/pages/ONFRk1cDqMI1BYwjYfma" %}
[Vault](/core-concepts/vault)
{% endcontent-ref %}


# Vault

The **KRNL Vault** is the economic backbone of the protocol — the component that ensures workflows not only execute securely but also settle fairly. Executors may compute, attestors may prove, but the Vault handles the **money flows**: billing, fee collection, storage, and distribution.

By integrating with Ethereum standards like **EIP-7702** (delegated accounts) and **EIP-4337** (account abstraction), the Vault makes billing seamless, flexible, and fully automated. This ensures developers can focus on building while the protocol transparently handles value exchange.

### Role in the Protocol

* **Billing Engine** – Enforces payment flows for every workflow execution.
* **Fee Collector** – Captures protocol fees, gas fees, and service costs.
* **Distributor** – Routes funds to node operators, executor builders, kernel providers, and the protocol treasury.
* **Economic Guardian** – Prevents underpayment, double-spending, and ensures sustainability via transparent fee policies.

### Billing System with EIP-7702 + EIP-4337

The Vault leverages Ethereum’s most advanced account standards to handle payments:

#### **EIP-7702: Delegated Accounts**

* Lets an **EOA (Externally Owned Account)** delegate authority to a **Smart Contract Account (SCA)**.
* SCAs can sign and pay for workflow executions on behalf of the user.
* Supports **dual transactions**:
  1. The **workflow execution** itself.
  2. The **corresponding payment** into the Vault.
* Benefits:
  * Users don’t have to manually juggle fee payments.
  * Developers can enforce billing policies at the account level.

#### **EIP-4337: Account Abstraction**

* SCAs function as **programmable wallets**, enabling meta-transactions.
* Supports:
  * **Bundlers**, who relay batched transactions into the chain.
  * **Paymasters**, who can sponsor gas fees for users.
* Benefits:
  * Smooth UX: users don’t need ETH for gas.
  * Flexible billing: fees can be paid in stablecoins or other ERC-20s.
  * Gas optimization: multiple workflow steps can be batched into a single transaction.

Together, **7702 + 4337 turn KRNL billing into a self-contained system**: users delegate, SCAs enforce, Vault collects, and everything is cryptographically verifiable.

### Fee Structure

Every workflow execution incurs three categories of cost:

**Total Execution Cost = Platform Base Fee + External Service Costs + Gas Costs**

1. **Platform Base Fee**
   * Paid to the Vault for using KRNL infrastructure.
   * Funds node operators, executor builders, and protocol maintenance.
2. **External Service Costs**
   * APIs, off-chain data providers, and kernel services each have their own costs.
   * Automatically collected and routed to the correct provider.
   * Enables long-tail API providers to monetize directly within KRNL.
3. **Gas Costs**
   * Native Ethereum gas fees for on-chain verification and settlement.
   * Can be sponsored by developers (via Paymasters) or paid directly by users.

### Distribution of Fees

The Vault executes **automated, rules-based distribution**:

* **Node Operators** – Paid for running KRNL-Nodes that execute workflows and provide computational resources.
* **Executor Builders** – Receive rewards when their executors are used inside workflows.
* **Protocol Treasury** – Funds governance, ecosystem incentives, audits, and long-term development.

This ensures that every contributor to the ecosystem is rewarded **fairly and transparently**.


# Target Base Contract

### Overview

`TargetBase` is a foundational contract that provides a **signature-based authorization system** for smart contracts. It enforces strict access controls by combining **cryptographic signatures**, **smart account validation**, and **replay protection** into a single, reusable module.

Application developers can extend `TargetBase` to build specialized contracts (e.g., DeFi protocols, marketplaces, or tokenized asset platforms) while inheriting all of its **security guarantees**.

***

### Core Features

#### 1. Master Key Authorization

* A **trusted master key** signs all authorizations.
* The master key can be rotated by the **owner** or a **recovery key** for security.
* This ensures that only signatures from the current master key are valid.

#### 2. Smart Account Enforcement

* Only approved **DelegatedAccount** implementations can call protected functions.
* Enforced using `extcodehash` checks:
  * EOAs are **rejected** (no direct access).
  * Contracts with incorrect or empty bytecode are **rejected**.
  * Only contracts with the registered `DelegatedAccount` code hash are accepted.

#### 3. Replay Protection

* **Nonces**: Each sender has a sequential nonce. Must match `authData.nonce`.
* **Authorization Hash Tracking**: Each authorization (signature + data) is marked as used after execution.
* This prevents signature reuse across different calls or chains.

#### 4. Temporal Validation

* Authorizations include an **expiry timestamp**.
* Prevents attackers from replaying old signatures long after they were valid.

#### 5. Emergency Recovery

* **Recovery Key**: Dedicated address that can update the master key.
* **Nonce Reset**: Owner can reset user nonces if accounts get stuck.

***

### Authorization Workflow

#### AuthData

Every protected function must receive an `AuthData` struct as its **first argument**.\
It contains:

* `nonce` → Sequential replay protection.
* `expiry` → Timestamp after which the auth is invalid.
* `id` → Execution hash for the overall operation.
* `executions` → Array of execution steps for auditability.
* `result` → ABI-encoded final result or function parameters.
* `sponsorExecutionFee` → Indicates if fees are sponsored.
* `signature` → ECDSA signature from the master key.

#### Authorization Verification (requireAuth)

When a protected function is called:

1. **Implementation Check** → Caller must be approved DelegatedAccount.
2. **Nonce Check** → `authData.nonce == nonces[msg.sender]`.
3. **Expiry Check** → `block.timestamp <= authData.expiry`.
4. **Hash Generation** → Unique hash created from sender, nonce, expiry, result, selector.
5. **Replay Check** → Hash must not already exist in `usedAuthorizations`.
6. **Signature Check** → Recovered signer must match `masterKey`.
7. **State Update** → Nonce incremented, hash marked used.
8. **Event Emitted** → `AuthorizationVerified`.

***

### Extending TargetBase

Developers extend `TargetBase` by **inheriting it in their own contracts** and applying `requireAuth` to sensitive functions.

#### Example: RealEstateInvestment (Without extra parameters)

The `RealEstateInvestment` contract extends `TargetBase` to implement **fractional real estate ownership**.

Key extensions:

* Inherits both `TargetBase` (for authorization) and `ERC20` (for fractional tokens).
* Defines **domain-specific structs** like `PropertyInfo`, `PropertyAnalysisResponse`, and `InvestmentRecord`.
* Implements **business logic**:
  * `submitPropertyAnalysis` → Requires a signed analysis result.
  * `purchaseTokens` → Requires signed authorization for each investment.
* All core operations use `requireAuth(authData)` to enforce:
  * Signature validation.
  * DelegatedAccount-only access.
  * Replay protection.

```solidity
function submitPropertyAnalysis(AuthData calldata authData)
    external
    requireAuth(authData)
{
    // Decode AI analysis results
    PropertyAnalysisResponse memory analysis = abi.decode(authData.result, (PropertyAnalysisResponse));

    // Apply domain-specific validation rules
    if (analysis.confidence < MIN_CONFIDENCE) revert ConfidenceTooLow();
    if (keccak256(bytes(analysis.recommendation)) != keccak256("INVEST")) revert InvalidRecommendation();

    // Update property state & emit events
    property.totalValue = analysis.propertyValue;
    property.isActive = true;
    emit PropertyAnalyzed(...);
}
```

**Example 2: TokenSale (With extra parameters)**

```solidity

contract TokenSale {
    IERC20 public token;

    constructor(address _token) {
        token = IERC20(_token);
    }

    function purchaseTokens(
        AuthData calldata authData,   // comes from krnl "authData_result"
        uint256 amount                // comes from krnl "parameters"
    ) external {
        // ✅ 1. Verify the AuthData
        require(verifyAuthData(authData), "Invalid AuthData");

        // ✅ 2. Process token purchase
        require(amount > 0, "Zero amount");
        require(token.balanceOf(address(this)) >= amount, "Insufficient liquidity");

        token.transfer(msg.sender, amount);
    }
}

```

From the DSL we wrote earlier in [/pages/bh3glhS6WS6V6ZI7taKO#id-2.-target-contract-details](https://docs.krnl.xyz/smart-contract/pages/bh3glhS6WS6V6ZI7taKO#id-2.-target-contract-details "mention") this is how the structure will look like with the extra parameter:

```json
"function": "purchaseTokens((uint256,uint256,bytes32,(bytes32,bytes,bytes)[],bytes,bool,bytes),uint256)",
"authData_result": "${construct-authdata-evm.result}",
"parameters": [
  {
    "name": "amount",
    "type": "uint256",
    "value": "1000000000000000000"
  }
]
```

* `authData_result` → fills the **first argument** (`AuthData calldata authData`)
* `parameters` → supplies **extra arguments** (`uint256 amount`)

#### Benefits of Inheriting TargetBase

* **Security out of the box**: No need to reimplement replay protection or signature verification.
* **Standardized authorization**: Uniform way to authorize actions across contracts.
* **Extensible**: Each new contract only needs to define its domain-specific logic.
* **Composable**: Multiple `TargetBase`-derived contracts can interoperate securely.

### Best Practices

* **AuthData as the first parameter**
  * All functions requiring authorization must have `AuthData calldata authData` first.
  * Ensures deterministic ABI encoding.
* **Validate extra parameters**
  * Never trust DSL inputs blindly.
  * Use `require` or custom errors for range, zero addresses, or business logic constraints.
  * Example:

    ```solidity
    require(amount > 0, "Amount must be positive");
    require(recipient != address(0), "Invalid recipient");
    ```
* **Use events for auditability**
  * Emit events for:
    * Authorization verified
    * Master key update
    * Property or token transactions
  * Enables off-chain monitoring & workflow debugging.
* **Fail fast and explicitly**
  * Custom errors instead of generic `require` messages save gas and improve readability.


# Usage

### What You're Building <a href="#what-youre-building" id="what-youre-building"></a>

Think of `TargetBase` as your smart contract's security bouncer. It's a battle-tested foundation that gives you signature-based authorization, smart account enforcement, and all the protection you need for EIP-7702 delegated accounts—without having to reinvent the wheel.

This guide walks you through extending TargetBase to build your own secure contracts. We'll use the RealEstateInvestment contract as our real-world example because, well, nothing teaches better than actual code.

### What TargetBase Does For You <a href="#what-targetbase-does-for-you" id="what-targetbase-does-for-you"></a>

Here's what you get out of the box:

* **Signature-based authorization** – Only calls signed by your master key get through
* **Smart account validation** – Enforces EIP-7702 compliance (no random EOAs sneaking in)
* **Replay attack protection** – Nonces and hash tracking ensure each authorization works exactly once
* **Time-bound authorizations** – Set expiry timestamps so old signatures can't haunt you
* **Emergency recovery** – Because sometimes you need a backup plan
* **Multi-source execution chains** – Perfect for when you need to aggregate data from multiple sources

Think of it as a security framework that handles all the hard parts so you can focus on your business logic.

### The Core Building Blocks <a href="#the-core-building-blocks" id="the-core-building-blocks"></a>

#### AuthData <a href="#authdata-your-authorization-package" id="authdata-your-authorization-package"></a>

Every protected function needs one of these. It's like a VIP pass that proves the caller has permission:

```solidity
struct AuthData {
    uint256 nonce;              // Prevents replay attacks
    uint256 expiry;             // "This signature expires on..."
    bytes32 id;                 // Unique execution identifier
    Execution[] executions;     // For multi-step operations
    bytes result;               // The final data or parameters
    bool sponsorExecutionFee;   // Who pays the gas?
    bytes signature;            // The master key's signature
}
```

#### The Authorization Players <a href="#the-authorization-players" id="the-authorization-players"></a>

* **Master Key** – The VIP who signs everything. This is your authorization authority.
* **Recovery Key** – Your emergency contact. Can rotate the master key if things go wrong.
* **Owner** – The admin. Controls contract settings and upgrades.
* **DelegatedAccount** – The only type of account allowed to call your protected functions (EIP-7702 smart accounts only)

### How to Extend TargetBase (The Three-Step Implementation) <a href="#how-to-extend-targetbase-the-three-step-recipe" id="how-to-extend-targetbase-the-three-step-recipe"></a>

#### Step 1: Set Up Your Contract <a href="#step-1-set-up-your-contract" id="step-1-set-up-your-contract"></a>

Start by inheriting from TargetBase. You can mix in other contracts too—we're using ERC20 in our real estate example:

```solidity
contract YourContract is TargetBase, [OtherContracts] {
    constructor(
        address _authKey,
        address _recoveryKey,
        address _owner,
        address _delegatedAccountImpl,
        // your additional parameters
    ) TargetBase(_authKey, _recoveryKey, _owner, _delegatedAccountImpl) {
        // your initialization magic happens here
    }
}
```

{% hint style="info" %}
**Pro tip**: Pass those four addresses to TargetBase first, then handle your own initialization. Order matters!
{% endhint %}

#### Step 2: Define Your Data Structures <a href="#step-2-protect-your-functions" id="step-2-protect-your-functions"></a>

Before you do anything else, define the structs that will carry your data which is basically the result your are expected from the KRNL node as a part of the workflow execution. These are what you'll encode/decode in `authData.result`:

```solidity
// What your protected function will actually use
struct YourResponseStruct {
    uint256 someField;           // 0-100
    uint256 expectedAnnualYield;  // In basis points
    string investmentGrade;       // "A+", "A", "B+", etc.
    uint256 propertyValue;        // In USD
    string recommendation;        // "INVEST", "HOLD", or "PASS"
}
```

**Important**: The fields in your struct should be **alphabetically ordered** when you're working with external data sources. This ensures consistent encoding/decoding across different systems.

#### Step 2: Protect Your Functions <a href="#step-2-protect-your-functions" id="step-2-protect-your-functions"></a>

Now when you integrate KRNL to your smart contract, you use `requireAuth(authData)` modifier to do the basic validation check like your nonce, expiry, etc and make `AuthData` your first parameter:

```solidity
function yourProtectedFunction(
    AuthData calldata authData,  // Always first!
    // then your actual business parameters
) external requireAuth(authData) {
    // By the time this runs, TargetBase has already verified:
    // ✓ The caller is a legit EIP-7702 account
    // ✓ The signature is valid
    // ✓ The nonce is correct
    // ✓ It hasn't expired
    // ✓ It hasn't been used before
    
    // Your business logic here
}
```

#### Step 3: Decode Your Data (When You Need It) <a href="#step-3-decode-your-data-when-you-need-it" id="step-3-decode-your-data-when-you-need-it"></a>

If you're working with multi-source execution chains or need to extract data from the authorization:

```solidity
function submitData(AuthData calldata authData) 
    external requireAuth(authData) 
{
    // Unpack the final result from your execution chain
    YourResponseStruct memory response = 
        abi.decode(authData.result, (YourResponseStruct));
    
    // Now validate it
    require(response.someField > threshold, "Not good enough!");
    
    // And use it
    // ... your business logic
}
```

### Real-World Example: Tokenizing Real Estate <a href="#real-world-example-tokenizing-real-estate" id="real-world-example-tokenizing-real-estate"></a>

Let's look at how the RealEstateInvestment contract does it. This contract lets people buy fractional ownership of properties using USDC. It needs TargetBase because property analysis data comes from multiple sources (Zillow, Census data, AI analysis) and needs to be verified before allowing investments.

```solidity
contract RealEstateInvestment is TargetBase, ERC20 {

    // Step 1: Define the response struct for property analysis
    struct PropertyAnalysisResponse {
        uint256 confidence;           // Fields alphabetically ordered
        uint256 expectedAnnualYield;
        string investmentGrade;
        uint256 propertyValue;
        string recommendation;
    }
    
    // Step 2: Set up the constructor
    // Notice we're mixing TargetBase with ERC20—totally fine!
    constructor(
        address _authKey,
        address _recoveryKey, 
        address _owner,
        address _delegatedAccountImpl,
        address _usdcToken,
        string memory _propertyAddress
    ) TargetBase(_authKey, _recoveryKey, _owner, _delegatedAccountImpl) 
      ERC20("Real Estate Property Token", "REPT") {
        // Initialize our business-specific stuff
        usdc = IERC20(_usdcToken);
        property.propertyAddress = _propertyAddress;
    }

    // Step 3: Create a protected function that handles multi-source data
    function submitPropertyAnalysis(AuthData calldata authData) 
        external requireAuth(authData) 
    {
        // This data came from a chain of executions:
        // Zillow API → Census data → AI analysis
        // We decode the final aggregated result
        PropertyAnalysisResponse memory analysisResponse = 
            abi.decode(authData.result, (PropertyAnalysisResponse));
        
        // Always validate before trusting!
        if (analysisResponse.confidence < MIN_CONFIDENCE) {
            revert ConfidenceTooLow();
        }
        
        // Now we can safely use it
        property.totalValue = analysisResponse.propertyValue;
        property.investmentGrade = analysisResponse.investmentGrade;
        
        // Pro move: Emit events with authData context for audit trails
        emit PropertyAnalyzed(
            msg.sender,
            authData.nonce,
            authData.id,
            property.propertyAddress,
            analysisResponse.propertyValue,
            // ... more event params
        );
    }
    
    // Step 4: Another Protected function with business parameters
    function purchaseTokens(
        AuthData calldata authData,  // Auth first
        uint256 usdcAmount           // Then your params
    ) external requireAuth(authData) {
        // Authorization already verified, just do your thing
        require(usdcAmount >= MIN_INVESTMENT, "Need at least 1000 USDC");
        
        // Calculate tokens, transfer USDC, mint tokens, etc.
        // ... your business logic
    }
}
```

**What's happening here?**

* The constructor handles both TargetBase and ERC20 initialization
* `submitPropertyAnalysis` decodes complex multi-source data and validates it
* `purchaseTokens` combines authorization with business parameters
* Events include `authData.nonce` and `authData.id` for complete traceability

### Things to Avoid <a href="#the-rules-of-the-game" id="the-rules-of-the-game"></a>

#### When Setting Up Your Constructor <a href="#when-setting-up-your-constructor" id="when-setting-up-your-constructor"></a>

* **No zero addresses** – TargetBase will reject them. Every address parameter matters.
* **DelegatedAccount must be real** – It needs to be an actual deployed contract with code. No empty addresses or EOAs.
* **Order matters** – Pass the four TargetBase parameters first, in order: `_authKey, _recoveryKey, _owner, _delegatedAccountImpl`

#### When Writing Protected Functions <a href="#when-writing-protected-functions" id="when-writing-protected-functions"></a>

* **AuthData always comes first** – It's not just convention, it's how the pattern works. `function myFunc(AuthData calldata authData, ...)`
* **Use the modifier** – Don't forget `requireAuth(authData)`. That's where all the magic happens.
* **Include context in events** – Always emit `authData.nonce` and `authData.id` in your events. Future you will thank present you when debugging!

#### The Security Guarantees <a href="#the-security-guarantees" id="the-security-guarantees"></a>

Here's what TargetBase enforces automatically:

* **EIP-7702 only** – No EOAs allowed. Only properly delegated smart accounts get through.
* **Sequential nonces** – Can't skip ahead or go backward. If Alice is on nonce 5, her next call must use nonce 5, then 6, then 7...
* **Expiry matters** – That timestamp isn't just for show. Expired = rejected.
* **One-time use** – Each authorization is like a ticket. Once it's used, it's burned. No replays, no exceptions.

### Best Practices <a href="#smart-moves-best-practices" id="smart-moves-best-practices"></a>

**Emit meaningful events**\
Include `authData.nonce` and `authData.id` in every event. Six months from now when you're debugging a production issue, you'll want that audit trail. Trust me.

**Validate everything**\
Just because data made it through authorization doesn't mean it's correct. Always validate decoded results before using them. Check ranges, verify checksums, enforce business rules.

**Use custom errors**\
TargetBase uses them for a reason—they're gas-efficient and more descriptive. `revert InsufficientFunds()` beats `require(balance > 0, "Insufficient funds")` every time.

**Protect against reentrancy**\
TargetBase includes `nonReentrant` protection. Use it on any function that changes state or moves value around.

**Keep view functions simple**\
Don't use `requireAuth` on view or pure functions. They don't change state, so they don't need authorization. Save the gas.

**Use Ownable for admin stuff**\
TargetBase inherits from Ownable, so you get `onlyOwner` for free. Use it for administrative functions that shouldn't go through the auth flow.

### Three Common Patterns You Can Use <a href="#three-common-patterns-youll-use" id="three-common-patterns-youll-use"></a>

#### Pattern 1: Simple Authorization (Just Verify, No Data) <a href="#pattern-1-simple-authorization-just-verify-no-data" id="pattern-1-simple-authorization-just-verify-no-data"></a>

```solidity
function simpleAction(AuthData calldata authData) 
    external requireAuth(authData) 
{
    // No data decoding needed
    // Just verify the caller is authorized and execute
    someState = true;
}
```

#### Pattern 2: Multi-Source Data Pipeline <a href="#pattern-2-multi-source-data-pipeline" id="pattern-2-multi-source-data-pipeline"></a>

```solidity
function complexAction(AuthData calldata authData) 
    external requireAuth(authData) 
{
    // Decode the aggregated result from your execution chain
    FinalResult memory result = abi.decode(authData.result, (FinalResult));
    
    // Validate it
    require(result.confidence >= MIN_CONFIDENCE, "Low confidence");
    
    // Use it
    processResult(result);
}
```

#### Pattern 3: Authorization + Business Parameters <a href="#pattern-3-authorization--business-parameters" id="pattern-3-authorization--business-parameters"></a>

```solidity
function businessAction(
    AuthData calldata authData,
    uint256 amount,
    address recipient
) external requireAuth(authData) {
    // Combine authorization with your own parameters
    // Auth is verified, now validate your business logic
    require(amount > 0, "Amount must be positive");
    require(recipient != address(0), "Invalid recipient");
    
    // Do your thing
    transfer(recipient, amount);
}
```

**When to use each:**

* **Pattern 1**: Permission changes, state toggles, simple actions
* **Pattern 2**: External data validation, multi-API aggregation, complex analysis
* **Pattern 3**: Most common! Authorized actions with user-provided parameters

<br>


# FAQ

<details>

<summary><strong>Why signatures from EOAs are rejected even if they are valid?</strong></summary>

TargetBase is built for **smart account–based execution**, not direct EOA calls. All protected functions must be executed **via a DelegatedAccount** that has been pre-approved. This creates an enforcement layer where **EOAs cannot bypass authorization logic**.

</details>

<details>

<summary><strong>What happens if someone tries to reuse the same signed authorization twice?</strong></summary>

They can’t. TargetBase prevents this via **dual-layer replay protection**:

1. **Nonce Check** — must match `nonces[msg.sender]`
2. **Authorization Hash Tracking** — once a signature hash is used, it’s permanently recorded and rejected on future calls

This means even if an attacker copies calldata across chains, it still won’t execute.

</details>

<details>

<summary><strong>Can I rotate the master key without breaking existing signatures?</strong></summary>

Yes. When rotating the master key, all future authorizations must be signed with the new key, but **already-executed signatures remain final**. Pending signatures signed by the old key become invalid, this is intentional for security. This means that you also need to create a new attestor image which includes the private key of the latest master key.

</details>

<details>

<summary><strong>Does the contract owner have god mode? Can they bypass requireAuth?</strong></summary>

No. TargetBase does **not** implicitly grant owner privileges over normal functionality. The owner **only controls**:

* Master key rotation
* Recovery key update
* Emergency nonce reset

Actual business logic must still pass through `requireAuth`.

</details>


# KRNL SDK Installation

### Prerequisites

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

Integrating the KRNL SDK into your dApp enhances the capabilities of transactions, through accessing the KRNL Operating System, kOS.

***

### Installing KRNL SDK

Install KRNL SDK via your package manager.

{% tabs %}
{% tab title="npm" %}

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

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @krnl-dev/sdk-react-7702
```

{% endtab %}

{% tab title="bun" %}

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

{% endtab %}

{% tab title="pnpm" %}

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

{% endtab %}
{% endtabs %}

### What's next?

{% content-ref url="/pages/6EXCZE4hNYlKfkW9LIID" %}
[Usage](/krnl-sdk/usage)
{% endcontent-ref %}


# 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
```


# Overview

<figure><img src="/files/MVe7qUsgQdwUvDc1UVPi" alt=""><figcaption></figcaption></figure>

KRNL Studio is a visual builder for developers who are tired of wiring together APIs, smart contracts, and AI services by hand. Instead of writing glue code for every new feature, you drag blocks, connect them, and run the whole thing like a flowchart.

**Try it live:** [https://studio.krnl.xyz](https://studio.krnl.xyz?utm_source=chatgpt.com)

You can think of it like Zapier or GitHub Actions, but built with blockchain and AI in mind from day one. Every part of your workflow runs in a secure execution environment that generates cryptographic proof, so you are not just assuming it worked — you can verify it.

This is not a toy for demos. It is designed for real production workflows:

* Build complex blockchain logic without drowning in boilerplate
* Drop in AI models as decision points anywhere in the flow
* Run everything inside isolated, attestable containers
* Deploy workflows instantly with one command

If you have ever written a script that says “fetch data → process it → sign → send transaction”, KRNL Studio is that process turned into a visual system you can reuse, share, and evolve.

Stop stitching infrastructure together. Start building actual products.

### How the DSL Connects to the KRNL Node

KRNL Studio is not just a visual editor. Everything you build on the canvas is compiled into a DSL, a structured workflow definition that the KRNL Node understands and executes.

Here is the full loop:

#### 1. Visual Workflow → DSL

When you connect nodes in the Studio, the system generates a workflow definition in KRNL’s domain-specific language. It captures:

* The sequence of tasks
* What container or execution environment each one needs
* What inputs and outputs are passed between them

No visuals are stored. The KRNL Node only sees the DSL as a set of instructions to follow while your workflow is being executed.

#### 2. DSL → KRNL Node

That DSL is sent to a KRNL Node, which acts as a secure off-chain execution engine. Its job is not just to run the workflow but to **prove** that it ran correctly.

The node:

* Parses the DSL into an execution graph
* Spins up isolated environments for each task (gVisor sandboxes)
* Restricts outgoing network traffic and signs every call
* Generates cryptographic proof for each step

#### 3. Node → Blockchain

Once execution is complete, the node packages the result into a signed structure such as `AuthData` or a User Operation. That proof can then be sent to a smart contract or a bundler.

The smart contract does not need to trust the node. It verifies the proof and accepts or rejects the action based on it.


# How to Construct a Workflow

{% embed url="<https://youtu.be/YajjCaKQOD4>" %}

This guide will walk you through how to construct a **KRNL Studio workflow** that fetches real estate data, analyzes it with AI, and encodes the results for on-chain submission.

We’ll break it down step by step so you understand what each part of the workflow does, and then show you the final JSON config you’ll use.

Again, this is just a demo, and this might defer depending on the problem you are trying to solve with using KRNL in dApp

**⏱ Time to complete**: \~15 minutes

### What You’ll Build

A workflow that:

1. Fetches property data from Zillow (mocked API in this example)
2. Fetches market estimates (value, rent, etc.)
3. Runs an AI property analysis (GPT-based)
4. Encodes the results into an EVM transaction
5. Prepares it for blockchain submission with cryptographic proof

### Step 1: Launch KRNL Studio

Open <https://studio.krnl.xyz> in your browser. You should see the KRNL Studio interface.

### Step 2: Set Up Your Workflow Foundation

#### Create a New Workflow

1. Click **"Start Building"**
2. Name your workflow: `Real Estate Investment Analyzer`
3. Select `Sepolia Testnet` as the Blockchain Network
4. Paste the target contract address (deployed in [Local Dev](/getting-started/getting-started-with-krnl/local-dev))
5. Next you will have option to fetch your ABI automatically from Etherscan or manually input the ABI
6. Select `submitPropertyAnalysis((uint256,uint256,bytes32,(bytes32,bytes,bytes)[],bytes,bool,bytes))` as the function signature
7. Finally you will have a canvas with pre-filled nodes

<figure><img src="/files/XVQTGG0vQ8W3Qv1qocqX" alt=""><figcaption></figcaption></figure>

The canvas will display the default nodes:

* **Basic Info**: Workflow metadata and configuration
* **dApp Config**: Target contract settings
* **Workflow Steps**: To add custom workflow steps

#### Configure Basic Information

1. Hover over **Basic Info** node and click on the settings
2. You might see all the fields already filled in
3. After verifying the fields, let's move on to the next node

#### Configure dApp Information

1. Hover over the **dApp Config** node and click on the settings
2. You might see all the fields already filled in
3. Again after verifying the fields, let's move on to the next node

### Step 3: Add Workflow Steps

#### Add a Property Data Fetcher Step

<figure><img src="/files/sBYlnGwwhWCKEEBdtNTG" alt=""><figcaption></figcaption></figure>

1. Click on Add Node and drag and drop the **HTTP GET under HTTP** step into the workflows
2. Hover over the step and click on settings
3. First, let's name it `property-data-fetcher` (This name could be anything you like)

#### Configure the API Request

* In the settings page, there is a section called **Inputs,** under this configure your API request
* URL: `https://poc.platform.lat/zillow/webservice/GetSearchResults.htm?zws-id=demo-api-key&address=1234-Maple-Street&citystatezip=Austin,TX`
* Method: `GET`

#### Set Outputs

* `zpid` → `response.body.searchResults.zpid`
* `address.street` → `response.body.searchResults.address.street`
* `address.city` → `response.body.searchResults.address.city`
* `address.state` → `response.body.searchResults.address.state`
* `address.zipcode` → `response.body.searchResults.address.zipcode`

Close the **Settings**.

#### Add a Market Data Fetcher Step

1. Click on Add Node and drag and drop the **HTTP GET under HTTP** step into the workflows
2. Hover over the step and click on settings
3. First, let's name it `market-data-fetcher` (This name could be anything you like)

#### Configure the API Request

* URL: `https://poc.platform.lat/zillow/webservice/GetZestimate.htm?zws-id=demo-api-key&zpid=${property-data-fetcher.zpid}`
* Method: `GET`

#### Set Outputs

* `zestimate.amount.value` → `response.body.zestimate.amount.value`
* `zestimate.amount.currency` → `response.body.zestimate.amount.currency`
* `zestimate.rent.value` → `response.body.zestimate.rentZestimate.value`
* `zestimate.rent.currency` → `response.body.zestimate.rentZestimate.currency`
* `property.bedrooms` → `response.body.property.bedrooms`
* `property.bathrooms` → `response.body.property.bathrooms`
* `property.finishedSqFt` → `response.body.property.finishedSqFt`
* `property.yearBuilt` → `response.body.property.yearBuilt`
* `property.type` → `response.body.property.propertyType`

Close the **Settings**.

{% hint style="warning" %}
Output type should be string for all the outputs
{% endhint %}

#### Add an AI Node

1. Click on Add Node and drag and drop the **OpenAI GPT under AI Assistant** step into the workflows
2. Hover over the step and click on settings
3. First, let's name it `ai-property-analysis` (This name could be anything you like)

#### Configure the AI Request

* URL: `https://api.openai.com/v1/chat/completions`
* Method: `POST`
* Headers:

  ```json
  {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": "Bearer ${_SECRETS.OPENAI_API_KEY}"
  }
  ```
* Body:

  ```json
  {
    "model": "gpt-4o-mini",
    "temperature": 0,
    "response_format": { "type": "json_object" },
    "messages": [
      { "role": "system", "content": "You are a professional real estate analyst. Only output valid JSON." },
      { "role": "user",
        "content": "Analyze this property for investment potential. Property: ${property-data-fetcher.address.street}, ${property-data-fetcher.address.city}, ${property-data-fetcher.address.state} ${property-data-fetcher.address.zipcode}. Bedrooms: ${market-data-fetcher.property.bedrooms}, Bathrooms: ${market-data-fetcher.property.bathrooms}, SqFt: ${market-data-fetcher.property.finishedSqFt}, Year Built: ${market-data-fetcher.property.yearBuilt}, Type: ${market-data-fetcher.property.type}. Zillow Estimate: ${market-data-fetcher.zestimate.amount.value}(${market-data-fetcher.zestimate.amount.currency}). Rent: ${market-data-fetcher.zestimate.rent.value}(${market-data-fetcher.zestimate.rent.currency}). Return JSON: { recommendation: INVEST/HOLD/PASS, property_value: number*10^20, investment_grade: A+/A/B+/B/C+/C/D, expected_annual_yield: number*10^18, confidence: number (1-100), invest_value: number * 10^18 }."
      }
    ]
  }
  ```

#### Set Outputs

* &#x20;`ai_analysis.result` → `response.body.choices.0.message.content`

Close the **Settings**.

### Step 4: Construct & Submit EVM Payload

This node will be automatically added as soon as you add the first step in the workflow. Now click on edit to open the settings

#### Configure Parameters -> Expected Response in the contract

Under the settings we need to first configure the response fields which are expected by the target smart contract, in our case,

```
confidence -> uint256
expectedAnnualYield -> uint256
investmentGrade -> string
propertyValue -> uint256
recommendation -> string
```

#### Map Parameters -> Expected Response in the contract

As we have configured the field as components under Configuration in the Settings. Now we can map the workflow results to the fields as per the requirement, in our case this is how the mapping should look like where each field is being mapped via internal referencing of selective workflow steps.

```json
propertyInfo: {
  confidence: "${ai-property-analysis.result.confidence}",
  expectedAnnualYield: "${ai-property-analysis.result.expected_annual_yield}",
  investmentGrade: "${ai-property-analysis.result.investment_grade}",
  propertyValue: "70000000000000000000000",
  recommendation: "${ai-property-analysis.result.recommendation}"
}
```

#### Set Outputs

* No change needed

Close the **Settings**.

### Step 5: Preview, Save, and Export

1. Verify all connections
2. Check node outputs
3. Save workflow (auto-save enabled)
4. Export workflow: Workflow Name → Export → Download JSON


# FAQ

<details>

<summary>Why <strong>don’t I see my project after refresh?</strong></summary>

* Your browser may have cleared local storage. Re-import your `.json` export.
* Ensure you’re using the same browser/profile.

</details>

<details>

<summary>Why <strong>doesn’t my function appear in the function signature picker screen?</strong></summary>

* Only functions whose first parameter matches the `authData` tuple appear.
* Verify your ABI and the function’s signature.

</details>

<details>

<summary>Where my data is being stored?</summary>

KRNL Studio doesn't store any of your DSL data on any server, all data is stored on your browser's local storage

</details>

<details>

<summary>How can I ensure if my changes are saved?</summary>

All changes are automatically saved, and a indicator on the header indicates the last saved changes with timestamp

<figure><img src="/files/CwNq4yrke5cpPvBlXRVF" alt=""><figcaption></figcaption></figure>

</details>


# Overview

## **KRNL CLI Overview**

**KRNL CLI** is a command-line tool for developing, compiling, and deploying smart contracts using the KRNL Protocol. It simplifies project setup, manages Foundry installation, and provides commands for verification attestors.

#### Key Features

* Project initialization with Foundry setup
* Smart contract compilation with auto-detected directories
* Deployment via Forge scripts with network detection and optional verification
* Attestor creation for verification and proof workflows

#### Installation

Install globally using npm:

```bash
npm install -g @krnl-dev/krnl-cli
```

#### Quick Start

```bash
# Initialize a new KRNL project
krnl init --name my-project

# Compile contracts
krnl compile

# Deploy to a network
krnl deploy --network sepolia
```

***

## **KRNL CLI Commands**

#### `krnl init` – Initialize a project

Creates a new KRNL project with the default template. Sets up Foundry, installs dependencies, and generates `.env`.

**Options:**

| Flag                        | Description     | Default   |
| --------------------------- | --------------- | --------- |
| `-t, --template <template>` | Template to use | `default` |
| `-n, --name <name>`         | Project name    | —         |

**Example:**

```bash
krnl init --name my-krnl-project
cd my-krnl-project
```

***

#### `krnl compile` – Compile contracts

Compiles smart contracts with auto-detection of source and output directories.

**Options:**

| Flag                       | Description                    |
| -------------------------- | ------------------------------ |
| `-c, --contracts <path>`   | Contracts directory (optional) |
| `-o, --output <path>`      | Output directory (optional)    |
| `-p, --project-dir <path>` | Project root (optional)        |

**Example:**

```bash
krnl compile
krnl compile -c ./src -o ./out
```

***

#### `krnl deploy` – Deploy contracts

Deploys contracts using Foundry scripts. Auto-detects network from `.env` and `foundry.toml`. Supports optional verification.

**Options:**

| Flag                        | Description                                                         | Default               |
| --------------------------- | ------------------------------------------------------------------- | --------------------- |
| `-n, --network <network>`   | Deployment network                                                  | `localhost`           |
| `--script <pathOrTarget>`   | Forge script path                                                   | `script/Deploy.s.sol` |
| `--verify`                  | Verify contract on explorer. requires `--contract`                  | —                     |
| `--verify-all`              | Verify all the contract being deployed using the script on explorer | —                     |
| `--contract <name>`         | Contract name to verify (required with `--verify` and `--script`)   | —                     |
| `--constructor-args <args>` | Constructor arguments for verification (if needed)                  | —                     |

**Example:**

```bash
# Deploy using default script to sepolia
krnl deploy --network sepolia

# Deploy with verification of a specific contract
krnl deploy --network sepolia --verify --contract RealEstateInvestment

# Deploy with verification of all contracts in script
krnl deploy --network sepolia --verify --verify-all

# Use custom script with specific contract target
krnl deploy --network sepolia --script "script/Deploy.s.sol:DeployRealEstateScript" --verify --contract RealEstateInvestment

# Use custom script and verify all the contracts
krnl deploy --network sepolia --script "script/Deploy.s.sol:DeployRealEstateScript" --verify-all

# Deploy to localhost (requires Anvil running)
krnl deploy --network localhost
```

***

## **KRNL CLI: Create Attestor**

#### `krnl create-attestor` – Generate a verification attestor

Creates a Docker-based attestor for contract verification. Attestors are required to submit proof-enabled actions on KRNL Protocol workflows.

**Usage:**

```bash
krnl create-attestor
```

This command executes the included `create-attestor-standalone.sh` script.

**Notes:**

* Requires Docker installed and running
* Automatically sets up the attestor environment for standalone usage
* Can be used in CI/CD pipelines for automated attestor generation


# FAQ

<details>

<summary>Do I need Foundry installed before using KRNL CLI?</summary>

No. The CLI automatically checks for Foundry (forge, cast, anvil) during project initialization. If Foundry is missing or the version is below 1.0.0, it will install or update it automatically.

</details>

<details>

<summary>How does KRNL CLI detect project structure?</summary>

* Source contracts: Auto-detects `src/` or `contracts/`
* Output artifacts: Auto-detects `out/` or `artifacts/`
* Configuration: Reads `foundry.toml` if present

You can override these paths using the `-c`, `-o`, and `-p` flags with `krnl compile`.

</details>

<details>

<summary>How does deployment network detection work?</summary>

KRNL CLI prioritizes networks in this order:

1. Network specified via `--network` flag
2. RPC URLs defined in `.env` (e.g., `SEPOLIA_RPC_URL`)
3. `[rpc_endpoints]` section in `foundry.toml`
4. Defaults to `localhost:8545`

</details>

<details>

<summary>What is an attestor, and why do I need one?</summary>

Attestor is a component which will attest and also resolve the secrets in your DSL workflow. You create one using:

```bash
krnl create-attestor
```

</details>

<details>

<summary>What happens if my PRIVATE_KEY is missing the 0x prefix?</summary>

KRNL CLI automatically detects this and adds `0x` if needed during deployment.

</details>

<details>

<summary>Where are the compiled artifacts stored?</summary>

By default:

* Foundry outputs: `out/` or `artifacts/`
* Can be overridden with the `-o` flag in `krnl compile`

</details>

<details>

<summary>Can I create a custom project template?</summary>

Yes. Use the `-t, --template` flag with `krnl init`:

```bash
krnl init --name my-project --template custom-template
```

Your template must follow the KRNL project structure.

</details>

<details>

<summary>How do I update KRNL CLI?</summary>

```bash
npm install -g krnl-cli@latest
```

This will install the latest version globally.

</details>


# New to Web3?

## Welcome builders!

For enthusiasts and developers who are just getting started in blockchain and Web3, **we strongly recommend you explore every section of this entire documentation.**

We provide **guidelines, examples, and links to relevant materials** that will guide your understanding.

We also invite you to **explore tools and frameworks that will assist your development**, such as MetaMask (wallet), Remix (smart contract development tools), and Etherscan (blockchain explorer).

***

## 0. Learn blockchain and Web3

It might seem like an expected answer from any guidebook you may find, but the very first few things you should do are reading, exploring, and studying.

Blockchain and Web3 are vast, rapidly evolving fields still in their early stages of development.

It is recommended to explore related topics such as execution layers, consensus mechanisms, EVM, wallets, and more.

***

## 1. Dictionary

Some technical terminology, jargon, and acronyms used in the KRNL docs will be new to you - please use the **Dictionary** page to familiarise yourself. Thank you, and good luck!

{% content-ref url="/pages/OOVTsgGFeoN01ajmmQ0h" %}
[Dictionary](/helpful-resources/dictionary)
{% endcontent-ref %}

***

## 2. Learn how to write and deploy smart contract

{% embed url="<https://www.youtube.com/watch?v=xIIyeT9rs5o>" %}

If you are reaching this stage, it is a good time to learn how to use smart contract development tools such as **Remix IDE**, **Hardhat** or **Foundry**. This does not only give you the exposure to the frameworks, but you will also get the idea of your favorite tool for debugging and deploying smart contracts.

***

## 3. Quick Start

Quick Start pages will also guide you to the shortcut of utilizing kOS into your smart contract without having to code a single line.

It has steps, guidelines, and pictures which you can follow.

After finishing, you may explore the possibilities of KRNL by changing or adding kernels into the list of selected kernels.

{% content-ref url="/pages/5Wf7JaZ8RRXkzSWLMabk" %}
[Getting Started](/getting-started/getting-started-with-krnl)
{% endcontent-ref %}

***

## 4. Try different smart contact and dApp ideas

At this stage, you should have tried more than one kernel. You should also have some good ideas on smart contract development.

It is recommended to build your own smart contract, and a dApp that interacts with it.

Good luck!


# Dictionary

This page is dedicated to KRNL-specific vocabulary that will appear in this document.

#### Core Protocol Concepts

| Term                             | Definition                                                                                                                                       |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| **KRNL Protocol**                | A decentralized orchestration layer that unifies Web3, Web2, and AI systems into verifiable workflows using cryptographic proofs.                |
| **Kernel**                       | A single execution unit in a workflow that performs a specific function such as an API call, smart contract interaction, or data transformation. |
| **Workflow**                     | A multi-step process built using KRNL’s DSL (Domain-Specific Language) that defines how kernels interact to perform a complete operation.        |
| **Executor**                     | An open-source, auditable component that executes workflow steps within a secure sandbox.                                                        |
| **Attestor**                     | A private security module owned by dApp developers that cryptographically verifies executor outputs and signs attestations.                      |
| **Executor–Attestor Separation** | The architectural principle separating computation (executor) from verification (attestor) to achieve zero-trust execution.                      |
| **KRNL Node**                    | The execution and orchestration engine (a Geth extension) that coordinates workflows, handles network attestation, and generates proofs.         |
| **KRNL Registry**                | An on-chain registry that stores protocol configurations, kernel schemas, and versioned workflow references.                                     |
| **KRNL Vault**                   | The fee management contract that handles payments, rewards, and treasury operations for executors, node operators, and developers.               |
| **KRNL SDK**                     | Developer toolkit enabling integration of workflows into dApps through TypeScript or JavaScript APIs.                                            |
| **KRNL CLI**                     | A command-line interface for deploying, testing, and managing KRNL integrated contracts                                                          |
| **KRNL Studio**                  | A visual IDE for building and testing workflows without writing code.                                                                            |
| **KOS (KRNL Operating System)**  | The coordination layer managing node discovery, attestation, and proof validation across the network.                                            |

#### Architecture & Infrastructure

| Term                             | Definition                                                                                                  |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| **Core Orchestration Layer**     | The main KRNL engine that executes workflows and coordinates executor-attestor communication.               |
| **Integration Layer**            | Connects dApps and smart contracts to KRNL via SDKs and account abstraction mechanisms.                     |
| **User Interface Layer**         | The front-end interface through which end users initiate workflows via wallets and smart contract accounts. |
| **External Infrastructure**      | Components managed outside KRNL (e.g., relayers, bundlers, oracles).                                        |
| **Target Contract**              | A smart contract that receives verified results from a workflow for final execution.                        |
| **Relayer / Bundler**            | A service that manages EIP-4337 transactions for Smart Contract Accounts.                                   |
| **Smart Contract Account (SCA)** | A programmable wallet (EIP-7702 + ERC-4337) that executes transactions and payments automatically.          |

***

#### Security & Cryptography

| Term                                    | Definition                                                                                                               |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| **Ephemeral Keys**                      | Single-use cryptographic keys derived for each workflow execution, ensuring replay protection and forward secrecy.       |
| **Master Secret**                       | Root cryptographic secret stored securely in the attestor and used for key derivation.                                   |
| **Execution Proof**                     | A cryptographic record proving that workflow steps were executed as defined.                                             |
| **Composability Proofs**                | Nested proofs combining multiple workflow steps into a verifiable chain of trust.                                        |
| **Network Attestation**                 | A cryptographic record verifying every external network call (HTTP, HTTPS, DNS) made during execution.                   |
| **Network Interceptor**                 | A man-in-the-middle system that transparently monitors, records, and signs network interactions for forensic validation. |
| **DNS Attestation**                     | Cryptographic logging of DNS queries and resolutions during workflow execution.                                          |
| **TLS Interception**                    | Secure interception of HTTPS traffic to verify end-to-end communication integrity.                                       |
| **Attestation Data Structure**          | Structured logs of network activities (requests, responses, DNS) signed by the attestor.                                 |
| **Proof of Execution (PoE)**            | The verifiable linkage between executor outputs and attestor signatures.                                                 |
| **TEE (Trusted Execution Environment)** | Hardware-based secure enclave used optionally for high-value workflow isolation (e.g., Intel SGX, AMD SEV).              |
| **gVisor Sandbox**                      | A user-space kernel providing syscall interception and runtime isolation for executors.                                  |
| **Reproducible Builds**                 | Deterministic build process ensuring executor binaries can be independently verified.                                    |

***

#### Economic & Governance Model

| Term                            | Definition                                                                           |
| ------------------------------- | ------------------------------------------------------------------------------------ |
| **Node Operator**               | Participant running a KRNL Node to process workflows and generate proofs.            |
| **dApp Developer**              | Builder who integrates KRNL workflows into decentralized applications.               |
| **Fee Architecture**            | The breakdown of workflow execution costs: base fee, external service fees, and gas. |
| **Value Distribution Model**    | Economic mechanism distributing fees and rewards among protocol participants.        |
| **Platform Base Fee**           | The protocol’s fixed cost for using KRNL infrastructure per execution.               |
| **Treasury Management**         | Automated handling of collected fees, development funds, and ecosystem grants.       |
| **Governance Model**            | Community-driven structure for approving executors and protocol updates.             |
| **Executor Governance Model**   | Consensus process through which executors are reviewed, audited, and whitelisted.    |
| **Protocol Evolution Strategy** | Framework for introducing new features and managing backward compatibility.          |

***

#### Comparative & External References

| Term                         | Definition                                                                                                                           |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| **EIP-4337**                 | Ethereum proposal enabling account abstraction for smart contract wallets. Read more [here](https://eips.ethereum.org/EIPS/eip-4337) |
| **EIP-7702**                 | Ethereum proposal for delegating transaction execution rights. Read more [here](https://eips.ethereum.org/EIPS/eip-7702)             |
| **CID (Content Identifier)** | IPFS hash used for content verification and versioning.                                                                              |


# KRNL RPC

KRNL is in the testnet stage, where KRNL nodes are only running by KRNL Labs.

The below list shows the RPC endpoints that **dApp builders** can call to kernels and call transactions.

***

## Recommended

The recommended RPC endpoint for calling KRNL node is in the below snippet.

```
https://node.krnl.xyz
```

***

## List of RPC Endpoints

| RPC                     | Release Date | EOL |
| ----------------------- | ------------ | --- |
| <https://node.krnl.xyz> | 6 Oct 2025   | -   |


# Testnet Faucets

## Sepolia ETH Option 1

{% embed url="<https://sepolia-faucet.pk910.de/>" %}

***

## Sepolia ETH Option 2

{% embed url="<https://cloud.google.com/application/web3/faucet>" %}

### Relevant Link

{% embed url="<https://www.infura.io/faucet/sepolia>" %}


# How to Get Etherscan API Key?

## Steps

#### 1. Visit Etherscan website

{% embed url="<https://etherscan.io/>" %}

#### 2. Click "Sign In" on the top-right corner

<figure><img src="/files/GvAHresva53BRPhAWuRp" alt=""><figcaption></figcaption></figure>

#### 3. Login if you already have an account, or click "Sign Up" if you do not have an account

<figure><img src="/files/gfrXFfDLzLBqRVww4CU3" alt="" width="382"><figcaption></figcaption></figure>

#### 4. Once logged in, hover your mouse on your logged in username and click "API Keys"

<figure><img src="/files/AZPDNP4JoOcHvPAX25F9" alt=""><figcaption></figcaption></figure>

#### 5. Scroll down to see the "API Keys" panel and click "+Add"

<figure><img src="/files/jKaHD9sp37ClahaSjqTR" alt=""><figcaption></figcaption></figure>

#### 6. Give a name to your API key (probably only you can see)

<figure><img src="/files/ix7Fe9DitMpkYMdSDMal" alt=""><figcaption></figcaption></figure>

#### 7. Copy and note down your API key for later

<figure><img src="/files/59H8GPlunbXIwxNKk2Xs" alt=""><figcaption></figcaption></figure>

***

## Additional Steps for Remix IDE

#### 8. Get back to Remix IDE and click "Enable?"

<figure><img src="/files/1nQ6XrDGheLnGvbteFt7" alt="" width="260"><figcaption></figcaption></figure>

#### 9. Edit API key in Etherscan section and then click "Save"

<figure><img src="/files/VdA5D878lid2kSnMQqq9" alt="" width="250"><figcaption></figcaption></figure>

#### 10. Congratulations! you can now verify your deployed smart contracts


# Litepaper


# Overview

KRNL is a next-generation infrastructure layer that enables cryptographically verifiable off-chain and cross-chain computation via developer-defined modules called kernels. Its orchestration framework combines new proof primitives, secure execution, and open governance to deliver full transparency and composability for Web3, Web2, and AI-powered dApps.

Key properties:

* Verifiable off-chain computation: any external call, HTTP request, or AI inference is attested so that on-chain contracts or external verifiers can confirm correct execution.
* Cross-chain & cross-domain bridges: workflows can span multiple blockchains, Web2 services/APIs, and AI systems, with proofs stitched together.
* Modular & developer-friendly: Kernels are plug-and-play units that define specific workflows (e.g. API fetch, simulation, inference, computation) that are reusable and composable.
* Governed & secure: decentralised registration, open attestation, and runtime security measures ensure trust minimisation.

"Kernels" are modular execution shards that convert both on-chain and off-chain functions into a distributed runtime environment, optimizing for resource utilization, modularity, and rapid interoperability.

This approach enhances the responsiveness of decentralized applications (dApps) and significantly reduces their time-to-market, unlocking new potential use cases in DeFi, RWAs, AI, gaming, and beyond


# Problem Statement

dApp developers, institutions, and ecosystem partners currently suffer from multiple unresolved issues when building complex workflows of logic:

**Fragmentation:** The proliferation of Layer 1 and Layer 2 solutions has created isolated silos, obstructing seamless interaction between dApps and smart contracts across different ecosystems, thus undermining the core principle of composability in decentralized systems.

**Scalability Constraints:** Ethereum continues to struggle with network congestion and high gas fees, which discourage widespread dApp adoption and degrade user experience.

**Cross-Chain Friction:** Achieving interoperability between Ethereum and other blockchains often requires complex, bespoke integrations. The lack of standardized cross-chain communication protocols exacerbates development complexity, hindering innovation and efficiency.

**Security Vulnerabilities:** Ensuring transaction integrity, provenance, and security in a decentralized manner remains challenging. The rise of bridges and interoperability solutions introduces new attack vectors, increasing security risks.

The KRNL Protocol serves as an orchestration and verification engine, allowing smart contracts to integrate these kernels (workflow steps), enriching the logic and state management of traditional smart contract operations without requiring custom infrastructure. This proposal positions KRNL as an essential tool for the development of *real-world* applications.


# Current State Does Not Solve the Problem

There are a few methods utilized to attempt to solve this problem with limited results:

1. Webhooks
2. Co-processors
3. Messaging Protocols

**Webhooks:** Webhooks are inherently read-only, are often off-chain, are sometimes permissioned, and cannot directly determine the outputs without further integration by the party using them.

**Co-processors:** Are inherently single-user and not available to other parties in the ecosystem (e.g., a developer building an analytics co-processor to help them evaluate the health of their lending protocol, which they can utilize but is not interoperable with other protocols).

**Messaging Protocols:** Messaging protocols such as LayerZero and Axelar are concerned primarily about how state changes are implemented cross-chain – not whether or how transactions should be executed to begin with.

In a hypothetical scenario, a DeFi protocol on Ethereum would like to allow users to trade RWA assets if they are an approved user on Company 1’s RWA platform (and if not, to reject the transaction from this wallet). Say Company 1 has built an RWA platform on Blockchain 2, with dynamic off-chain metadata corresponding to approved users. Additionally, these users need to have an identity score of X as determined by a on-chain DID smart contract on Blockchain 3. In the past, implementing these solutions across various chains would have required multiple complex integrations and in many cases require direct communication with vendors. However, with KRNL, builders now only need to perform a single, one-time permissionless integration.

There is not currently any application layer that facilitates the conditional logic before state changes are executed, and this is generally built ground-up by builders. Ideally, this would be done in a plug-and-play, permissionless manner that would be reproducible by protocols that want to utilize the RWA platform and identifiers from the DID system.

<figure><img src="/files/tCb2GQvVCgM39RCKCUyA" alt="" width="563"><figcaption><p>Figure 1</p></figcaption></figure>


# Introducing Kernels

Execution Sharding refers to the approach of dividing and distributing the execution of smart contracts across multiple blockchain networks, or "shards", to enhance scalability and efficiency in blockchain systems. Instead of executing every transaction on a single chain, execution sharding allows transactions and smart contract states to be distributed across multiple chains, each handling a portion of the overall workload.

Execution sharding is pivotal for Ethereum’s scalability. The KRNL Protocol integrates permissionless and composable kernels (execution shards) across multiple networks directly into the Ethereum transaction lifecycle.

KRNL optimizes resources to provide a secure and efficient execution environment for smart contracts, creating a distributed runtime that determines transaction outcomes based on the selected kernels across diverse environments. KRNL’s open framework enhances modularity, optimizes resources, and accelerates deployment, ultimately improving dApp responsiveness and reducing time-to-market.

Within the KRNL Protocol, kernels represent execution shards and transform both on-chain and off-chain functions into modular units with the following attributes:

* **Statelessness:** Kernels maintain no intrinsic state, ensuring flexibility and easy migration across environments.
* **Lightweight Design:** Kernels minimize computational overhead, promoting efficient execution.
* **Resilience:** Kernels are designed to withstand operational failures, ensuring reliable performance.
* **Independent Deployability:** Kernels can be deployed across various environments without dependency.

The defining features of kernels include:

* **Infrastructure Agnostic:** Kernels are not tied to specific infrastructures; they can migrate across environments as needed.
* **Enhanced Modularity and Composability:** By deconstructing applications into discrete kernels, modularity is improved, enabling permissionless sharing across multiple applications.

Accelerated Deployment: Simplified deployment processes enhance dApp responsiveness and reduce time-to-market.


# Ecosystem of Kernels

#### **The Pre-Cloud Paradigm**

Before cloud computing, developers bore the burden of constructing, operating, and maintaining all requisite programs and services. This paradigm engendered prohibitive costs, scalability constraints, accessibility challenges, and resource limitations. Cloud computing revolutionized this landscape, introducing managed services where back-end infrastructures are handled by cloud providers.

<figure><img src="https://docs.krnl.xyz/~gitbook/image?url=https%3A%2F%2F2375546308-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FejIqZaKRZqEX2L6dfKDH%252Fuploads%252F97nmGcFp6UidE4YSVQee%252FAfter%2520Cloud%2520Computing.png%3Falt%3Dmedia%26token%3D8fddd9dc-19e0-46b3-b69d-81e70cb7e4b9&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=f9bfe626&#x26;sv=1" alt=""><figcaption><p>Before and after cloud</p></figcaption></figure>

#### **KRNL’s Transformative Potential**

KRNL aims to catalyze a similar paradigm shift within the Web3 domain—a permissionless Web3 environment built by the community through contributions of monetizable kernels. This vision aligns with the Function as a Service (FaaS) model, reimagined to suit the decentralized and heterogeneous fabric of blockchain ecosystems.

<figure><img src="/files/gUEvAk4VMjjTAjfTr2wm" alt=""><figcaption><p>Before and after KRNL</p></figcaption></figure>

#### **Functions as a Service (FaaS) in the Web3 Context**

FaaS is a category of cloud computing services that provide a platform enabling customers to develop, run and manage applications without the complexity of building and maintaining the infrastructure associated with developing and launching an app. Examples of a traditional FaaS include AWS Lambda, Google Cloud Functions, Microsoft Azure Functions, etc.

The conventional FaaS model does not fit well in distributed and heterogeneous blockchain environments, where each blockchain is a silo and not efficient in the context of the whole Web3 ecosystem. To adapt this concept to Web3, it is essential to ensure decentralized registry, management, and execution of kernels.


# The KRNL Protocol

<figure><img src="/files/dau54Sywo13awo8az136" alt=""><figcaption></figcaption></figure>

#### **Compute Engine**

The KRNL Compute Engine is a powerful orchestration and verification system embedded within Ethereum RPC nodes (modified Geth), designed to optimize smart contract execution across multiple blockchain networks.

**Execution Sharding**

Smart contract tasks are distributed across independent kernels (execution shards), enabling modular scaling and cross-chain efficiency. Each kernel can be executed permissionlessly, allowing developers to compose complex workflows without central coordination.

**Executor–Attestor Mechanism**

Every workflow is decomposed into containerized steps executed within discrete [**gVisor**](https://gvisor.dev/) **sandboxes**.

* The **Executor** runs each step according to the encoded workflow logic, performing external data calls, computations, or on-chain interactions.
* The **Attestor** independently verifies the execution by reproducing or validating results within its own sandbox, signing an attestation once the output is confirmed.

This dual-layer verification model replaces traditional resolver-based integrations, ensuring all off-chain and cross-chain computations have cryptographic audit trails that are independently reproducible and tamper-evident.

The Compute Engine thus establishes a scalable, verifiable, and trust-minimized foundation for hybrid applications that bridge Web2, Web3, and AI systems.

#### **Proof of Provenance (PoP)**

**Proof of Provenance (PoP)** ensures that every workflow executed through KRNL has been securely run, observed, and verified before any transaction is finalized on-chain.

This integrity is achieved through the **Executor–Attestor separation model**, where open-source **Executors** perform the computation within discrete **gVisor sandboxes**, and closed-source **Attestors**, controlled by developers, independently verify each execution step.

The **Attestor** continuously monitors the sandbox environment, observes all network traffic, and cryptographically attests to the correctness of the computation. By separating execution from attestation, KRNL prevents rogue or compromised executors from manipulating results—every step must be cryptographically validated before its proof can be accepted.

Each attestation is signed using **ephemeral keys** derived from securely managed master secrets and the unique execution context. This ensures that:

* Keys are one-time-use and context-bound, preventing replay or forgery.
* Secrets are protected at compile time and never persist beyond execution.
* Every attestation is verifiable and linked to its specific workflow run.

The resulting composite proof combines execution context hashes, signatures, and network attestation data—creating an immutable, verifiable record of computation that can be validated on or off-chain.

PoP thus guarantees **end-to-end provenance**, ensuring all workflow results are both cryptographically sound and operationally transparent.


# Decentralization and Security Considerations

#### **Upholding Decentralization**

KRNL leverages the intrinsic decentralization of existing native blockchains. By integrating with a standard Ethereum RPC node, any Ethereum RPC node can function as a KRNL node without interfering with consensus mechanisms of the underlying network. Node operators are incentivized through the accrual of a proportion of fees generated from kernels, fostering a decentralized and participatory ecosystem.

#### **Mitigating Malicious Activities**

To preempt and mitigate potential malicious activities, such as replicating KRNL node code to fabricate counterfeit signatures, KRNL employs multiple cryptographic schemes that ensure security by design. The security architecture is flexible, customizable, and predominantly under the control of the dApp developer. This approach ensures that the KRNL Protocol remains permissionless, resilient, and secure.


# Use Cases for KRNL

KRNL enables developers to compose verifiable workflows that extend smart-contract logic beyond the chain. Each use case below highlights new capabilities unlocked by bringing off-chain computation and real-world logic into the verifiable execution flow.

<details>

<summary>AI Tethering</summary>

AI Tethering is the design pattern of anchoring an AI system’s critical artifacts and actions (training data, model binaries, version history, key inferences) to a blockchain ledger. The ledger’s immutability supplies a cryptographic “paper-trail” that anyone can audit to prove the AI has not been tampered with and is operating under agreed-upon rules.&#x20;

Put diﬀerently, AI tethering locks models and their data inside a cryptographic glass case so every hand-oﬀ, every update, and every decision leaves an indelible fingerprint. When something goes wrong, auditors don’t rely on promises or internal logs; they open the ledger and inspect the immutable trail. The result is AI that proves its integrity instead of merely requesting trust.

For more information, explore [OpenBox](https://openbox.ai).<br>

</details>

<details>

<summary>Taint Analysis</summary>

Taint analysis is a key technique for identifying whether untrusted (tainted) data can reach sensitive parts of a program (sinks), potentially triggering harmful operations.

Dynamic taint analysis operates at runtime and provides more accurate detection in real-world execution contexts. KRNL allows for efficient taint analysis through running the validation through a more gas-optimised execution environment (e.g. cheaper L2).<br>

</details>

<details>

<summary>Pre-Transaction Compliance</summary>

Pre-transaction compliance ensures every on-chain action is screened against regulatory, AML, and policy rules before it is broadcast, preventing bad actors. By validating sender/recipient provenance, sanctions exposure, and licence constraints at the intent stage, projects can prove a provable compliance posture to auditors and regulators.

Traditional compliance providers rely on inefficient frontend solutions which can be bypassed or costly oracle-based solutions.

KRNL embeds these checks into the native transaction flow as kernels, so builders get verifiable, deterministic, and enforceable compliance policies at minimal costs.

</details>

<details>

<summary>Programmable Assets</summary>

Programmable assets embed business logic such as compliance, vesting, governance, or clawback logic directly in the token standard. They act more like autonomous micro-applications than static assets. Examples include: compliant stablecoins, RWAs, dynamic NFTs, and more.

</details>

<details>

<summary>Web2 &#x3C;> Web3 Pull Oracle</summary>

Pull oracles let a user or application fetch fresh off-chain data on demand. In most implementations, the contract must first write the oracle’s response to the blockchain, forcing the user to wait a full block (or more) before the data becomes usable—slow and costly.

With KRNL, the data is embedded in the same transaction that requests it. The oracle fetches the information off-chain, injects it in the transaction payload, and delivers it directly to the smart contract, bypassing the extra state-update step and eliminating the delay.

</details>

<details>

<summary>Decentralized Identity (DID)</summary>

The Web3 ecosystem already has several DID solutions, but many are chain-specific or rely on zk-proof technology, requiring development for each integrated chain. KRNL technology changes the game by enabling a DID built on a single, optimized network to serve as a universal solution across Web3. By creating the DID as a kernel on a chosen chain and mapping it to the KRNL protocol, it can seamlessly integrate into any network's transaction lifecycle.

</details>

<details>

<summary>Private &#x3C;> Public Blockchain Messaging</summary>

Many enterprises split workloads between permissioned ledgers (for sensitive data) and public networks (for liquidity or trust). Secure, verifiable messaging must bridge the two without leaking information.

Leveraging KRNL as the messaging layer, critical data is signed and sealed in payloads that confirm message integrity without revealing the content. The result: GDPR-safe data remains private, while the fact of the transaction is publicly undeniable.

KRNL also makes Delivery versus Payment (DvP) atomic and trust-minimised: it packages the asset-delivery instruction on a permissioned ledger and the matching payment on a public chain into mutually dependent actions that each leg verifies before either executes, ensuring the trade settles–or rolls back–in a single stroke without exposing sensitive deal details.<br>

</details>

<details>

<summary>IP Management</summary>

Digital intellectual property—music, art, patents—needs transparent ownership history, fractional licensing, and automated royalty distribution. Traditional registries are siloed and slow.

Creators sign an “asset-manifest” off-chain; KRNL notarises it on-chain, stores the hash, and injects automatic royalty-split logic into every subsequent transfer or licence call routed through the node.

</details>

<details>

<summary>Verifiable Randomness</summary>

Many Web3 games, raffles, and DeFi primitives depend on unpredictable yet provably fair randomness. Pseudo-random on-chain tricks are manipulable; off-chain oracles add trust assumptions.

With KRNL, developers can access VRFs (Verifiable Random Functions) located on optimised execution layers outside of EVM where calls are verifiable and transparent.

</details>

<details>

<summary>Transparent On-chain and Off-chain Insurance</summary>

Traditional insurers can take weeks to process even the simplest claims because each step is manual, opaque, and costly. KRNL compresses the entire workflow into one attested transaction. When a covered event occurs, KRNL automatically triggers the claim. The event could be a flight delay, a crop-weather anomaly, or an air-bag sensor alert. KRNL then retrieves and verifies proof from trusted sources such as airline APIs, weather services, or IoT devices. It hands this evidence to the claim-settlement kernel, checks the policy conditions, calculates the payout, and releases the funds in a single on-chain call. The result is payouts in minutes rather than weeks, a sharp reduction in fraud risk, and dramatically leaner operating costs for insurers.

</details>

<details>

<summary>Dynamic NFT</summary>

Dynamic NFT that automatically updates NFT traits by tracking both on-chain and off-chain activity via kernels. Evolving assets keep collectors invested and interacting, transforming holders into loyal advocates.

</details>

<details>

<summary>Cross-Chain Gaming</summary>

Game developers currently need to coordinate with each other to enable interoperable features, especially for off-chain dependencies requiring APIs. KRNL simplifies this by allowing developers to upload their kernels on-chain, providing a permissionless way to utilize and monetize their data.

</details>

These are a few among many other use cases that can be derived from the KRNL Protocol. Reach out to us if you'd like to tackle building one of these.


