# What Is Truebit Verify?

Truebit Verify brings cryptographic **proof of correctness** to off-chain computation, providing verifiable orchestration, data provenance, and transparency for any workflow—from blockchain applications to traditional data pipelines.

**This platform allows application to run-off chain code with on-chain guarantees, providing verifiable proof that the execution was honest and correct.**&#x20;

With features like audit trails, multi-node validation, and blockchain-anchored verification protocol, Truebit enables secure use of external APIs, cross-chain data, and complex logic without compromising trust.

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

Truebit Verify addresses core trust challenges emerging as digital systems gain autonomy and decentralized infrastructures evolve, establishing a foundational verification layer that **ensures authenticity, transparency, and reliability** for critical processes operating beyond the boundaries of a blockchain.

### Truebit's Issue-Solving Platform

While blockchains are secure, many applications still rely on external systems that can’t be fully trusted. Truebit solves this by verifying off-chain computation, ensuring it's accurate, transparent, and provable.

Some of the key usage patterns are the following:

1. [Integrating safely with third-party APIs](/overview/what-is-truebit-verify/truebits-benefits#integrating-safely-with-third-party-apis)
2. [Moving data across different chains](/overview/what-is-truebit-verify/truebits-benefits#moving-data-across-different-chains)
3. [Trustlessly calling outside functions](/overview/what-is-truebit-verify/truebits-benefits#trustlessly-calling-outside-functions)

### Process Verification

As digital systems grow increasingly complex and autonomous, much of their decision-making unfolds beyond the boundaries of transparent infrastructure. Hidden logic and closed environments create “black box” processes that challenge trust and transparency.

**Truebit Verify** closes this gap by introducing **Truebit Certified Transcripts—tamper-proof records that make every offchain process auditable, from data sourcing to computation.** By transforming invisible code into verifiable proof, Truebit Verify allows you to:

* Establish trust at scale
* Reduce systemic risk
* Accelerate adoption of tokenized markets and decentralized applications

#### Truebit's Transcripts

**Transcripts are your proof of trust.** They capture every step of a task in a secure, tamper-proof record—so you always know exactly what happened and that the results are accurate. With Truebit, transparency isn’t a promise—it’s built in.

{% hint style="info" %}
To check more info about them, please review [What is a Transcript?](#truebits-issue-solving-platform)
{% endhint %}


# Truebit's Benefits

**Truebit Verify fills the gap between traditional offchain computation and onchain blockchain by bringing transparency and trust.**

\
With Truebit Verify, Web3 developers can eliminate hidden, "black box" operations and ensure full transparency over external data used in smart contracts—strengthening data integrity and establishing verifiable provenance for every transaction.&#x20;

#### Why Choose Truebit Verify?

Truebit Verify bridges the critical divide between the decentralized transaction processing of blockchains and the centralized infrastructure commonly used for essential application logic and integration.

This empowers Web3 developers to eliminate opaque operations, ensuring the integrity of their data and establishing a clear provenance for external data referenced in blockchain transactions.

### **Key Usage Patterns**

<details>

<summary><strong>Integrating Safely With Third-Party APIs</strong></summary>

This transparency ensures that every API interaction—including data reads and writes—is fully verifiable.&#x20;

For example, if I want to fetch data into a smart contract or my Web3 app from an external API, I can do so in a verifiable way. I can verify the authenticity of details, such as stock quotes or temperature data, that influence the outcome of a smart contract.

</details>

<details>

<summary><strong>Moving Data Across Different Chains</strong></summary>

Transparency is also crucial when moving data across different blockchains. As blockchains don't naturally communicate, interoperability becomes complex in Web3. We simplify this by transparently coding interactions between blockchains, ensuring the validity of read and write operations. This certification makes the operation secure, resolving challenges in moving data between different blockchains like Ethereum and Hyperledger.

</details>

<details>

<summary><strong>Trustlessly Calling Outside Functions</strong></summary>

Truebit enables trustless calls to external functions—a critical requirement for AI-driven applications. Now, smart contracts and Web3 apps can seamlessly trigger AI models or complex business logic via Truebit’s verifiable computing layer. This allows developers to maintain a Web2-style workflow while ensuring full decentralization.

</details>


# How Does Truebit Work?

### Truebit Workflow

**Truebit Verify provides a transparent environment to develop, deploy, and execute both Truebit Functions and Truebit API Tasks.** Truebit's platform generates proof of the correct execution of your code and allows you to integrate safely with different APIs, move data between blockchains, and implement complex application code.

**There are two execution types**:

* [**Function Tasks**](/developing-truebit-tasks/how-to-create-function-tasks) – execute predefined functions.
* [**API Tasks**](/developing-truebit-tasks/how-to-create-api-tasks) – interact with external APIs.

Both task types are invoked through a standard REST interface, allowing seamless integration into your applications or workflows, moving data across different chains.

#### Function Tasks

<figure><img src="/files/0UUpYrA8GkUsdiQEH2zx" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
This diagram represents the Function Task execution from a Task Requester point of view.
{% endhint %}

As a Task Developer, you create **Truebit Function Tasks** —**self-contained functions that run on** [**Truebit Verify Node**](/architecture/introduction/truebit-verify-nodes)**.** These tasks act like microservices and are exposed via a **REST API**.

For Function Tasks, [**Truebit Verify Hub**](/architecture/introduction/truebit-verify-hub) makes these tasks internet-accessible and orchestrates node operations. Under the hood, **Truebit leverages blockchain-based ledgers** to secure execution, ensure full transparency, and manage system-level financial mechanics.

**Within Function Tasks, each of them is executed by multiple nodes**, with [**Truebit Transcripts**](/overview/what-is-a-transcript) certifying outputs and providing an immutable audit trail of task and node behavior. **In case of discrepancies** in node responses, the **Adjudication Process is triggered** to resolve them by re-executing the task under the **Truebit Control Node**. This process determines which node provided an incorrect result, ensuring discrepancies are resolved and all nodes execute tasks honestly.

#### API Tasks

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

{% hint style="info" %}
This diagram represents the API Task execution from a Task Requester point of view.
{% endhint %}

As a Task Developer, you create **Truebit API Tasks**. These tasks function like microservices and are accessible via a **REST API**.

**The** [**TEE**](/developing-truebit-tasks/how-to-create-api-tasks#trusted-execution-for-api-tasks) **(Trusted Executed Environment) executes API Tasks by directly calling an API endpoint.** **This keeps API credentials and data private. Truebit Verify Nodes use a shared session key to verify communication between the Hub and API endpoints.**

Transparency is also crucial when moving data across different blockchains. As blockchains don't naturally communicate, interoperability becomes complex in Web3. We simplify this by transparently coding interactions between blockchains, ensuring the validity of read and write operations. This certification makes the operation secure, resolving challenges in moving data between different blockchains.


# What Is a Transcript?

**Transcripts are certificates of compute**. Each transcript serves as an unchanging record of every step taken, attesting details of every task execution​.

It acts as the ultimate **source of truth**, ensuring that anyone who reviews it can accurately determine the status of a task and verify the correctness of its output. This means **you can rely on the transcript** to provide an accurate account of what happened during such execution.

## Transcript Pillars

<div data-with-frame="true"><figure><img src="/files/qzB8hofm6z5kvGGxIhlx" alt=""><figcaption></figcaption></figure></div>

Transcripts ensure full transparency, driven by the following key pillars:

* **Immutability**: The transcript provides an **unchangeable record** of everything that occurred during task execution. It's a reliable source of truth for the entire process.
* **Protocol**: *Clear Roles & Responsibilities -* The transcript clearly outlines **who is responsible for what and when.** This means anyone reviewing the transcript can easily determine the progress of the task and verify the accuracy of the results.
* **Incentives & Slashes**: *Rewarding Good Behavior, Correcting Mistakes -* The transcript includes **information about rewards and penalties** for following or deviating from the protocol. This ensures that everyone involved has extra motivation to act in accordance with the established guidelines.

{% hint style="info" %}
Click [here](/architecture/execution-transcripts) to view an example transcript.
{% endhint %}


# Common Truebit Use Cases

As blockchain, AI, and decentralized infrastructure reshape industries, trust in offchain processes remains a major challenge. Truebit Verify delivers a critical verification layer that ensures transparency, compliance, and authenticity where it matters most—offchain. **From tokenized assets to AI systems and decentralized networks, Truebit Verify empowers industries to reduce risk, enhance scalability, and operate with confidence.**

### **Use Cases: Industries Transformed by Truebit Verify**

<details>

<summary><strong>Real-World Asset Tokenization</strong></summary>

The majority of tokenization processes happen offchain. While blockchain technology provides transparency for on-chain transactions like minting, selling, and bridging tokens, the critical components that determine an asset’s value occur outside the blockchain, like:

* **Asset Valuation** – Integrating real-time proof of reserves and automatically verify financial statements
* **Asset Lifecycle** – Creating verified origination, underwriting and asset accounting processes
* **Token Management** – Building automated, provably compliant token management processes

By verifying document authenticity, ownership transfers, and regulatory compliance, Truebit Verify enables the creation of trustworthy tokenized assets that reduce risk, increase asset valuation, enhance liquidity through reduced transaction friction, and enable greater scalability through automated processes.

</details>

<details>

<summary><strong>Digital Assets</strong></summary>

For digital assets to reach their full potential, the processes managing them must be transparent and verifiable. Truebit Verify creates proofs that asset valuation, lifecycle management, and compliance processes follow prescribed rules.

This verification infrastructure enables:

1. **Higher asset valuations** by reducing risk through transparency
2. **Enhanced liquidity** through automated compliance verification, reducing transaction friction
3. **Greater operational efficiency**  through automated, verified back-office processes

From proof of reserves to cross-chain transactions, Truebit Verify provides the trust foundation necessary for sophisticated digital asset platforms.

</details>

<details>

<summary><strong>Decentralized Physical Infrastructure Networks (DePIN)</strong></summary>

**DePIN represents one of the fastest-growing Web3 segments, connecting physical infrastructure with blockchain incentives to create community-owned networks.** These projects, including wireless connectivity, compute resources, energy grids, and sensor networks, depend heavily on verified offchain data to maintain system integrity.

**Truebit Verify bridges this gap by ensuring real-world infrastructure inputs can be trusted within decentralized networks**. It verifies that compute-sharing participants honestly complete tasks, validates data integrity from IoT sensors, and provides cryptographic proof that service levels meet requirements in regulated industries like telecommunications and energy.

This verification layer enables transparent IoT data marketplaces where information from distributed sensors can be confidently traded and utilized. By ensuring all network participants operate with reliable information, Truebit Verify removes a critical barrier to DePIN growth and mainstream adoption.

</details>

<details>

<summary><strong>Supply Chain Management</strong></summary>

**Modern supply chains involve complex networks of participants who don’t necessarily trust each other. Truebit Verify transforms this dynamic by creating verifiable records of product journeys from origin to consumer.**

[The Quadrans Foundation’s FoodChain](https://truebit.io/truebits-traceability-solution-a-case-study-in-blockchain-powered-supply-chain-transparency/) exemplifies this approach, using Truebit Verify to enable transparent and tamper-proof tracking for food and textile products. By verifying data from IoT sensors, supply chain documentation, and cross-system interactions, Truebit creates a single source of transparent truth that builds trust without requiring centralized control.

</details>

<details>

<summary><strong>AI Model Validation</strong></summary>

As AI systems increasingly drive market-moving decisions, Truebit Verify provides critical validation for AI model inference. This enables transparency into AI-driven decision-making processes, creating accountability through verification of inputs, outputs, and execution paths for automated decision systems.&#x20;

**Truebit Verify establishes a transparent record of AI model training and inference, including input data, model parameters, and inference results.** **Truebit Certified Transcripts provide verification** that the model behaved according to expectations and provides a transparent audit trail for regulatory compliance.

</details>


# How Do You Intend To Use Truebit?

Truebit offers a versatile solution designed to support a variety of business and technical objectives which can be summarized as follows:

<table><thead><tr><th align="center">DEVELOP</th><th align="center" valign="middle">INTEGRATE</th><th align="center">VERIFY</th></tr></thead><tbody><tr><td align="center"><a href="/pages/4ZhJRneOlwgy6WZ7fknw"><strong>Developers</strong> who want to build with Truebit</a> </td><td align="center" valign="middle"><a href="/pages/VozXrtf7zwuNFj9h4XYA"><strong>Developers</strong> who want to connect their systems to Truebit</a></td><td align="center"><a href="/pages/rwielP19YwgrnXwlwo3u"><strong>Node Operators</strong> who want to contribute computing power to verify tasks</a></td></tr></tbody></table>

### System Actors&#x20;

Within Truebit platform, you will find **three main actors** performing different actions.

The use of Truebit Verify varies depending on the role within the system—whether as a **Task Developer**, **Task Requester**, or **Node Operator**.

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

#### **Task Developers**

They will use the Truebit Verify CLI to create, test, and deploy task code.

* **Task Development**: Tasks can be written in different languages.  Please check the [supported languages](/developing-truebit-tasks/how-to-create-function-tasks/supported-languages) section.&#x20;
* **Task Deployment**: Truebit provides a [Command Line Interface](/developing-truebit-tasks/truebit-cli-reference) to manage the task development lifecycle. The CLI makes it simple to build and test tasks locally and is used to deploy tasks to the hub.

#### **Task Requesters**

They initiate Task Requests by calling a REST API endpoint hosted by the Coordination Hub.

* **Task Integration**: Using a [REST API](/integrating-truebit-tasks/api-task-execution), Task Requesters integrate tasks into their codebase, including task metadata that sets runtime parameters.
* **API Execution**: When the API is called, the Truebit Verify Hub dispatches the task for execution and returns the Task output in response. &#x20;
* **Verification & Transcripts:** The hub dispatches the task to multiple nodes and verifies the results. Task Users can access a [transcript](/overview/what-is-a-transcript) for a given  executionID using the [Transcript API](broken://pages/v3Wms939vkv808A6Q76y).

#### **Node Operators**

Bring decentralized computing capacity online by installing Truebit Verify Node software within their environments and registering with the hub.&#x20;

* **Task Execution and Verification**: Nodes get selected by the Truebit platform, execute the task, and send task output to our platform according to the [Truebit Unchained Protocol](/community/truebit-unchained-protocol).
* **Economic Incentives**: Nodes receive payment for verified tasks. The adjudication process uses incentives and penalties to ensure that nodes provide honest results.&#x20;


# Getting Started Guide

**Follow our Getting Started guide to install the Truebit CLI and connect to the pre-configured Truebit Developer Node**, available for community use. **This platform enables developers to simulate the Truebit network’s execution environment**, ensuring optimal performance and reliability before deployment in production.

### Prerequisites

* [node.js: 22.13.1](https://nodejs.org/en/blog/release/v22.13.1) or higher
* [npm: 10.7.0](https://www.npmjs.com/package/npm/v/10.7.0) or higher

{% stepper %}
{% step %}

### Installing the Truebit CLI

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

Install the Truebit CLI globally by using the following command:

<pre class="language-bash"><code class="lang-bash"><strong>npm i -g @truebit/cli
</strong></code></pre>

Then, run:&#x20;

<pre class="language-bash"><code class="lang-bash"><strong>truebit
</strong></code></pre>

This command will verify the installation and accept the Terms of Use.
{% endstep %}

{% step %}

### Register Into Truebit

**Already Have An Account?**

If you already registered into Truebit, please follow the instruction below:&#x20;

Update the [secret.json ](https://secret.json)file located in the `~/.truebit` directory

```
{
  "address": "your-wallet-address",
  "privateKey": "your-private-key"
}
```

**Create New Account**

To setup a new Truebit account, please run the following command:

<pre class="language-bash"><code class="lang-bash"><strong>truebit setup 
</strong></code></pre>

You will need to accept the Terms of Use. Once accepted, you will see the following result:

{% hint style="info" %}
A new [secret.json ](https://secret.json)file containing your account information has been created at:\
`/Users/<username>/.truebit/secret.json`.
{% endhint %}

{% code overflow="wrap" %}

```
Welcome to Truebit Verify!

Your all-in-one solution to develop, build, test, and deploy tasks seamlessly.
Let's get started by setting up your account and configuring your wallet.
We'll guide you through each step to ensure a smooth experience.

**Important: Private Key Information

Truebit Verify employs a private key system to secure your account:

  - A unique private key will be automatically generated for you.
  - This key serves as your secure identifier within Truebit Verify.
  - It's used internally to authenticate your actions.
  - You won't need to manage this key directly.

We are committed to ensuring the security of your private key and safeguarding your account.
Ready to begin?
Press [Y] to proceed or [N] to exit: 
```

{% endcode %}

**Step 1:**

```
Step 1: Create an Account

It appears you're a new user without a wallet configured locally.

Would you like to create a new wallet now?
Press [Y] to proceed or [N] to skip:
```

**Once you type "Y":**

{% code overflow="wrap" %}

```
Setting up your new wallet...

Your new wallet address is: <wallet>

Your wallet information has been securely stored in /Users/<username>/.truebit/secret.json
Please keep this file safe, as it contains your credentials for using Truebit Verify.

```

{% endcode %}

**Step 2:**

To finally create an account, the system will need the following information:

* **Name**: Your full name
* **Verification Email**: An email address
* **Company Name**: Your company’s name
* **Job Position**: Your job position
* **EULA Acceptance**: Accept the End User License Agreement (EULA) \[ Y|N ]

```
Now that your wallet is set up, let's create your Truebit Verify account.

Please provide the following information:

1. Full Name: John Doe
2. Email Address: john.doe@example.com
3. Company Name: Acme
4. Job Position: Senior Developer
5.Accept EULA? [Y|N] (https://truebit.io/terms/): Y

Is the information provided above correct?
Press [Y] to confirm or [N] to edit: Y

By completing registration, you'll be automatically subscribed to our newsletter.
To opt-out, please follow the steps described in our documentation portal.

... registering your account.

Thanks for registering to Truebit Verify!

Congratulations! Your Truebit Verify account has been successfully created. 

Account Summary: 
- Name: John Doe 
- Email: john.doe@example.com 
- Company: Acme 
- Position: Senior Developer 
- Wallet Address: 0xfc046e7cd36ffff3e59642387dca6dcd76c9b355
- Namespace: J349oiAO // API Key: 0x109435FR78

Run 'truebit --help' at any time to get started
```

{% hint style="success" %}
If you'd like to view your personal information again, please run `truebit setup`.
{% endhint %}
{% endstep %}

{% step %}

### Working With Your First Function Task

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

**Download The Examples**

Clone the examples repository to start working with Truebit.

```bash
git clone https://github.com/TruebitProtocol/truebit-nextgen-examples.git
```

We have created example tasks so you can get familiar with the process of testing and deploying code. You can learn more about creating your own [Function](/developing-truebit-tasks/how-to-create-function-tasks) and [API](/developing-truebit-tasks/how-to-create-api-tasks) Tasks.

For now, we will use one of the examples ([Fibonacci](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/fibonacci)) to demonstrate how to use the CLI to test and deploy Function Tasks, and the platform's REST API to execute and verify them.&#x20;

**Build**

This command will build the Fibonacci task.

```
truebit build truebit-nextgen-examples/function-tasks/js/fibonacci/dist -l js
```

As a result of running the `build` command, you will receive a `TaskId`, which serves as the unique identifier for your task.

**Testing**&#x20;

This command will run the [Fibonacci](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/fibonacci) task and provide the result and total steps executed:

```bash
truebit start <taskId> 15
```

* \[taskId]: Add the taskId generated in the previous step.&#x20;

**Deploy And Register Your Function task.**

This command will deploy and register the Fibonacci task.

{% code overflow="wrap" %}

```bash
truebit deploy <namespace> <taskname> --taskId <taskId>
```

{% endcode %}

* \[namespace]: Use your default namespace registered in **Step 2 - User Creation**
* \[taskname]: Choose a representative name for your task. i.e: fibonacci
* \[taskId]: Add the taskId generated in the previous step
  {% endstep %}

{% step %}

### Executing Your First Function Task

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

**Execute The Function Task**

1. Access the Task execution Swagger UI here: [Swagger UI for Truebit](https://run.truebit.network/dispatcher/api-docs/).
2. Open the **/task/function/execute-by-name** endpoint and click **"Try it Out"** to test it.
3. Update the following parameters in the request body:
   * **namespace**: Use the namespace from **Step 3 – Deploy and register your Function Task**
   * **taskname**: Use the task name from **Step 3 – Deploy and register your Function Task**
   * **async**: Set to **false**
4. Add your API Key from **Step 2 – Register into Truebit** in the **x-api-key** parameter.

{% hint style="info" %}
If you don’t remember your namespace or API key, please run **truebit setup** again to retrieve your personal information.
{% endhint %}

**You should receive the following answer**

```bash
{
  "executionId": "08c717bb-f92a-4f43-96a7-940e9ef37983",
  "clearTextSolution": {
    "signature": {
      "v": 27,
      "r": "997e437a3c2828d141ea7038e68391ffa3bbc4447c5e03e72e90b981d12cf30f",
      "s": "3b503da5ba6225137ec6f546de93bbbe8a7092091c557ea1a3bc9aad27b3ba75"
    },
    "output": "6765",
    "status": "succeed",
    "senderAddress": "0x344462d1a0a3a61945aa9dd4c072df8caed1af86"
  },
  "status": "Success"
}
```

**Get The Transcript**

* Access the Transcript swagger UI here: [Swagger UI for Truebit](https://run.truebit.network/transcript-query/api-docs/)
* Use the `/task/{executionId}/transcript` endpoint, passing the `executionId` value obtained from the previous execution as a parameter

You should get the [transcript](/overview/what-is-a-transcript) associated with the given executionId.
{% endstep %}

{% step %}

### Working With Your First API Task

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

**Create-api**

This command will create the API task.

{% code overflow="wrap" %}

```bash
truebit create-api truebit-nextgen-examples/api-tasks/petstore-crud/manifest.json 
```

{% endcode %}

**Deploy And Register Your API task**

This command will deploy and register the [Fibonacci](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/fibonacci) task.

{% code overflow="wrap" %}

```bash
truebit deploy <namespace> <taskname> --taskId <taskId>
```

{% endcode %}

* \[namespace]: Use your default namespace registered in [**Step 2 - User Creation**](#step-2)
* \[taskname]: Choose a representative name fo[^1]r your task. i.e: petstore
* \[taskId]: Add the taskId generated in the previous step
  {% endstep %}

{% step %}

### Executing Your First API task

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

**Execute The API Task**

1. Access the task execution Swagger UI here: [Swagger UI for Truebit](https://run.truebit.network/dispatcher/api-docs/).
2. Open the **/task/api/execute-by-name** endpoint and click **"Try it Out"** to test it.
3. Add your API Key from **Step 2 – Register into Truebit** in the **x-api-key** parameter.
4. Update the following parameters in the request body and click on "**Execute**":
   * **namespace**: Use the namespace from **Step 6 – Deploy and register your API task**
   * **taskname**: Use the task name from **Step 6 – Deploy and register your API task**
   * **async**: Set to **false**
   * **input**: &#x20;

```
  "input": {
    "path": "/store/order",
    "method": "POST",
    "body": {
      "id": 2,
      "petId": 198772,
      "quantity": 7,
      "shipDate": "2077-08-24T14:15:22Z",
      "status": "approved",
      "complete": true
    }
  }
```

{% hint style="info" %}
If you don’t remember your namespace or API key, please run **truebit setup** again to retrieve your personal information.
{% endhint %}

**The following answer should appear:**

```bash
{
  "executionId": "fb8bbaf4-8fb6-49d7-b089-f22c37b0285e",
  "clearTextSolution": {
    "output": {
      "id": 2,
      "petId": 198772,
      "quantity": 7,
      "shipDate": "2077-08-24T14:15:22.000+0000",
      "status": "approved",
      "complete": true
    },
    "status": "succeed",
    "senderAddress": "0xd70c3454aad1b7ec660a064d8b1fe5708d898d84"
  },
  "status": "Success",
  "totalTransferredBytes": {
    "request": 220,
    "response": 438
  }
}
```

**Get The Transcript**

* Access the Transcript swagger UI here: [Swagger UI for Truebit](https://run.truebit.network/transcript-query/api-docs/)
* Use the `/task/{executionId}/transcript` endpoint, passing the `executionId` value obtained from the previous execution as a parameter

You should get the [transcript](/overview/what-is-a-transcript) associated with the given executionId.
{% endstep %}

{% step %}

### Explore Truebit in Action

By now, you’ve gone through the full journey: From installing and registering with Truebit to creating your first task locally, deploying it to the Truebit cloud, and obtaining a verifiable transcript. Now, it's time to see everything in action on a website.

To demonstrate this, we’ve built a [demo](https://demo.truebit.network/) page that executes a verifiable Fibonacci computation. **How does it work?** The page calls the Truebit execution endpoint and retrieves the corresponding verification transcript.

{% hint style="info" %}
We run a limited-capacity **Stake Sponsorship Program** to support selected node operators. If you’d like to be considered for an invitation, please submit your request via <http://forms.truebit.io/>
{% endhint %}
{% endstep %}
{% endstepper %}

[^1]:


# Introduction

## Architecture's High-Level Overview

**Truebit’s architecture combines a** [**Truebit Verify Hub**](/architecture/introduction/truebit-verify-hub) **with a network of** [**Truebit Verify nodes**](/architecture/introduction/truebit-verify-nodes)**.**\
The Hub coordinates task execution, verification, and transcript creation through secure APIs.\
Nodes provide the compute layer, enabling both developers and operators to build, run, and verify tasks.

## Truebit Verify Hub

**A cloud-based service that orchestrates the Truebit ecosystem.** It serves as the primary network interface for [Truebit Tasks](/developing-truebit-tasks/introduction), coordinates Verify Node activity, and generates execution transcripts in accordance with the [Truebit Unchained Protocol](/community/truebit-unchained-protocol).&#x20;

## Truebit Verify Node

**Nodes are hosts that execute and verify Truebit Function Tasks, subject to the oversight of the Truebit Verify Hub.**

They form the decentralized compute layer, executing and validating tasks under the Hub’s protocol oversight. Together, they create a hybrid architecture where coordination ensures efficiency and reliability, while decentralized execution delivers transparency, scalability, and trust across the network.

### How Do Nodes Work?

**Truebit nodes serve a dual purpose** within the Truebit ecosystem:

* First, it functions as a **"Development Environment"** tailored to [Task Developers](/overview/how-do-you-intend-to-use-truebit#task-developers). This aspect enables developers to build and test Truebit tasks during their development process. They can safely develop and test their code locally, ensuring its readiness before deploying it to the [Truebit Verify Hub](/architecture/introduction/truebit-verify-hub).&#x20;
* Second, the Truebit node can be utilized by the Node Operators seeking to **contribute their computer's processing power to the Truebit network**. These users have the opportunity to earn incentives by executing tasks for other users on the network.&#x20;

In essence, the Truebit node accommodates both Task Developers and Node Operators to participate and earn rewards within the Truebit network.

&#x20;


# Truebit Verify Hub

**The Truebit Verify Hub is a layer of services that coordinate the execution and verification of tasks.** The Hub exposes secure API endpoints, manages requests and responses, and orchestrates executions for each Truebit Task.&#x20;

### Truebit Task Execution

The Truebit Verify Hub provides a set of endpoints for Task Requesters to submit Truebit Task executions. Utilizing the Truebit unchained protocol, the Hub manages and coordinates task execution seamlessly.

### Transcript generation

The Truebit Hub will log each step of the task execution, offering a clear and verifiable record for any auditor.

### Invoice Generation

After completing the task, the Truebit verification hub generates the invoices related to the task execution.


# Truebit Verify Nodes

### Testing Truebit Tasks

Task Developers aiming to create Truebit tasks should utilize the Truebit CLI to build, test, and deploy their work. The CLI connects directly to a hosted Truebit Node, eliminating the need for developers to install the node themselves if they are focused solely on development. This setup simplifies and streamlines the development process. &#x20;

### Truebit Nodes Providing Decentralized Execution

#### Startup/Shutdown Process

Upon startup or shutdown, the node automatically [registers or deregisters with the blockchain](/architecture/audit-layer#node-registry-smart-contract) , ensuring its availability for task execution.

#### Node Selection Process

When a Task Requester executes a Truebit Function task, the Truebit Verify Hub selects a decentralized group of nodes responsible for verifying the task.&#x20;

The Truebit Verify Hub randomly selects a subset or union of Node subsets. This selection relies on random bits generated by concatenating three seeds: the Task Requester’s message timestamp, the Dispatcher’s message timestamp, and a recent, unpredictable blockchain block hash. These immutable and verifiable random bits are accessible to anyone with the task transcript and can also serve as optional inputs for the task.&#x20;

This process ensures transparency and auditability by preventing collusion between the Truebit Verify Hub and any registered Truebit Verify Node on the network.

#### Verification

During this phase, selected nodes from the "Node Selection" process will execute the Truebit task and submit an encrypted solution to the Verify Hub before the execution timeout. This ensures that any Truebit Verify node assigned to the task can access the response until all selected nodes provide the solution or the protocol initiates the execution timeout. Afterwards, the Truebit Verify Hub logs a "Solution revealed" message in the transcript.

#### Local Storage

To make sure the Truebit Verify Hub behaves in a trustworthy way, all the nodes store every message sent to and from the Hub. This way, if something goes wrong, like an incorrect payment to the node, it has all the information needed to dispute it.

All the messages are stored within the folder app/datadb.

The file names are defined as:

```
${process.env.LOCALSTORE}/${process.env.NODE_ENV}-${process.env.ADDRESS}-eventDB.json
```

This is the list of stored messages:

* `task_created`
* `node_outcome`
* `computed_outcome`
* `invoice` (Only for Function Tasks execution)


# Truebit Verify Control Node

## Non-concensus resolution

In the event of a **non-consensus resolution** from the Truebit Verify Nodes, where one or more nodes offer different solutions for the same task, t**he Truebit Node Control acts as a judge.**&#x20;

Truebit Node Control executes the task in the same manner as the nodes, providing a verifiable result to identify which node has made an error, ensuring transparency.


# Execution Transcripts


# Function Transcript

### Overview

**Transcripts** **serve as&#x20;*****certificates of compute*** — **immutable records** that capture every stage of a task execution. Each transcript offers a transparent and verifiable account of how a computation was performed, providing complete traceability and auditability throughout the process.

This example illustrates a **Function Task Execution Transcript**, where multiple nodes submitted identical outputs.

<details>

<summary>Function Task Transcript</summary>

{% code fullWidth="true" expandable="true" %}

```json
{
    "executionId": "657938a7-ebf1-4899-85ea-494fbca71123",
    "transcript": [
        {
         {
    "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
    "transcript": [
        {
            "type": "task_created",
            "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
            "message": {
                "type": "dispatch_task",
                "taskId": "rs_13e93c66863b2c02fe1ea690234134287cfde0cfc11fc63406dd6ef539e40099",
                "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
                "msgHash": "bd42f7387f91d4de78d2c357cf1e5882d2133e3231c7206d15a89c9fd8e05839",
                "signature": {
                    "v": 28,
                    "r": "571f1a796041afe2ca4e90b72ca3158270bab71f7a653760635ab40e545689b2",
                    "s": "4c3edb551ee89605d38ee4f87d341a970339034622650fa87906995dc6bf8a0d"
                },
                "limits": {
                    "gas": "60000000000",
                    "call": "65536",
                    "frame": "524288",
                    "memory": "1024"
                },
                "econParams": {
                    "reward": "0",
                    "requiredSolutions": 2,
                    "totalSolutions": 2,
                    "executionTimeout": 27000
                },
                "workers": {
                    "blockNumber": 47476800,
                    "selectionStrategy": "default",
                    "setNodes": [
                        "0x************************************0B1A",
                        "0x************************************EC4D"
                    ]
                },
                "dispatcherTimestamp": 1762363564,
                "taskRequesterTimestamp": 1744817190,
                "ledgerName": "evm",
                "blockHash": "0x************************************************************8eaf",
                "blockNumber": 47476800,
                "chainId": "43113",
                "nodeRegistryContractAddress": "0x************************************66Ce",
                "taskRegistryContractAddress": "0x************************************5f5A",
                "taskAuthorizationContractAddress": "0x************************************96E4",
                "taskRequesterAddress": "0x************************************7E42",               
                "taskPath": "/3891ca78/fibo",
                "taskVersion": 1,
                "senderAddress": "0xE3AcBBB129F14681C315028dB0A156597fb5058B",
                "input": "20"
            },
            "msgHash": "1f08d8165217b4eedc345317c7d586b63f41cdda72795116f3c43a894a80d998",
            "signature": {
                "v": 28,
                "r": "b514d9c39c8f490ced2533616e662ea03800b0fb4cac499a2f57ea89ce3e751c",
                "s": "5fc922c503e279ac9085957eae07b1d01fdd63d255eb616fa0ecc7b821629db0"
            },
            "publicKey": "0423fcbc3763e133bbec077378366887191b9dc7053bea44505ba7df8fa7d571be967f04e5246261884b3737ff94de900bca12aa41367138c033558d36d81b9299",
            "sequencerAddress": "0x************************************058B",
            "timestamp": 1762363564534
        },
        {
            "type": "node_outcome",
            "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
            "message": {
                "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
                "senderAddress": "0x************************************0B1A",
                "encryptedSolution": {
                    "iv": "4756cc5e25a080b4a262818a56ab5a2e",
                    "ephemPublicKey": "0411c83cb3e08a155c340a5e8dfc3ce205923b02c1acec4f800f04a531c9cef23fe61c56dcca58cd78ecbc65c868b77b57b6a3434acf5a325030127f906190125d",
                    "ciphertext": "6536310dd0d68d8f68bcebbb6ba92b0066e076401184190e3acc6686881116668cb21843a3fe5a97888b1080e3cec40e6341b4b3c540769b668baf78455168b5874a2fb0d24dcd22d3831b5b96fe20e2f3c2d2cedce8091994dd18c04f0b542bd6729c52ebc72b5ab4b05eb3a467b5e5649d9a2dc777c18f42f3ed6dab5fc415e7dc8e1226d0e56308a630b6cd509659b900ae34023456aaa6e1c22dd84ccf7e881c42001932c0e93dc4b84f6b82cd73394ec2adde7d47d40fc535e169784eb878c9745834cf570fbd98b8ce6cf9f92ae31db1619993d752dc517fc9356dc7cd779fb420d82ffd18d5f561f056a8fe4324130bd72b35bbe11a3e1a1f27c4f41a4ae59c2dfb44659158ab0e8fa51378d005ce00b7ebdcdef010a600147832a229d2e5a8d33cc4dd0cf80cb686aec1d72e7999e5432832b6dd77034c5c0a8ed3d5f0ef6595ae5ca4ba0180f340136e13f4eb29e819dadb095615a91937133bee4b6bc69f5807c0ff98a96e3724ba75fab59a4a171fdce058ddb5a5280ab942559b79a81a5dc0b9afe53cdc493f38760fb9237f28214d431384611851f0c692ce2c03c4eac73e733d79353cc09f9cec9b523164d208565733902e421777791b68167cdb77e36e9f27eb9fb4bd6f81a3604362b598af1ae43268258a3980ec419ca7",
                    "mac": "1c6481c1a1d3cf258733718f3b6ddc3b054ecc6d80cfedc47d5f427160dfbd0f"
                },
                "msgHash": "b24b5ce07f9e2850b3adc66c75e2f6d3ac324e881e447a41f727edbdefac7e15",
                "signature": {
                    "v": 28,
                    "r": "35e07888a376dca665c93061514081ffa887ac6db67a23f8afd989738551abd1",
                    "s": "4782beba6c2ca2c8a5f8e34baa43bb1fd4455ca60646912021c59b6a5e613493"
                }
            },
            "msgHash": "7df509e0d4a41817d4d1430198c0814ffe94efc9e5acfccba1832f1bac99a463",
            "signature": {
                "v": 28,
                "r": "a0248adca0a31db05406911907f5e5d27e7f3d353ef56a98dd327b3c1e232616",
                "s": "212d89091e27d343b393d7ba672df1830aa04bcc7c97643ddcb04d4a3fd96cc5"
            },
            "sequencerAddress": "0x************************************058B",
            "timestamp": 1762363564785
        },
        {
            "type": "node_outcome",
            "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
            "message": {
                "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
                "senderAddress": "0x************************************EC4D",
                "encryptedSolution": {
                    "iv": "bb2553f57a61e4667df2eb2349a07fcf",
                    "ephemPublicKey": "0434174e02cf111c643d29d255eb759c82b67aab92dec2351678b80d4668f2b45bbdd694055d63da66688ed217aa8b302316d6409cca544cd1f512d7ae305d2ec2",
                    "ciphertext": "f1a2c4326b834976a095555df6d1299d2412ec3f913aeea503c8dc7cb9b79eb75a5ddf9a61af063ef3e513e0da32b2ac9d2772ad5bdd6920eeda8f672aa0a2bd0c26591a87e61d23f689df6735a1bf6fdced3d82a5fa2958e430e03a461d192f3c803cd34359341ab88d01b886e5f47f3595ea850826ef7961da3a2ab186562a8864940aa4c4ae79ee48a58266c12beed6f8fef3ab4d57ae754fb951cce65868dc6d9118d03a9f58ccdffe3d3948c681162e4a50cbc29ea9832529e17857a41c18a2e514ad7150d953a30e0578e7462d52e3c34a42f1f75139256af721020444e1e082521121b86cdd02d08c0d9364a21c06795b345acdbf893da4282781c28a7a3489b3743bb740505c13e9d0059c0cd256a3628c87d4ca142793366e38cb418162e8b6d1c94ad84a0335cbf4a00067c68d16ab3dfc8787284a86ae8bfd6582118f00f0db7b735e7699e8cf29ee7671e4e6699ffaa1065ba5e1fa2cb454441aa7f7d956d858bb428ef25ffb3b8dbe41aec503a6a08a0404d3ad0e5507933f2e50f873e98a9ef014051f792ea1006d2459a1ab703d2115b6feb2e1e18e0334c93421d80b9692afc1fe69d978cb97d7ab649e0bad0350e0144947c205cacf5b7833d85abc4747902a08221b86eefccc335ca0636b61314bd4debd93872725dd2f",
                    "mac": "68f2fc468c5fe7c75a389544747c3f1fe1e95448d453d6128e4f0904d36a2535"
                },
                "msgHash": "de15db288f1833e1a929ef6bc1909dc9938c55def6bf3ea65521d7e1398ac6ca",
                "signature": {
                    "v": 28,
                    "r": "f151ca1a7e412c7901f3032fb99aef2d5b737bc08ddfc30dc213d99ccbe58484",
                    "s": "244f994a2b1d2a6b32b5e6d3c49f04cadba93b26151922f7ff6a25e2cffb1c6b"
                }
            },
            "msgHash": "5ed8219981143b87bd421388a676ee4365cbd85bcf70c6f15841de08164a73a8",
            "signature": {
                "v": 27,
                "r": "09dd841dc6653198fba75bdf7fd35b023c53fbb6d372c3c8cb826a30a57f37e5",
                "s": "033bb03d5506f1553c41e95858d461766326eb3a570353165311b9c431e314ee"
            },
            "sequencerAddress": "0x************************************058B",
            "timestamp": 1762363564788
        },
        {
            "type": "solutions_revealed",
            "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
            "msgHash": "cf98d061de3b32f9f292562e0e893c77c6a73f5042e854c66fb2469a4bd135de",
            "signature": {
                "v": 28,
                "r": "138fed323202d52c6f08a3a66e8e4b54422cf1ec0ee710302717f9da55e84e02",
                "s": "0563f71775a26499985bdc87619257dfa67527eb6cace9811a75bd845edbe359"
            },
            "clearTextSolutions": [
                {
                    "signature": {
                        "v": 27,
                        "r": "fd94598b19e9de38b5f36e5e0d88b596b9ba74d37c81dbc3999ffec5160a7983",
                        "s": "549ddc5207773d8b579fa0218d83e80ffddc8c1c53c9cd7850adb541de98d008"
                    },
                    "clearTextSolution": {
                        "output": "6765",
                        "status": "succeed",
                        "metering": {
                            "limits": {
                                "gas": 60000000000,
                                "call": 65536,
                                "frame": 524288,
                                "memory": 1024
                            },
                            "last": {
                                "steps": 7083189,
                                "call": 2,
                                "frame": 23
                            },
                            "peak": {
                                "call": 26,
                                "frame": 1677,
                                "memory": 18
                            },
                            "versions": {
                                "protocol": "1.120.0-beta.224"
                            }
                        },
                        "senderAddress": "0x************************************0B1A"
                    }
                },
                {
                    "signature": {
                        "v": 28,
                        "r": "8d88f742ef68acd6a39b796cdc59700283df430edb19902b6c99663a14d8483b",
                        "s": "6b2deba99026174dd9cd2aa3a47950eda6d3c7c4df62faab0393fcca4fcce8a2"
                    },
                    "clearTextSolution": {
                        "output": "6765",
                        "status": "succeed",
                        "metering": {
                            "limits": {
                                "gas": 60000000000,
                                "call": 65536,
                                "frame": 524288,
                                "memory": 1024
                            },
                            "last": {
                                "steps": 7083189,
                                "call": 2,
                                "frame": 23
                            },
                            "peak": {
                                "call": 26,
                                "frame": 1677,
                                "memory": 18
                            },
                            "versions": {
                                "protocol": "1.120.0-beta.224"
                            }
                        },
                        "senderAddress": "0x************************************EC4D"
                    }
                }
            ],
            "sequencerAddress": "0x************************************058B",
            "timestamp": 1762363564862
        },
        {
            "type": "execution_completed",
            "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
            "transcriptHash": "5e9a304e7a3c7bcd7af49a41a8ac5a91e181e6ed34b636ad0cd3c40d5a4642b6",
            "status": "ReadyForInvoice",
            "signature": {
                "v": 28,
                "r": "363361dc46d1215c26987c58b12af63d9d69f12c4e68e89bdd264d9e5b133462",
                "s": "7f7bd677791a2a60511be60d6c3f2cb12334b1bc7f9f54ac4a758a15780001c6"
            },
            "signerAddress": "0x************************************058B",
            "timestamp": 1762363564920
        },
        {
            "type": "execution_metadata",
            "executionId": "4eaccb5c-17a5-4a32-b0d8-9ff0df18f016",
            "message": {
                "version": "1.0.0"
            },
            "msgHash": "e91e71e1600a703f6008387487a0da2636b665a29458c75aea9a7638c5926409",
            "signature": {
                "v": 28,
                "r": "85c9b4eb4b8d30e3981be9f8fd76a0568697aaf43e1f219ed5e07310979470d0",
                "s": "3c4d0b39125c73f3282167a49594a5df0daef6754f338bb1f5889c1641164b3d"
            },
            "timestamp": 1762363565011
        }
    ],
    "timestamp": 1762363577084,
    "msgHash": "3188fc10a466a01842b396d603725fc998d694fb54acad61005c5b68606e29f0",
    "signature": {
        "v": 27,
        "r": "9c6565667e5a357725c425af182c07a79ac934c133ff93187a59c49429cdd338",
        "s": "5f0d0d9545775fc8f0e938cbf582813c54b21b1f88f5e3cefcefd089c2844cf5"
    }
}                    "iv": "abf4bfccb4a0b40eb00e3a0a20919000",
                    "ephemPublicKey": "0471d6cc1c87826bbe2fb12885de4dc0de471ff572c1a848f87631b600da041cd0c62f82d89127b8370250a9d25488d56bba6a7853a28bcd0d1d43d51c1811c119",
                    "ciphertext": "5df2ccbf2098e5b4c8ad84955963667625eb83f7cd8b48a82fa31ddfd19892aefcbd1d70086bb119f8505dabba2ac7202b36d9a621de27b5de7a25620b19e87b6f083253c768b26af378ce9012f73e10179f376ce4dc7c383aa0dc371c066552486803f46026d79c9a65ab949d1f170c14d97096577295f86380c5ac9ed6adb6280877910ac578abdb7cd2bbff96ad9c1206d51569d2d0250a6c8d54e9b38919faa0f4b73f3fe08887a9fcab353a9636ac3975abbae7293e110fabfd4f446c5765ea2b534b5504521f87d56e1c1824742ab3eae5d53365bd09de7ffa4d74f01bcf221ddb6a1cb387c0566fc5bb74af1b17a19b11f1a140de0f98c887288cd2512fc6d000ee2104d2f0a68af77425d96352941b32cb32e7752600b54e77873e82ce17f39de6b0c138c1c135c40e9ce81bcae1bb62f222c1a2ccd0f7c7f100c50978239668a3f32ecf8940c53c7d4c4bd10dec3e9db7b3fa8179f3552f65839d4928aca17baf46a7684335b05d6ca32786b56a1bba727289608f1e76b6797001f97509c05af1ba894b01980b85f2c79a161235168fd77db2f90482f10c897564d9f572308757dc69aece0e0b77e87c4905d3237f9ac82b0be5de256fbca30b7a797c95e8700ffd93ae17e1210ccdd5d37d",
                    "mac": "b5ad4c7f9627c4760c3cf806688bfa52c38eb80c2970730d1d49ca6fc2a90eaa"
                },
                "msgHash": "825479530f1ac744573d03c3d65d4b45629bf276a88c5c96a84e093014908c6a",
                "signature": {
                    "v": 28,
                    "r": "b797e68762cd7df235d942b349ac8020a738f94bf63c7a5d7da0e842461021e3",
                    "s": "1af6f7af901ea1526896601a9d5300247eb7e19f39604938444bca9c1e05f71c"
                }
            },
            "msgHash": "8a2881c958f06b068a0384d44a7cd911130c77c3dd692df3106c23843c2a5abd",
            "signature": {
                "v": 27,
                "r": "15e5eef9c4465bc2a948ca4d7de734c93cf9a4aad481db2b7457733ff1206ce8",
                "s": "189351ce08b39bff61bfd6cd677f6d23925d9275944677972c2f94bff0df4972"
            },
            "sequencerAddress": "0x************************************2266",
            "timestamp": 1717686205848
        },
        {
            "type": "solutions_revealed",
            "executionId": "657938a7-ebf1-4899-85ea-494fbca71123",
            "msgHash": "a8f8eca9b0f25c0e76662a9e8e0899541f785717193e9887db3b2adf1199ab30",
            "signature": {
                "v": 28,
                "r": "4fcad130489b95545d464e4dd5ee872bcfb40ba78e8d02b691bfdb509b607e10",
                "s": "5c58b407f5271a8729b224941632004df4a9884c719fc3ca4f18d1c262616693"
            },
            "clearTextSolutions": [
                {
                    "signature": {
                        "v": 27,
                        "r": "cf46300186ff01fcf90720a6475d3ca1c924abf9d348e2d6081e2cb1c38d3e16",
                        "s": "37ad0e079462cfa47a281ae490e192a1b1e23d5ae11c1ca6171364f36acfd290"
                    },
                    "clearTextSolution": {
                        "output": "13",
                        "status": "succeed",
                        "metering": {
                            "limits": {
                                "gas": 1099511627776,
                                "call": 500000,
                                "frame": 4194304,
                                "memory": 256
                            },
                            "last": {
                                "steps": 1628060352,
                                "call": 3,
                                "frame": 9
                            },
                            "peak": {
                                "call": 219,
                                "frame": 1407
                            },
                            "versions": {
                                "protocol": "1.84.1"
                            }
                        },
                        "senderAddress": "0x************************************79C8"
                    }
                },
                {
                    "signature": {
                        "v": 28,
                        "r": "04ac644f10bbe15aaef05cb6f8b01c7af575b679d45f85eaaf0da2be8a61fcc5",
                        "s": "202f83bb698cd8541cf1f91a930514478f85e87d869237c839882aab72ca720f"
                    },
                    "clearTextSolution": {
                        "output": "13",
                        "status": "succeed",
                        "metering": {
                            "limits": {
                                "gas": 1099511627776,
                                "call": 500000,
                                "frame": 4194304,
                                "memory": 256
                            },
                            "last": {
                                "steps": 1628060352,
                                "call": 3,
                                "frame": 9
                            },
                            "peak": {
                                "call": 219,
                                "frame": 1407
                            },
                            "versions": {
                                "protocol": "1.84.1"
                            }
                        },
                        "senderAddress": "0x************************************b906"
                    }
                },
                {
                    "signature": {
                        "v": 27,
                        "r": "f9e25227fdc47f5f8440712e0800b2ea6ffd21896256eaeef8d09b6af4fe08bb",
                        "s": "78e30985d524242d1ccddffa1f687387e2657fed201102732af67e8c1ee1aa95"
                    },
                    "clearTextSolution": {
                        "output": "13",
                        "status": "succeed",
                        "metering": {
                            "limits": {
                                "gas": 1099511627776,
                                "call": 500000,
                                "frame": 4194304,
                                "memory": 256
                            },
                            "last": {
                                "steps": 1628060352,
                                "call": 3,
                                "frame": 9
                            },
                            "peak": {
                                "call": 219,
                                "frame": 1407
                            },
                            "versions": {
                                "protocol": "1.84.1"
                            }
                        },
                         "senderAddress": "0x************************************b906"
                    }
                }
            ]
            "sequencerAddress": "0x************************************2266",
            "timestamp": 1717686205894
        },
        {
            "type": "execution_completed",
            "executionId": "657938a7-ebf1-4899-85ea-494fbca71123",
            "transcriptHash": "ebc2f5fc248991e9f570c255140e1154f08962dc0bdc997ff67d5f37435e72d9",
            "status": "ReadyForInvoice",
            "signature": {
                "v": 28,
                "r": "4c12ca5b2e33d5566e3ec14742562b1df785f30f8c48a48bece1ac6eb2e762da",
                "s": "5fe6808bf5eaf948eb35ba1ed3e33f1d83174b5ce16c247a3f8f33a78f6cdeed"
            },
            "signerAddress": "0x************************************058B",
            "timestamp": 1717686205918
        }
    ],
    "timestamp": 1717686229391,
    "msgHash": "b058423ba3b27e8e75a126277ece339be9e2703f15131d5610bd1cdb08c8e279",
    "signature": {
        "v": 27,
        "r": "cb660c29b11012d0371d446f0eed9c6339eb09779b1d0f4910fe318bfda61554",
        "s": "58a1eb8d91f9c0b17f358dfdece56d266e9b20cfe857c079a6f9d1e066a47c98"
    }
}
```

{% endcode %}

</details>

### Execution Lifecycle Messages

<details>

<summary>root message</summary>

This `root message` is the first entry recorded in the execution transcript. It contains key information such as the **execution ID**, the **timestamp** of when the task requester initiated the execution, and the **hash** representing all the messages contained within the transcript.

<table><thead><tr><th width="201">Property</th><th width="331.3333333333333">Description</th><th>Values</th></tr></thead><tbody><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td><a href="#execution-lifecycle-messages">transcript</a></td><td>List of all the messages generated during the Function Task execution</td><td>Array</td></tr><tr><td>timestamp</td><td>Transcript query request timestamp. The moment when the task-requester calls the transcript query endpoint.</td><td>unixTimestamp</td></tr><tr><td>msgHash</td><td>Transcript Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr></tbody></table>

</details>

<details>

<summary>task_created</summary>

The `task_created` message is added to the transcript when the Truebit platform receives a new execution request from the task requester. It contains key information such as the **execution ID**, the **original message** sent by the requester (stored in the **message** field), and all data is **signed by the Truebit Verify Hub**.

<table><thead><tr><th width="188">Property</th><th width="309.4934895833333">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>task_created</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>message</td><td>Original message received from the Task Requester</td><td>See Below "dispatch_task"</td></tr><tr><td>msgHash</td><td>Current message hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>publickey</td><td>Truebit Verify Hub public key</td><td>Text</td></tr><tr><td>sequencerAddress</td><td>Truebit Verify Hub Address</td><td>Text</td></tr><tr><td>timestamp</td><td>task_created message created timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Original message sent by the Task Requester:** `dispatch_task`

<table><thead><tr><th width="202.1640625">Property</th><th width="255">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>dispatch_task</code></td></tr><tr><td>taskId</td><td>Function task ID</td><td>Text</td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>msgHash</td><td>Current message hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>limits</td><td>Function task execution limits values</td><td><ul><li><strong>gas</strong>: Maximum amount of steps allowed for task execution.</li><li><strong>call</strong>: Amount of Nested calls allowed for task execution.</li><li><strong>frame</strong>: Stack memory allocated for the Calls during the task execution.</li><li><strong>memory</strong>: Amount of memory used by the task execution</li></ul></td></tr><tr><td>econParams</td><td>Economics parameters for the function task execution.</td><td><ul><li><strong>reward</strong>: <strong>TBC</strong></li><li><strong>requiredSolutions</strong>: Min amount of solutions to get a validated result.</li><li><strong>totalSolutions</strong>: Total amount of solutions to get a validated result.</li><li><strong>executionTimeout</strong>: Amount of execution time before it gets canceled.</li></ul></td></tr><tr><td>workers</td><td>List of <a href="/pages/Qjyn9U72trbcM4wR0Mxa">Truebit Verify Nodes</a> selected to work on this function task rxecution</td><td><ul><li><strong>blockNumber</strong>: number</li><li><strong>selectionStrategy</strong>: [ "default"]</li><li><strong>setNodes</strong>: Array of nodes</li></ul></td></tr><tr><td>dispatcherTimestamp</td><td>Dispatcher timestamp at the moment of receiving a new task execution from taskRequester</td><td>unixTimestamp</td></tr><tr><td>taskRequesterTimestamp</td><td>Timestamp specified on the task execution request by the TaskRequester</td><td>unixTimestamp</td></tr><tr><td>ledgerName</td><td>Current ledger in usage</td><td>['avalanche']</td></tr><tr><td>blockHash</td><td>Current block hash</td><td>Text</td></tr><tr><td>blockNumber</td><td>Current block number</td><td>Number</td></tr><tr><td>chainId</td><td>Unique ID for blockchain identification</td><td>Text</td></tr><tr><td>nodeRegistryContractAddress</td><td>Node registration Smart contract Address</td><td>Text</td></tr><tr><td>taskRegistryContractAddress</td><td>Task registration Smart contract Address</td><td>Text</td></tr><tr><td>taskAuthorizationContractAddress</td><td>Task Authorization Contract Address</td><td>Text</td></tr><tr><td>taskRequesterAddress</td><td>Task Requester address. This address will pay for the task execution</td><td>Text</td></tr><tr><td>taskPath</td><td>Provided path for task execution. It must contain the namespace and taskname</td><td>Text</td></tr><tr><td>taskVersion</td><td>Provided version Task for execution </td><td>Number</td></tr><tr><td>senderAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>input</td><td>Function Task Input parameters</td><td>Text</td></tr></tbody></table>

</details>

<details>

<summary>node_outcome</summary>

The `node_outcome` message is recorded in the transcript each time the Truebit Verify Hub receives a response from a Truebit Verify Node. It includes key information such as the **execution ID**, the **original message** from the node (stored in the **message** field), and all data is **signed by the Truebit Verify Hub**.

<table><thead><tr><th width="203">Property</th><th width="292">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>node_outcome</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>message</td><td>Original message received from the Truebit node </td><td>See below "computed_outcome"</td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Node signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>sequencerAddress</td><td>Truebit Verify Hub Address</td><td>Text</td></tr><tr><td>timestamp</td><td>node_outcome message created timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Original message sent by the Task Requester:** `computed_outcome`

<table><thead><tr><th width="203">Property</th><th width="292">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>computed_outcome</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>senderAddress</td><td>Truebit Verify Node address</td><td>Text</td></tr><tr><td>encryptedSolution</td><td>Encrypted solution submitted by the Truebit Verify Node using the Truebit Verify Hub public key.</td><td><p>"iv": Text</p><p>"ephemPublicKey": Text</p><p>"ciphertext": Text</p><p>"mac": Text</p></td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Node signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr></tbody></table>

</details>

<details>

<summary>solutions_revealed</summary>

The `solutions_revealed` message is recorded in the transcript once either the required number of node responses has been received or the execution time has expired. This message includes key information such as the **execution ID** and all the **solutions provided by the nodes**, presented in an **unencrypted** form so that anyone can review the submitted results. These responses were previously **encoded** to prevent premature solution disclosure while the execution was still in progress.

<table><thead><tr><th>Property</th><th width="289">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>solutions_revealed</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>clearTextSolutions</td><td>List of all the solutions provided by the selected Truebit Verify Nodes.</td><td><p>Array of</p><p>[</p><ul><li>signature: Node's signature</li><li><a href="#cleartextsolutions-message">clearTextSolution</a></li></ul><p>]<br></p></td></tr><tr><td>sequencerAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Information stored within the clearTextSolution message**

This array will contain an unencrypted list of all the messages received from the nodes

<table><thead><tr><th width="184">Property</th><th width="289">Description</th><th>Values</th></tr></thead><tbody><tr><td>output</td><td>Unencrypted node solution</td><td>Text</td></tr><tr><td>status</td><td>Node execution status</td><td>[ "succeed", "Failed"]</td></tr><tr><td><a href="#metering">metering</a></td><td>Metrics used for the execution</td><td><p>Array of </p><ul><li>limits</li><li>last</li><li>peak</li><li>versions</li></ul></td></tr><tr><td>senderAddress</td><td>Truebit verify Node Address</td><td>Text</td></tr></tbody></table>

**Metering message**

<table><thead><tr><th width="184">Property</th><th width="289">Description</th><th>Values</th></tr></thead><tbody><tr><td>limits</td><td>Limits values specified in the dispatch_task message</td><td><ul><li>gas</li><li>call</li><li>frame</li><li>memory</li></ul></td></tr><tr><td>last</td><td>Actual <strong>last</strong> values consumed during execution</td><td><ul><li>gas</li><li>call</li><li>frame</li></ul></td></tr><tr><td>peak</td><td>Actual <strong>peak</strong> consumed during execution</td><td><ul><li>call</li><li>frame</li></ul></td></tr><tr><td>versions</td><td>Truebit protocol version</td><td><strong>protocol</strong>: Truebit protocol version number</td></tr></tbody></table>

</details>

<details>

<summary>execution_completed</summary>

The `execution_completed` message is logged into the transcript once the entire execution process has been completed — whether the task was resolved through **node consensus** or required intervention by the **Truebit Control Node** during the **Non-Consensus Resolution Process**.

<table><thead><tr><th width="234">Property</th><th width="256.1328125">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>execution_completed</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>transcriptHash</td><td>Execution lifecycle messages hash.</td><td>Text</td></tr><tr><td>status</td><td>Final execution status</td><td>["ReadyForInvoice", "Error"]</td></tr><tr><td>errorDetails</td><td>Only present if there was an error during the execution.</td><td>The details of any error thrown by the protocol or its services</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>signerAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Execution complete statuses**

| Status          | Description                                                                               |
| --------------- | ----------------------------------------------------------------------------------------- |
| ReadyForInvoice | The task execution finished, so the protocol is ready to process the execution's invoices |
| Error           | There was an error during the execution. Please check the **errorDetails** field.         |

</details>

<details>

<summary>execution_metadata</summary>

<table><thead><tr><th width="234">Property</th><th width="257.03515625">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>execution_metadata</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>message</td><td>Truebit Protocol version</td><td>Array of<br>["version"]</td></tr><tr><td>msgHash</td><td>Hash that represents the message</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

</details>


# Non-Consensus Transcript

### Overview

In a **Non-Consensus Resolution Transcript**, the participating nodes initially fail to reach consensus on the task result. Each **message** within the transcript represents a specific protocol step, detailing how nodes interacted, exchanged results, and how discrepancies were detected and addressed.

This example illustrates a **Function Task Execution Transcript in which multiple nodes submitted differing outputs**. Since responses were inconsistent, the system initiated an **adjudication process** — a verification phase designed to identify which node produced the erroneous response. Through this process, the correct output was established and certified, ensuring that the task requester received a final, verified, and trustworthy solution.

<details>

<summary>Function Task Transcript</summary>

{% code fullWidth="true" expandable="true" %}

```json
{
  "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
  "transcript": [
    {
      "type": "task_created",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "message": {
        "type": "dispatch_task",
        "taskId": "rs_23078871426ac1b8aca9d018638057a9af53b3d45e6fb79aeaa5183a8fc39d14",
        "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
        "msgHash": "706ac0a5ce1c9f2cf639169e662695e8d56ec46862f63ee05e342d5a1830bdd4",
        "signature": {
          "v": 27,
          "r": "c18facb8f7426abef99230d7c7645e8f537e98bd1514435e6a00585aa7f1cd3c",
          "s": "5aea4449077acceb54dc14d8a716799b5d317de0cc8825dd4ba31d6a81ba7fc9"
        },
        "limits": {
          "gas": "1099511627776",
          "call": "65536",
          "frame": "524288",
          "memory": "1024"
        },
        "econParams": {
          "reward": "0",
          "requiredSolutions": 4,
          "totalSolutions": 4,
          "executionTimeout": 30000
        },
        "workers": {
          "blockNumber": 70259248,
          "selectionStrategy": "default",
          "setNodes": [
            "0x************************************3F36",
            "0x************************************FB34",
            "0x************************************ad50",
            "0x************************************aF86"
          ]
        },
        "dispatcherTimestamp": 1760379056,
        "taskRequesterTimestamp": 1744817190,
        "ledgerName": "avalanche",
        "blockHash": "0x************************************************************c648",
        "blockNumber": 70259248,
        "chainId": "43114",
        "nodeRegistryContractAddress": "0x************************************3efC",
        "taskRegistryContractAddress": "0x************************************5f5A",
        "taskAuthorizationContractAddress": "0x************************************96E4",
        "taskRequesterAddress": "0x************************************C8F7",        
        "taskPath": "/69e0edc0/fibo",
        "taskVersion": 1,
        "senderAddress": "0x************************************058B",
        "input": "20"
      },
      "msgHash": "982242e3d07b0e28cf60ac5d3af129e79d873b94ca31f4e0f56aad541b80db9b",
      "signature": {
        "v": 28,
        "r": "de246e3438bd04dc9a3ff759cca71c4d28bf87a2040b5210c44da772184d8b95",
        "s": "7b13fa7de90a9762df826d434217097294d5f6178680dc4236906c7acc3d40cb"
      },
      "publicKey": "04ada802731c637d7275175737881b937c6b107d2c4aef080d387f28ac74f79dc33e0e83759ffe621ee24c8268d25d1abd90e6986476499d0866a2339270e2582b",
      "sequencerAddress": "0x************************************2F7b",
      "timestamp": 1760379056939
    },
    {
      "type": "node_outcome",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "message": {
        "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
        "senderAddress": "0x************************************058B",
        "encryptedSolution": {
          "iv": "ce53172f57cd4f9fcec9584756067cb7",
          "ephemPublicKey": "0427db1fefeedbcaa395107f7b2c5409dc156064b4d67877ff1ddd8d180679033345fb933dc874ca17c763d99f075318b32feeac9e74e6a41bae12d47ca206d168",
          "ciphertext": "673045913c213f9b0892edda574621192d05710c9718428d9f144b02122cb22d3d316370662e5bbcf1e511cd33202279b7128e65c0edc20367fcb4175cc56a74ff0253910bb647925aaad1244b46ba599b8e733681ce01426dc86047d51d7e79070219d790fc0e855d4621129b260d7288ec50bb85e5994a890bff41cfa3f71ddf041cebf612dd15f43d8b437a881fbf9b5eb4a96f39b404dc0a29b4fbef671a34c7a50f497e12614e80114d6fda206ddc6647c66638c9ea6bb09b6b48e6019469046883ae30b9ef7b48f1f0b93ca50179cf3685a559903debd46455818665e9a99db970ec6e3cc3da4cf69c497897c824cd417f219c5de5531ae548ef2cb89c58f45e08aec8ac7878fdc3285f1502f58b4df5aff9772ab3fe546aeb0bbbff55d709faba0e1a7c62188405c80a20b43522778a86c3c69a41ac0f735b310cb1613949c83958c774092eb7ec33c0b664c7809fa91560496848a172d7a68a76cae127d4196f0e30c067bf1c7b26a482810fab83299f49e34875047e41c7a1df8062e3ded7e1fb0152f0d44f61e2e1953e6339215b44c44e8db672a6b4b18b5afabbcd7b50c01e136986159bf49255eb37050905444e9694faa3df610c1d27868978b0c95a4b223739bbfc3eb1e49fc10090d293d157d716876e370aeb6e59242159",
          "mac": "5c3d38f9956d57c4d4c001ab4ee9624673bbaaa7bccaa6e7d5c61268dc144bed"
        },
        "msgHash": "fe5201fbea699696a539f86ac71a7336cd8594b39ef45ca5e43e2983129fe327",
        "signature": {
          "v": 28,
          "r": "8c24812005a71ed83338ccdf3308c138c38d23839552ba2c10d33a3407a6c4fa",
          "s": "1c4ae94e7442f88473f7f6da5a189b51951d49d03709b1082d88f375e72ab9d8"
        }
      },
      "msgHash": "8cdf5bb515dacf9d5fa1bd72c58de80ac9de81cf6947a242baefa9e09504607f",
      "signature": {
        "v": 28,
        "r": "77105d7d29f662ca52a283ebed283477068c51ba2f2878c62ddc7f1d2d491991",
        "s": "61b5ab580da0905d33f290dce8cdc23822c1e9a208949e71af94afe38613582d"
      },
      "sequencerAddress": "0x************************************2F7b",
      "timestamp": 1760379057169
    },
    {
      "type": "node_outcome",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "message": {
        "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
        "senderAddress": "0x************************************ad50",
        "encryptedSolution": {
          "iv": "6d390967234c46a624fbf455f7093a9a",
          "ephemPublicKey": "04e4705f4b2361ca0c4c5272d63eecfb08e84bf4819f68c864910641e940d1593a1a164948360a9873d2d4a7f204dcaabccae9dc010cfb1956279e66f01401cb7f",
          "ciphertext": "c42e7656d9628b43d2f25ee1593ee6c6fc98b84c916928355030ca25b851a430f67ab39a7e884141e798afe39ac0a5716b19fc16f446a778c48444d28bb5f4c28d2a018003a08a86e0420307dff68971ef96cfc5ead26be54af056b41eb34b66326cce9b4b80e410280eb19a978aa95dc19400a11b32f79a6cddc91b55a2f13e3b2b8f48c23be2a353a8c3c3761882a931291a6ca39383ba991378c7a1859c0d33374020eec27e1a0651b0b36e07c609f74936007ea7322fe9d98dcc23485de18f61443f75d81482f9229609a4735c7bda35e401542236b6a7185f3486f85be5ae8c269109006abb40d1b6cce318e41574bbfabd041cc335e9ac68764d8bee3b7a99a06424fc6ea879ac2f8d4681eb59f9c3272aa287b7cc994e1426935839ecba152831708e2b97f3a3daccebdf577594edd4cfd3fedb72ddf639f326a976b7398ed3b730dcfe0e851f0292c8d5383bd99fcb2ccf862a7b7294cb8cbaf44c3b0c092d5f8734e02dc968d852c62c680744fad7231b179cd736737759286cc4fafd19729fa586f6260fd5df5076cf3d280d76d1bed96fbb22b5c120d679280eef06f835f9809ab2ba8eb06356f1f7076af222c9512e32713d140dd40100ca2abbc6e3798093a0d99de7796c98c987fd8b667c833dc74c8f422c7fe0c0b70598eb",
          "mac": "3d31e0c51330667596a8c30fa91f364ac3c5eba31db0395144ba45836ac2ddd7"
        },
        "msgHash": "53bc91e55362fdc625b0a129e420bbf187c9cafa44dd6ca425591ddbc0a7787f",
        "signature": {
          "v": 27,
          "r": "ec3067e9b008aea66f46c269d4fbb4238d43d3641693db6a2ed17e3f7fa7f0aa",
          "s": "1b33ffbb15972de3f529bab0d27a7c8924fa66171ce01643e7a7fc16a61ebdb0"
        }
      },
      "msgHash": "846a1fb5b50882f48d7cc247d9563a3d6487f21e2091f5573426578bf87eb5ef",
      "signature": {
        "v": 28,
        "r": "9945c37377df4b840ac1937b2ea8cf444baef0522ce6cb59e238be7353976b62",
        "s": "7a88bbaf2dcbe01f82d8366a9698188adcc7d0dff63f401f1e02200b1eca6c19"
      },
      "sequencerAddress": "0x************************************058B",
      "timestamp": 1760379057170
    },
    {
      "type": "node_outcome",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "message": {
        "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
        "senderAddress": "0x************************************aF86",
        "encryptedSolution": {
          "iv": "7048f26ace5f49e67b408affadc86c78",
          "ephemPublicKey": "0472a6ef6d62447ad04eba62ce763dff911a63d11af05b72b1ecd3c41ff1c84801fe0626c2bb939c1508a9f72d5116a37ee271eeff95e027f94228f0704a4199f6",
          "ciphertext": "5f9f58b48d97119aeeb1b4847dfe2f0541ff9f9aedc7a1d7b1cac3a31a68490cd05da1d191010c314d366f0d6f07812d3916675a543f378a007de1dc002f25b82eb20cde082b6e3e549306a6c0cbb6715e09609e749587a48e808e373eb0ffc23fd4915b6b9ac254b7779e46adb0665e9b614ea2f1907290467b6f9475aa2928df6678a0cdbcd0b5c56f07bae7a5216d64e9b21fc010952e79e2ea364d73c1587063834fe17b9dcecd19560165f3781d7c545df6454b08ff809c75bdbbd617b9fd9721dd04fce469fde6c859c16178a20e90fd7e65c5aeb7d2fda14a6dc9143f1efc933d71d423712fe531fd914ed67693445d6cd67737d993f82fa1f208d2bcc4403b2eae5108dfb19eeb2cea8b5cf7a33a40664bbfea13f6fc283e6e08d914bdeae98c8af5d1ee3f3f70eaf94b48718a9711926e067ad9a291195bbe4b1dca6e18009d5803b86d374628d001de1b8953cb4c157b3fe0b915bddba4936b3b9a023122410a4c3f907160c12cd3e16dac1f877ceddab9a1ebc3c9b2fd74f524bc32ef891be85c7f133973a708d982f1dc1d1661a7dabe3903358b7ce9830dff4c421c6f3277b8eb77b6da12806e0780abc9b92bc076197ebbe77f070a76e965ef311df09416d545a77dbf6f1ba557047210b287e54046aa7b2b0738956de4f8f5",
          "mac": "28f84ff26003854c23be8b1d24686fef1586aedca6a2eba56c0de55c510b1c38"
        },
        "msgHash": "8aebc39cac2b8792740526ff24cdadf630352033f2a1fba28b0010cf1d62f6d0",
        "signature": {
          "v": 27,
          "r": "42f20b62f4471e19f45a2b6b47d27c9d96fb6e02ab00b8e26af76b6bed8330ec",
          "s": "2bc02b270da99e5a8203307f5cc95253aee73800e1d13ab2adf3221c08040217"
        }
      },
      "msgHash": "f1c7d48b37ccfaa01a9b24a4d51287d7c41774b352dfb96dbe69f6b5e6ae10d1",
      "signature": {
        "v": 28,
        "r": "98deeb7e35dbf56532d4c67294aae0f749fb2f1bd0a8455ce986abb316b76734",
        "s": "24769fcacadab127bd37763ba42136c3b2c2ea58be866bbf4424f73556a28d18"
      },
      "sequencerAddress": "0x************************************2F7b",
      "timestamp": 1760379057179
    },
    {
      "type": "node_outcome",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "message": {
        "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
        "senderAddress": "0x************************************3F36",
        "encryptedSolution": {
          "iv": "17ad11ce2d796615c2b563acabbe6103",
          "ephemPublicKey": "04800e99cf99747485aa535513b5e4253b985ca07df06d50323ad8a045b532b456949cd2e7b411319a554a62d0069908531eef0e44f351f4ee9728c4af856b25e3",
          "ciphertext": "1b649d471271c519c97871dab7ae17eed6207c6a13c1c66184ade370cb3d550be08e01c7f3cc1dbbbf98622388a7956790747e5301e5ccac7ae849903bb0b0a59ed33ee7cd5d5f4eba5820e62a59322604f5962af49489877a40dab70f86d251af6e05ad7bcba409cc2e514d2875f4902838ec1ace5525aad56a2059f04ab9b4a5a1c3fe7d5925322d90ba4c6e0623b1d01600b95d5a5c9ccacd9a2277bac945d0581e2a6ce73f0d9c5dbcc1dfa094464d9876b47d0794725a1704b692e6a17f13932eec93f3ba37619b9f1f736171d14fb62e41b2078960a52c66d525a16f394798cd6e57746ecce067a5608db1dfdf6bf662cdd5afaa4714e5c5aaa4bf7b21574ec536e596dc7f2914fffad5bc0f61133cb57a7700f903b983b105a20095b68b648695b9747a76261a710ec48cbcf2943e11c4939adf1bfd093b393635773bd29739717e3a75897de221fc8dfb7ea6d5fd7a0399ba41acaf4da9d8ce2acf9a67ea4288e94383d216c9c3ddb4b969e9cd0cc6784ea5a8e1b9cba404d41a7b7884eec4c1b91c75d6e88f73a24770679c229aa3e206d2475ff5d3c879d6f5f8c0763d242a83fa31df55575f2021b221cebadd24a0c085cee7b5c7f8fa4d1b14c9ff2c95ff5793a59f841e497c9a1e5ded2a400162b11318facb0fc11f78ff2d0a",
          "mac": "76ebc4d8260de9da2fd2b27cd15f8932d8d89f4bc4240e53951184fb0e93dff8"
        },
        "msgHash": "822c1664ae370ee8c133c3780d972d05dc6e384f2ec89dbaabda8b44a7d7eef5",
        "signature": {
          "v": 28,
          "r": "9b56d134e67fb0916314dc96a4a3382d052978897314a6e8c3db5f7977db00f1",
          "s": "047b36cd2d424b5410db100c4f186f49b1c5e8999348915f82749cbfce8394a5"
        }
      },
      "msgHash": "e2a374efb229d18feba348528511078127827d59927bc5c1cdff1cd83cc4c4c2",
      "signature": {
        "v": 27,
        "r": "7e20c29e8ac924f6b29e0b4a1747d5948f2573a228a3511c329d6b23f04752ce",
        "s": "1e5dd427f9a3ad8c462f1d1e63fbe75f93e2d7afe3ece46ea3f76780038d1c0c"
      },
      "sequencerAddress": "0x************************************2F3b",
      "timestamp": 1760379059417
    },
    {
      "type": "solutions_revealed",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "msgHash": "ab5b3f358ed80308c9e37904d84e9d0488fc32cb67d636a520b68595b6a79bdb",
      "signature": {
        "v": 28,
        "r": "6146d337c3c6bf7f3246e749bb59a7e7084ad1aeb117f0243319b9911b8eae36",
        "s": "2471d7242f7995536bf41c49cf05dacd5bbf35b4195cafe4ebc72eee7d2b873e"
      },
      "clearTextSolutions": [
        {
          "signature": {
            "v": 27,
            "r": "680927fe57425d861239b1ecd833e396f9a5650fe13929821cf4138debe0b0d3",
            "s": "5ea11984e0b92d0ca34cb822136136cce16306bdf9048e0584c6cef85baff692"
          },
          "clearTextSolution": {
            "output": "6765",
            "status": "succeed",
            "metering": {
              "limits": {
                "gas": 1099511627776,
                "call": 65536,
                "frame": 524288,
                "memory": 1024
              },
              "last": { "steps": 7083189, "call": 2, "frame": 23 },
              "peak": { "call": 26, "frame": 1677, "memory": 18 },
              "versions": { "protocol": "1.120.0-beta.214" }
            },
            "senderAddress": "0x************************************3F36",
          }
        },
        {
          "signature": {
            "v": 27,
            "r": "620f381b347002c1be542b38f6167885fcc617fefeb5c668942bc5d36c1e775d",
            "s": "6bdf6242478510845b044cd4ccaf932401284a04448636dccc76ca6c919fcb2a"
          },
          "clearTextSolution": {
            "output": "6765",
            "status": "succeed",
            "metering": {
              "limits": {
                "gas": 1099511627776,
                "call": 65536,
                "frame": 524288,
                "memory": 1024
              },
              "last": { "steps": 7083189, "call": 2, "frame": 23 },
              "peak": { "call": 26, "frame": 1677, "memory": 18 },
              "versions": { "protocol": "1.120.0-beta.214" }
            },
            "senderAddress": "0x************************************B45F",
          }
        },
        {
          "signature": {
            "v": 28,
            "r": "78bd3adddda59ac0e011bc8654ff450106496ff3b3fe606c448e714fca06ee4d",
            "s": "1027762ab92211ffbe165ab24150a50a864fc106f4136826d549cc8f2e4c07ed"
          },
          "clearTextSolution": {
            "output": "6765",
            "status": "succeed",
            "metering": {
              "limits": {
                "gas": 1099511627776,
                "call": 65536,
                "frame": 524288,
                "memory": 1024
              },
              "last": { "steps": 7083189, "call": 2, "frame": 23 },
              "peak": { "call": 26, "frame": 1677, "memory": 18 },
              "versions": { "protocol": "1.120.0-beta.214" }
            },
            "senderAddress": "0x************************************058B",
          }
        },
        {
          "signature": {
            "v": 28,
            "r": "76e74b8ae15f666f9e6e1865973eaf8f26f34585aa9a48b61a5cca4e8b8aa2dc",
            "s": "754ffeab68eae964e41accc8f75ac26bfc0206d5f4235188910077be1e1fc353"
          },
          "clearTextSolution": {
            "output": "47",
            "status": "succeed",
            "metering": {
              "limits": {
                "gas": 1099511627776,
                "call": 65536,
                "frame": 524288,
                "memory": 1024
              },
              "last": { "steps": 7083189, "call": 2, "frame": 23 },
              "peak": { "call": 26, "frame": 1677, "memory": 18 },
              "versions": { "protocol": "1.120.0-beta.214" }
            },
            "senderAddress": "0x************************************058B",
          }
        }
      ],
      "sequencerAddress": "0x************************************2F3b",
      "timestamp": 1760379059458
    },
    {
      "type": "adjudication_outcome",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "status": "succeed",
      "signature": {
        "v": 28,
        "r": "e5c092786028c88f38d262d88065ee7d192366cbfd471165b1f3c9daded8b050",
        "s": "009b2856d7389ce0c95536b27082b19aa1a50db823d292187b03b4e7d0de0b76"
      },
      "senderAddress": "0x***********************************6bDC",
      "output": "6765",
      "metering": {
        "limits": {
          "gas": 1099511627776,
          "call": 65536,
          "frame": 524288,
          "memory": 1024
        },
        "last": { "steps": 7083189, "call": 2, "frame": 23 },
        "peak": { "call": 26, "frame": 1677, "memory": 18 },
        "versions": { "protocol": "1.120.0-beta.214" }
      },
      "timestamp": 1760379060900
    },
    {
      "type": "execution_completed",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "transcriptHash": "c72680f4d2db513671c9bd9bc2c33d27fe45a7888b6af9b5b5177faa729ac52e",
      "status": "ReadyForInvoice",
      "signature": {
        "v": 27,
        "r": "57a8d479452f8b93a0737b875fce7460198c851c2abcb4add40211b007290776",
        "s": "150feaf13af9de4ad4db538298f3448df4c4725167377f5f7a3faec0fded8d69"
      },
      "signerAddress": "0x************************************2F3b",
      "timestamp": 1760379065483
    },
    {
      "type": "execution_metadata",
      "executionId": "536bd861-88ff-49dc-9849-d2f909d2a3d4",
      "message": { "version": "1.0.0" },
      "msgHash": "bbc4cea80357a7b61483115fa3a3c2dfb5559c38591bc0fba294535ed12bfdf6",
      "signature": {
        "v": 27,
        "r": "66883fd938166ba7ab0be0e026c5653e048619cd2a03341e5453a968b6dfee90",
        "s": "6423a67806950f8fb023590203ad28406499420c83d3b493c503c54debc375e6"
      },
      "timestamp": 1760379065526
    }
  ],
  "timestamp": 1760467017999,
  "msgHash": "9167f5d34c53778410e80ea537910725f285dff575516087d7e67cbf625b3f8d",
  "signature": {
    "v": 28,
    "r": "123413176e39386f5a96bb35158157bb35f862cc78d71404621ddb8de3d5195c",
    "s": "1820b1cd45dbc67b6716244fa0257de4e8cc2c1a9a22921b0a1c083a4e3818fa"
  }
}
```

{% endcode %}

</details>

### Execution Lifecycle Messages

<details>

<summary>root message</summary>

This `root message` is the first entry recorded in the execution transcript. It contains key information such as the **execution ID**, the **timestamp** of when the task requester initiated the execution, and the **hash** representing all the messages contained within the transcript.

<table><thead><tr><th width="201">Property</th><th width="331.3333333333333">Description</th><th>Values</th></tr></thead><tbody><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td><a href="#execution-lifecycle-messages">transcript</a></td><td>List of all the messages generated during the Function Task execution</td><td>Array</td></tr><tr><td>timestamp</td><td>Transcript query request timestamp. The moment when the task-requester calls the transcript query endpoint.</td><td>unixTimestamp</td></tr><tr><td>msgHash</td><td>Transcript Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr></tbody></table>

</details>

<details>

<summary>task_created</summary>

The `task_created` message is added to the transcript when the Truebit platform receives a new execution request from the task requester. It contains key information such as the **execution ID**, the **original message** sent by the requester (stored in the **message** field), and all data is **signed by the Truebit Verify Hub**.

<table><thead><tr><th width="188">Property</th><th width="337.4973958333333">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>task_created</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td><a href="#task-created-message">message</a></td><td>Original message received from the task-requester </td><td>see below "dispatch_task"</td></tr><tr><td>msgHash</td><td>Current message hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>publickey</td><td>Truebit Verify Hub public key</td><td>Text</td></tr><tr><td>sequencerAddress</td><td>Truebit Verify Hub Address</td><td>Text</td></tr><tr><td>timestamp</td><td>task_created message created timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Original message sent by the Task Requester:** `dispatch_task`

<table><thead><tr><th width="192.55859375">Property</th><th width="255">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>dispatch_task</code></td></tr><tr><td>taskId</td><td>Function task ID</td><td>Text</td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>msgHash</td><td>Current message hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>limits</td><td>Function task execution limits values</td><td><ul><li><strong>gas</strong>: Maximum amount of steps allowed for task execution.</li><li><strong>call</strong>: Amount of Nested calls allowed for task execution.</li><li><strong>frame</strong>: Stack memory allocated for the Calls during the task execution.</li><li><strong>memory</strong>: Amount of memory used by the task execution</li></ul></td></tr><tr><td>econParams</td><td>Economics parameters for the function task execution.</td><td><ul><li><strong>reward</strong>: <strong>0</strong> </li><li><strong>requiredSolutions</strong>: Min amount of solutions to get a validated result.</li><li><strong>totalSolutions</strong>: Total amount of solutions to get a validated result.</li><li><strong>executionTimeout</strong>: Amount of execution time before it gets canceled.</li></ul></td></tr><tr><td>workers</td><td>List of <a href="/pages/Qjyn9U72trbcM4wR0Mxa">Truebit Verify Nodes</a> selected to work on this function task execution</td><td><ul><li><strong>blockNumber</strong>: number</li><li><strong>selectionStrategy</strong>: [ "default"]</li><li><strong>setNodes</strong>: Array of nodes</li></ul></td></tr><tr><td>dispatcherTimestamp</td><td>Dispatcher timestamp at the moment of receiving a new task execution from taskRequester</td><td>unixTimestamp</td></tr><tr><td>taskRequesterTimestamp</td><td>Timestamp specified on the task execution request by the TaskRequester</td><td>unixTimestamp</td></tr><tr><td>ledgerName</td><td>Current ledger in usage</td><td>['avalanche']</td></tr><tr><td>blockHash</td><td>Current block hash</td><td>Text</td></tr><tr><td>blockNumber</td><td>Current block number</td><td>Number</td></tr><tr><td>chainId</td><td>Unique ID for blockchain identification</td><td>Text</td></tr><tr><td>nodeRegistryContractAddress</td><td>Node registration Smart contract Address</td><td>Text</td></tr><tr><td>taskRegistryContractAddress</td><td>Task registration Smart contract Address</td><td>Text</td></tr><tr><td>taskAuthorizationContractAddress</td><td>Task Authorization Contract Address</td><td>Text</td></tr><tr><td>taskRequesterAddress</td><td>Task Requester address. This address will pay for the task execution</td><td>Text</td></tr><tr><td>taskPath</td><td>Provided path for task execution. It must contain the namespace and taskname</td><td>Text</td></tr><tr><td>taskVersion</td><td>Provided version Task for execution </td><td>Number</td></tr><tr><td>senderAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>input</td><td>Function Task Input parameters</td><td>Text</td></tr></tbody></table>

</details>

<details>

<summary>node_outcome</summary>

The `node_outcome` message is recorded in the transcript each time the Truebit Verify Hub receives a response from a Truebit Verify Node. It includes key information such as the **execution ID**, the **original message** from the node (stored in the **message** field), and all data is **signed by the Truebit Verify Hub**.

<table><thead><tr><th width="203">Property</th><th width="292">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>node_outcome</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>message</td><td>Original message received from the Truebit node </td><td>see below "computed_outcome"</td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Node signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>sequencerAddress</td><td>Truebit Verify Hub Address</td><td>Text</td></tr><tr><td>timestamp</td><td>node_outcome message created timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Original message sent by the Task Requester:** `computed_outcome`

<table><thead><tr><th width="203">Property</th><th width="292">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>computed_outcome</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>senderAddress</td><td>Truebit Verify Node address</td><td>Text</td></tr><tr><td>encryptedSolution</td><td>Encrypted solution submitted by the Truebit Verify Node using the Truebit Verify Hub public key.</td><td><p>"iv": Text</p><p>"ephemPublicKey": Text</p><p>"ciphertext": Text</p><p>"mac": Text</p></td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Node signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr></tbody></table>

</details>

<details>

<summary>solutions_revealed</summary>

The `solutions_revealed` message is recorded in the transcript once either the required number of node responses has been received or the execution time has expired. This message includes key information such as the **execution ID** and all the **solutions provided by the nodes**, presented in an **unencrypted** form so that anyone can review the submitted results. These responses were previously **encoded** to prevent premature solution disclosure while the execution was still in progress.

<table><thead><tr><th>Property</th><th width="289">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>solutions_revealed</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>clearTextSolutions</td><td>List of all the solutions provided by the selected Truebit Verify Nodes.</td><td><p>Array of</p><p>[</p><ul><li>signature: Node's signature</li><li><a href="#cleartextsolutions-message">clearTextSolution</a></li></ul><p>]<br></p></td></tr><tr><td>sequencerAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Information stored within the clearTextSolution message**

This array will contain an unencrypted list of all the messages received from the nodes

<table><thead><tr><th width="184">Property</th><th width="289">Description</th><th>Values</th></tr></thead><tbody><tr><td>output</td><td>Unencrypted node solution</td><td>Text</td></tr><tr><td>status</td><td>Node execution status</td><td>[ "succeed", "Failed"]</td></tr><tr><td><a href="#metering">metering</a></td><td>Message used for the execution</td><td><p>Array of </p><ul><li>limits</li><li>last</li><li>peak</li><li>versions</li></ul></td></tr><tr><td>senderAddress</td><td>Truebit verify Node Address</td><td>Text</td></tr></tbody></table>

**Metering message**

<table><thead><tr><th width="184">Property</th><th width="289">Description</th><th>Values</th></tr></thead><tbody><tr><td>limits</td><td>Limits values specified in the dispatch_task message</td><td><p></p><ul><li>gas</li><li>call</li><li>frame</li><li>memory</li></ul></td></tr><tr><td>last</td><td>Actual <strong>last</strong> values consumed during execution</td><td><p></p><ul><li>gas</li><li>call</li><li>frame</li></ul></td></tr><tr><td>peak</td><td>Actual <strong>peak</strong> consumed during execution</td><td><p></p><ul><li>call</li><li>frame</li></ul></td></tr><tr><td>versions</td><td>Truebit protocol version</td><td><strong>protocol</strong>: Truebit protocol version number</td></tr></tbody></table>

</details>

> In the `solutions_revealed` step, if participating nodes submit differing solutions, the **Non-Consensus Resolution Process** is initiated. The [Truebit Control Node](/architecture/introduction/truebit-verify-control-node) executes the task independently and produces an `adjudication_outcome` message defining which nodes provided the right solution.

<details>

<summary>adjudication_outcome</summary>

The `adjudication_outcome` message is created when the `solutions_revealed` step detects that the participating nodes have provided non-matching solutions, indicating a lack of consensus. In this case, the system automatically triggers the **Non-Consensus Resolution Process**, which is managed and executed by the **Truebit Control Node**.

During this process, the Truebit Control Node conducts an adjudication procedure to determine which node or nodes submitted erroneous results and to establish the correct solution for the task. Once this verification is complete, the system logs the `adjudication_outcome` message into the transcript as the official and immutable record of the resolution.

The message contains the final verified solution that has been confirmed as correct, information identifying any nodes found to have provided invalid responses, and additional metadata related to the adjudication process such as timestamps, verification reasoning, or proof references when available.

This message represents the final decision of the protocol in a non-consensus scenario. It ensures that the task requester receives a verified and trustworthy result, closing the execution transcript with a certified outcome derived through a transparent and verifiable process.

<table><thead><tr><th width="184">Property</th><th width="289">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><p></p><p><code>adjudication_outcome</code></p></td></tr><tr><td>executionId</td><td>Current execution ID</td><td><p></p><p>Text</p></td></tr><tr><td>status</td><td>TBD</td><td>success</td></tr><tr><td>signature</td><td>Truebit Node Control signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>senderAddress</td><td>Truebit Node Control Address</td><td>Text</td></tr><tr><td>output</td><td>Truebit Node Control execution Output</td><td>Text</td></tr><tr><td>metering</td><td></td><td><p></p><p>Array of </p><ul><li>limits</li><li>last</li><li>peak</li><li>versions</li></ul></td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

</details>

<details>

<summary>execution_completed</summary>

The `execution_completed` message is logged into the transcript once the entire execution process has been completed — whether the task was resolved through **node consensus** or required intervention by the **Truebit Control Node** during the **Non-Consensus Resolution Process**.

<table><thead><tr><th width="234">Property</th><th width="257.03515625">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>execution_completed</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>transcriptHash</td><td>Execution lifecycle messages hash.</td><td>Text</td></tr><tr><td>status</td><td>Final execution status</td><td>["ReadyForInvoice", "Error"]</td></tr><tr><td>errorDetails</td><td>Only present if there was an error during the execution.</td><td>The details of any error thrown by the protocol or its services</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>signerAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Execution complete statuses**

| Status          | Description                                                                               |
| --------------- | ----------------------------------------------------------------------------------------- |
| ReadyForInvoice | The task execution finished, so the protocol is ready to process the execution's invoices |
| Error           | There was an error during the execution. Please check the **errorDetails** field.         |

</details>

<details>

<summary>execution_metadata</summary>

<table><thead><tr><th width="234">Property</th><th width="257.03515625">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>execution_metadata</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>message</td><td>Truebit Protocol version</td><td>Array of<br>["version"]</td></tr><tr><td>msgHash</td><td>Hash that represents the message</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

</details>


# API Transcript

### Overview

The API Transcript specifically captures the interactions between the Truebit node and external data sources. It documents the requests made and responses received, providing a cryptographic audit trail for all off-chain data exchanges during an API Task.

### Example

<details>

<summary>API Transcript Example</summary>

{% code expandable="true" %}

```json
{
    "executionId": "bafcfb33-f845-4845-a7d3-b4e612a70382",
    "transcript": [
        {
            "type": "api_task_created",
            "executionId": "bafcfb33-f845-4845-a7d3-b4e612a70382",
            "message": {
                "type": "dispatch_api_task",
                "taskId": "api_93f70a3299ad48ea9f4f7296f63d57d861aaa39f0bc5310b59649c6e65b9f96e",
  {
    "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd",
    "transcript": [
        {
            "type": "api_task_created",
            "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd",
            "message": {
                "type": "dispatch_api_task",
                "taskId": "api_142456019dd5b351e82b6f679bf7b36af9e9a0fd523f30844a2c479d908b913e",
                "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd",
                "msgHash": "3e4e7f04c4819075ebbef546b90fb3337e53e17df62bf5d5e722b7566913592c",
                "signature": {
                    "v": 28,
                    "r": "888fdedd9bc53b760565895cc2305028c7c7b8d2c270de3f0b66974d95c9a908",
                    "s": "127074388069fa37af2690e926375ff0c10d96d41d00b7ee0ee0f07e58c092e4"
                },
                "executionTimeout": 30000,
                "ledgerName": "evm",
                "blockHash": "0x************************************************************d3ab",
                "blockNumber": 47503404,
                "chainId": "43113",
                "taskRegistryContractAddress": "0x************************************5f5A",
                "taskAuthorizationContractAddress": "0x************************************96E4",
                "taskRequesterAddress": "0x************************************C8F7",
                "taskPath": "/62faaf33/basic",
                "taskVersion": 1,
                "senderAddress": "0x************************************058B",
                "input": {
                    "path": "/basic-auth/{user}/{password}",
                    "method": "GET",
                    "params": {
                        "user": "foo",
                        "password": "bar"
                    }
                }
            },
            "msgHash": "d6f80a07d2998701afeb0cde3aa4954d6525750b53bf12a34d91f7dc51580d9b",
            "signature": {
                "v": 28,
                "r": "7b0e0bed74e79e8527d296a750e7283fc482c4adaa45beaebd5e569c4e5c3579",
                "s": "429d80d2d3b205d1d717c1b239ca409d81eabd4fdfc53401ca8ff488041202c7"
            },
            "publicKey": "0423fcbc3763e133bbec077378366887191b9dc7053bea44505ba7df8fa7d571be967f04e5246261884b3737ff94de900bca12aa41367138c033558d36d81b9299",
            "sequencerAddress": "0x************************************058B",            
            "timestamp": 1762441257820
        },
        {
            "type": "api_outcome",
            "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd",
            "message": {
                "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd", 
                "senderAddress": "0x************************************058B",              
                "bodyResponse": {
                    "attestation": {
                        "document": "hEShATgioFkSJr9pbW9kdWxlX2lkeCdpLTA1MWFiNzc4ZjgyM2UxZmE5LWVuYzAxOWE0OTg3NzkxMmUzZWVmZGlnZXN0ZlNIQTM4NGl0aW1lc3RhbXAbAAABmlmlGCpkcGNyc7AAWDB55kWMt/HhB6tK4sWJJfextCtlKVoUx00Zo4/yFZOiW0izviZDjp6kqfs+NHAn2H4BWDBLTVs2YbPvwSkgkAyA4Sbkzng8Ui3mwCoqW/evOiuTJ7hndvGI5L4cHEBKEp29pJMCWDCiNBSqBvEmODg64JuJi5EEmia+KOAlbGmQn0J9sApOpZxzJAWk0pnLvnV7pr8myXgDWDB7CIYTshOLXuH46uG7hcqVYwRpV7KmItWgRQB1aAyRa5+JFvnnJ2kTgSbx+kNBqnIEWDD0YeEEQb8zq26t9kkCfHSkPDNCTWF0libfbZC43unCQcm5Xrg9Qv/VVDNQyx8jzjAFWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIWDCCCVvCXAfMaA1xcLgBoz5kKPNcgyB3Q9zZAtnldm702TuasFVMGU6FwRu7gNQ5jTYJWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPWDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABrY2VydGlmaWNhdGVZAn4wggJ6MIICAaADAgECAhABmkmHeRLj7gAAAABpDLWBMAoGCCqGSM49BAMDMIGOMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxOTA3BgNVBAMMMGktMDUxYWI3NzhmODIzZTFmYTkudXMtZWFzdC0xLmF3cy5uaXRyby1lbmNsYXZlczAeFw0yNTExMDYxNDQ5MzRaFw0yNTExMDYxNzQ5MzdaMIGTMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxPjA8BgNVBAMMNWktMDUxYWI3NzhmODIzZTFmYTktZW5jMDE5YTQ5ODc3OTEyZTNlZS51cy1lYXN0LTEuYXdzMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAENmC+TWCLI9NUVqzTUVfCvQtoL+Z7zjbQKSYFNrZCjwsctg9uFVcXSOcDpPtmvYVo957K/MIlsKiKb0a1dsj3l+JO3vIWfsB6kq/ksJBYhvSOH2LI8wPskFthu8oX9K0+ox0wGzAMBgNVHRMBAf8EAjAAMAsGA1UdDwQEAwIGwDAKBggqhkjOPQQDAwNnADBkAjAhpHPAnQzPD1we7bE799zoA5Wiv73jLxZtppzTA+HwADIrhh2Ey0R0OSHE4U50k5wCMF/b/kKD99mNxSMEcMRFMR2tRnAH2toryHiqueo3IeYN9nIFhpTR5NRv/ToKcLZh6WhjYWJ1bmRsZYRZAhUwggIRMIIBlqADAgECAhEA+TF1aBuQr+EdRsy05Of4VjAKBggqhkjOPQQDAzBJMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczAeFw0xOTEwMjgxMzI4MDVaFw00OTEwMjgxNDI4MDVaMEkxCzAJBgNVBAYTAlVTMQ8wDQYDVQQKDAZBbWF6b24xDDAKBgNVBAsMA0FXUzEbMBkGA1UEAwwSYXdzLm5pdHJvLWVuY2xhdmVzMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE/AJU66YIwfNocOKa2pC+RjgyknNuiUv/9nLZiURLUFHlNKSx9tvjwLxYGjK3sXYHDt4S1po/6iEbZudSz33R3QlfbxNw9BcIQ9ncEAEh5M9jASgJZkSHyXlihDBNxT/0o0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSQJbUN2QVH55bDlvpync+Zqd9LljAOBgNVHQ8BAf8EBAMCAYYwCgYIKoZIzj0EAwMDaQAwZgIxAKN/L5Ghyb1e57hifBaY0lUDjh8DQ/lbY6lijD05gJVFoR68vy47Vdiu7nG0w9at8wIxAKLzmxYFsnAopd1LoGm1AW5ltPvej+AGHWpTGX+c2vXZQ7xh/CvrA8tv7o0jAvPf9lkCwjCCAr4wggJEoAMCAQICEDGCD7ujdL9nRRyDngHc+5cwCgYIKoZIzj0EAwMwSTELMAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYDVQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMjUxMTAxMjAwNzQ1WhcNMjUxMTIxMjEwNzQ1WjBkMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxNjA0BgNVBAMMLTdiMDI2MDczNjgwZDQ2NzMudXMtZWFzdC0xLmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEGBSuBBAAiA2IABITYS0DKJkUCxrl9Bv2MdU53cjjg86U3tGpaKBURr3xHMhc7xoXJWBpD3BDMsye8evB+1XKqgOOqBHeIYrN1rNA47S+jtLilVrrgpC38PcqyssB3jYKTExqfRd0SjJedeqOB1TCB0jASBgNVHRMBAf8ECDAGAQH/AgECMB8GA1UdIwQYMBaAFJAltQ3ZBUfnlsOW+nKdz5mp30uWMB0GA1UdDgQWBBTtsqEZPv4v00x5hsn+Q83oTszpejAOBgNVHQ8BAf8EBAMCAYYwbAYDVR0fBGUwYzBhoF+gXYZbaHR0cDovL2F3cy1uaXRyby1lbmNsYXZlcy1jcmwuczMuYW1hem9uYXdzLmNvbS9jcmwvYWI0OTYwY2MtN2Q2My00MmJkLTllOWYtNTkzMzhjYjY3Zjg0LmNybDAKBggqhkjOPQQDAwNoADBlAjEA3WhCnbloEzo40gnS9251dX4+/JfTT/bLAJQOU89JbChDvf2uU1uq6eHxkWEC6CDhAjAYv73J47H0rEsObRgJ5NZGS7fkGSJQxvaXGeO0yzv2vdzsLCoQb4ZeuoXQlO++fF5ZAxgwggMUMIICmqADAgECAhBcn43wT1Vs1zoZPiuKwtd6MAoGCCqGSM49BAMDMGQxCzAJBgNVBAYTAlVTMQ8wDQYDVQQKDAZBbWF6b24xDDAKBgNVBAsMA0FXUzE2MDQGA1UEAwwtN2IwMjYwNzM2ODBkNDY3My51cy1lYXN0LTEuYXdzLm5pdHJvLWVuY2xhdmVzMB4XDTI1MTEwNjAzMTEwMFoXDTI1MTExMTIyMTEwMFowgYkxPDA6BgNVBAMMMzcyN2M5YTI0MDRlNDhjODQuem9uYWwudXMtZWFzdC0xLmF3cy5uaXRyby1lbmNsYXZlczEMMAoGA1UECwwDQVdTMQ8wDQYDVQQKDAZBbWF6b24xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJXQTEQMA4GA1UEBwwHU2VhdHRsZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABP+ACXZLFoEGIEBWzw1UCF2V2qClAjT27A/Vs/lSe165Xmu50jqe9yM22uBuqR098V0yA1n+4ie90mgZAhqIW0oCzZyepdU42Or9tkadGDrPX8GT5xGn1q1wDXxYuPzVl6OB6jCB5zASBgNVHRMBAf8ECDAGAQH/AgEBMB8GA1UdIwQYMBaAFO2yoRk+/i/TTHmGyf5DzehOzOl6MB0GA1UdDgQWBBQBa9x65rRVVO32fV1lOOOpZNBsLTAOBgNVHQ8BAf8EBAMCAYYwgYAGA1UdHwR5MHcwdaBzoHGGb2h0dHA6Ly9jcmwtdXMtZWFzdC0xLWF3cy1uaXRyby1lbmNsYXZlcy5zMy51cy1lYXN0LTEuYW1hem9uYXdzLmNvbS9jcmwvZjgwODQ3NzUtOWI2OC00YmIzLWJmM2ItMmQyZjNkYmU3ZDM2LmNybDAKBggqhkjOPQQDAwNoADBlAjEA45V/r7ebkivwCJAO/n4J0NY/eWM/2i1d3zHiHayLd6di+cQAwNazmpBGHqSEDoNGAjApAuMkRFeLSvSQjxtG//CUM1sjY9qGVkDX3u0dOjpHirmbmkbbINqQSIc334E8/OZZAsIwggK+MIICRKADAgECAhRogTf8GdQ0VG6fmOYTYEoxUg7kRzAKBggqhkjOPQQDAzCBiTE8MDoGA1UEAwwzNzI3YzlhMjQwNGU0OGM4NC56b25hbC51cy1lYXN0LTEuYXdzLm5pdHJvLWVuY2xhdmVzMQwwCgYDVQQLDANBV1MxDzANBgNVBAoMBkFtYXpvbjELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAldBMRAwDgYDVQQHDAdTZWF0dGxlMB4XDTI1MTEwNjA3MDgzN1oXDTI1MTEwNzA3MDgzN1owgY4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApXYXNoaW5ndG9uMRAwDgYDVQQHDAdTZWF0dGxlMQ8wDQYDVQQKDAZBbWF6b24xDDAKBgNVBAsMA0FXUzE5MDcGA1UEAwwwaS0wNTFhYjc3OGY4MjNlMWZhOS51cy1lYXN0LTEuYXdzLm5pdHJvLWVuY2xhdmVzMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEzTow1Rrsn3LKvLwoFLME+NrEBwL7OuTaQG0H1vJ1XwDlooRL2pEFioLWGL7XZV3jVfG5pysV9WZIVWAc6VQqfRokI/pAiSGzJfRFctZT2h7NBtcmGs/uK3sh/SHOgsPeo2YwZDASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwICBDAdBgNVHQ4EFgQUFAteZu6Zrw44hzzd6f3hmg17/5EwHwYDVR0jBBgwFoAUAWvceua0VVTt9n1dZTjjqWTQbC0wCgYIKoZIzj0EAwMDaAAwZQIwSYzxGsFVo5+Gzmxs4DIxDIgLpIBDaEJuZ2qypKvm+LdFfYZSxLUs0smXdOGmQe7IAjEAwf4KYAnzSpM1p5B/Kz+B8eaSmuU0GPu97vYri47b5bqWL0cX6TAbw1O0xqGnqtlmanB1YmxpY19rZXlZASYwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCth41rn6rwlmE8LrWy0CB0nWHrWRvySlu+Xzyf5s7bCWZ59oA6XN3S8idnZwuJ14uyZotKkOs+VmgNoEMqXV0L/FYzWP4QIP4cBVdIT/E6Fre4fcSmAEjDjPdUKy3DcIa0WXFUX4ppkUbylZUhFvnj6iHFlbhWYbPj6tJyVOhjXhPw4Wmm+JRMdsOaa1nRBG4For7rkOOCtj/v72k0YB1f6M2qKKfSrDGW8mE9YDfpIPNnzztZWJBALQeRfsnMJjhKeEm0P1v9MBJl9XsjGMQcfNsTzMh/TSAps+SCRlTdJwy9MFIC/u1R//rJf1P503Ujhkbn8doWDGolTwsEwM79AgMBAAFpdXNlcl9kYXRh9mVub25jZfb/WGDtH95g2vjrKE02vNEZ4QQVhstXP7WD96NbqP+FsfAcHUHkrdpQThp5iLYsLitZOjCYPprYMcG9NogXwuODqeUztENSSncAZZm3xFECnw+iwNtdn6kvMozF3JuA5wxRgeQ=",
                        "documentHash": "11949182f4735845d796070e1cdc90a906f00971cef4c245b5238119dbe7e819",
                        "enclave": {
                            "moduleId": "i-051ab778f823e1fa9-enc019a49877912e3ee",
                            "nonce": null,
                            "userData": null
                        },
                        "platform": {
                            "PCR0": "79e6458cb7f1e107ab4ae2c58925f7b1b42b65295a14c74d19a38ff21593a25b48b3be26438e9ea4a9fb3e347027d87e",
                            "PCR1": "4b4d5b3661b3efc12920900c80e126e4ce783c522de6c02a2a5bf7af3a2b9327b86776f188e4be1c1c404a129dbda493",
                            "PCR10": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR11": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR12": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR13": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR14": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR15": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR2": "a23414aa06f12638383ae09b898b91049a26be28e0256c69909f427db00a4ea59c732405a4d299cbbe757ba6bf26c978",
                            "PCR3": "7b088613b2138b5ee1f8eae1bb85ca9563046957b2a622d5a0450075680c916b9f8916f9e72769138126f1fa4341aa72",
                            "PCR4": "f461e10441bf33ab6eadf649027c74a43c33424d61749626df6d90b8dee9c241c9b95eb83d42ffd5543350cb1f23ce30",
                            "PCR5": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR6": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR7": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                            "PCR8": "82095bc25c07cc680d7170b801a33e6428f35c83207743dcd902d9e5766ef4d93b9ab0554c194e85c11bbb80d4398d36",
                            "PCR9": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
                        },
                        "timestamp": "2025-11-06T14:49:37.000493",
                        "validated": true
                    },
                    "data": "{\"authenticated\":true,\"user\":\"foo\"}\n",
                    "executedAt": "2025-11-06T15:00:57.878929",
                    "headers": {
                        "Access-Control-Allow-Credentials": "true",
                        "Access-Control-Allow-Origin": "*",
                        "Connection": "close",
                        "Content-Length": "36",
                        "Content-Type": "application/json",
                        "Date": "Thu, 06 Nov 2025 15:01:04 GMT",
                        "Server": "gunicorn"
                    },
                    "request_id": "50616139-0bfb-4d15-8e85-943465555716",
                    "status": "success",
                    "statusCode": 200,
                    "tlsInfo": {
                        "cipher": "Unknown",
                        "host": "10.1.10.100",
                        "port": 80,
                        "protocol": "Unknown",
                        "source": "fallback",
                        "timestamp": "2025-11-06T15:00:57.878900",
                        "verified": false
                    }
                },
                "msgHash": "dcdcaf566bc34196502ab8f522a135d1350670358aa148ac3c52a922e077b2da",
                "signature": {
                    "v": 28,
                    "r": "925cfcf8ad7c9834c4d94e407a132cbe931ef4ad45aa41a2bec74131ed569895",
                    "s": "76d63ebdfeec66297acd0cb78b955c0239db532e2d1919d14ab2153888457792"
                },
                "tlsHandshakeHash": "b48d38f93eaa084033fc5970bf96e559c33c4cdc07d889ab00b4d63f9590739d",
                "status": "succeed",
                "totalTransferredBytes": {
                    "request": 0,
                    "response": 0
                }
            },
            "msgHash": "d9fbe7f5a28465ee3c6bba6814eb5558c604f41db90b72f32a532d100ad1db62",
            "signature": {
                "v": 27,
                "r": "d530ccb0295e7e55190d7038f580c0df0d72d5e6272c36230057af089cd7bac7",
                "s": "73824ae7f3e1ccf9e21843718c5727e72be37a8fbe61cad162586bd58a7ebadc"
            },
            "sequencerAddress": "0x************************************058B",
            "timestamp": 1762441264136
        },
        {
            "type": "execution_completed",
            "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd",
            "transcriptHash": "cbac5b7008ec4dcccdae8106a7e7687907c790b24761d59f5ce4a93a72ef49cc",
            "status": "ReadyForInvoice",
            "signature": {
                "v": 28,
                "r": "2b100190b3a157c55e29ce0b2de8ca4222ffa711b096b42b3f9a3cdff51cbbba",
                "s": "7db04fca1d6454cb20af183b00048b0d35e03bc637c34ace2f06912e01969974"
            },
            "signerAddress": "0x************************************058B",
            "timestamp": 1762441264189
        },
        {
            "type": "execution_metadata",
            "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd",
            "message": {
                "version": "1.0.0"
            },
            "msgHash": "cbb80896ec2c2f544b454860af2e695eaebae6aedf1f8fb3d792bdb526bfd9d0",
            "signature": {
                "v": 27,
                "r": "9b1af47030318a674d9f76da1785ebfb2ffab0bc09196b4f857ca234b76356be",
                "s": "02e02ab9dbc958ac35a7a32565756aa04d888e2372a2ba7365c322cd005dfed0"
            },
            "timestamp": 1762441264407
        }
    ],
    "timestamp": 1762441278885,
    "msgHash": "ac2afb66b2d876907a14dac1b37a3d6fc7bf8086fb6167f025eec953b2babb01",
    "signature": {
        "v": 28,
        "r": "153dc4ba3ee67da6ed75bcafb4d51e927aef49ecf417f30c62b122f774772a8a",
        "s": "5ca6c8907fbaede968a61fe6e3db204a35d1ead34483e25763a88377f5ed3e7e"
    }
}            "sequencerAddress": "0x************************************058B",
            "timestamp": 1762186653114
        },
        {
            "type": "execution_completed",
            "executionId": "bafcfb33-f845-4845-a7d3-b4e612a70382",
            "transcriptHash": "16b2697357335b70994b8edb24cd9896fe19c0374ff272346e0889b99a47a154",
            "status": "ReadyForInvoice",
            "signature": {
                "v": 28,
                "r": "a649b6d25a2b4c4c590e09ad29ad7bb70a25eea9ec92e8eb1711a3bd5e65f08e",
                "s": "7c6cea2e65b21e501f078a5010ee9f407ae2079299c5efc393e6e8f5ea283e73"
            },
            "signerAddress": "0x************************************058B",
            "timestamp": 1762186653162
        },
        {
            "type": "execution_metadata",
            "executionId": "bafcfb33-f845-4845-a7d3-b4e612a70382",
            "message": {
                "version": "1.0.0"
            },
            "msgHash": "b8b018e500513e608feef59653e223e22e2d0691596601145b5cc057b2d95165",
            "signature": {
                "v": 28,
                "r": "75493c403f330d69c615ad5376283a98d729e0dbd8ef80f9cdfdc08083f4304e",
                "s": "19f5a424579ad9f768cf7bea2c9a8a115e63f8068098c5310e3ad9c2b01ad228"
            },
            "timestamp": 1762186653366
        }
    ],
    "timestamp": 1762186724007,
    "msgHash": "a386c3ea87141ff8d953813745474f38354ae365c94d239e03ae9eaa17f48bc1",
    "signature": {
        "v": 27,
        "r": "37ed6a404550eb352eed1275434071a1e273f456a2cb01cae7e179e0cb35a6eb",
        "s": "033cfd9a7225021dcb3648e898b8e5a9ecc0fe430a76bad32eb71ebe12ff1fd9"
    }
}
```

{% endcode %}

</details>

### Execution Lifecycle Messages

<details>

<summary>root message</summary>

This `root message` is the first entry recorded in the execution transcript. It contains key information such as the **execution ID**, the **timestamp** of when the task requester initiated the execution, and the **hash** representing all the messages contained within the transcript.

<table><thead><tr><th>Property</th><th width="355.3333333333333">Description</th><th>Possible values</th></tr></thead><tbody><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td><a href="#execution-lifecycle-messages">transcript</a></td><td>List of all the messages generated during the API Task execution</td><td>Array of data </td></tr><tr><td>timestamp</td><td>Transcript query request timestamp. The moment when the task-requester calls the transcript query endpoint.</td><td>Number</td></tr><tr><td>msgHash</td><td>Transcript Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr></tbody></table>

</details>

<details>

<summary>api_task_created</summary>

The `api_task_created` message is added to the transcript when the Truebit platform receives a new execution request from the task requester. It contains key information such as the **execution ID**, the **original message** sent by the requester (stored in the **message** field), and all data is **signed by the Truebit Verify Hub**.

<table><thead><tr><th width="188">Property</th><th width="256.6145833333333">Description</th><th>Possible values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td>api_task_created</td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td><a href="#task-created-message">message</a></td><td>Original message received from the Task Requester</td><td>see below "dispatch_api_task"</td></tr><tr><td>msgHash</td><td>Current Message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>publickey</td><td>Truebit Verify Hub public key</td><td>Text</td></tr><tr><td>sequencerAddress</td><td>Truebit Verify Hub Address</td><td>Text</td></tr><tr><td>timestamp</td><td>task_created message created timestamp</td><td>Number</td></tr></tbody></table>

**Original message sent by the Task Requester:** `dispatch_api_task`

<table><thead><tr><th width="204.859375">Property</th><th>Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>dispatch_api_task</code></td></tr><tr><td>taskId</td><td>API Task ID</td><td>Text</td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>executionTimeout</td><td>Execution time out</td><td>number</td></tr><tr><td>ledgerName</td><td>Current ledger in usage</td><td>['avalanche']</td></tr><tr><td>blockHash</td><td>Current block hash</td><td>Text</td></tr><tr><td>blockNumber</td><td>Current block number</td><td>Number</td></tr><tr><td>chainId</td><td>Unique ID for blockchain identification</td><td>Number</td></tr><tr><td>taskRegistryContractAddress</td><td>Task registration Smart contract Address</td><td>Text</td></tr><tr><td>taskAuthorizationContractAddress</td><td>Task Authorization Contract Address</td><td>Text</td></tr><tr><td>taskRequesterAddress</td><td>Task Requester Address. This address will pay for the task execution</td><td>Text</td></tr><tr><td>taskPath</td><td>Provided path for task execution. It must contain the namespace and taskname</td><td>Text</td></tr><tr><td>taskVersion</td><td>Provided version Task for execution </td><td>Number</td></tr><tr><td>senderAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>input</td><td>API Task Input parameters</td><td>path: Endpoint Path<br>method: {POST, GET}<br>body: Body endpoint values</td></tr></tbody></table>

</details>

<details>

<summary>api_outcome</summary>

The `api_outcome` message is recorded in the transcript once Truebit Verify Hub receives a response from the TEE. It includes key information such as the **execution ID**, the **original message** from the TEE (stored in the **message** field), and all data is **signed by the Truebit Verify Hub**.

<table><thead><tr><th width="186">Property</th><th width="229.7421875">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td>api_outcome</td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td><a href="#api-outcome-message">message</a></td><td>Original message received from the TEE</td><td>see below "api_fetcher_outcome"</td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>sequencerAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>Number</td></tr></tbody></table>

**Original message sent by the Task Requester:** `api_fetcher_outcome`

<table><thead><tr><th width="189.59375">Property</th><th width="271.62890625">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td><code>api_fetcher_outcome</code></td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>senderAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>bodyResponse</td><td>TEE response</td><td>see below "bodyResponse" message</td></tr><tr><td>msgHash</td><td>Current message Hash</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>tlsHandshakeHash</td><td>TLS handshake information hash </td><td>Text</td></tr><tr><td>status</td><td>API execution status</td><td>{Failed, Success, Running}</td></tr><tr><td>totalTransferredBytes</td><td>Bytes transferred during the API execution.</td><td><ul><li>request: Total bytes transferred in the Request</li><li>response: Total bytes transferred in the Response.</li></ul></td></tr></tbody></table>

**Information stored within the bodyResponse message**

<table><thead><tr><th width="130.88671875"></th><th width="164.84765625"></th><th></th></tr></thead><tbody><tr><td>attestation</td><td></td><td></td></tr><tr><td></td><td>document</td><td>The base64-encoded signed quote (Nitro attestation report) — this is the root of trust</td></tr><tr><td></td><td>documentHash</td><td>SHA-256 of the binary document</td></tr><tr><td></td><td>enclave.moduleId</td><td>Identifies the specific enclave that generated the quote.</td></tr><tr><td></td><td>enclave.nonce</td><td>Prevents replay attacks (each task gets unique nonce).</td></tr><tr><td></td><td>enclave.userData</td><td>Should contain task-specific data (e.g., hash of input parameters, task ID).</td></tr><tr><td></td><td>platform.PCR0</td><td>Enclave image hash — proves which code was loaded.</td></tr><tr><td></td><td>platform.PCR3</td><td>Hash of the enclave image file (EIF). This proves exactly what code ran in the enclave.</td></tr><tr><td></td><td>platform.PCR4</td><td>Hash of the kernel and bootstrap configuration. Ensures the enclave environment itself wasn't tampered with.</td></tr><tr><td></td><td>timestamp</td><td>Proves when the attestation was generated</td></tr></tbody></table>

</details>

<details>

<summary>execution_completed</summary>

The `execution_completed` message is logged into the transcript once the entire execution process has been completed or a timeout has occurred (whichever happens first).

<table><thead><tr><th width="181.33203125">Property</th><th width="281">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td>execution_completed</td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>transcriptHash</td><td>Execution lifecycle messages hash.</td><td>Text</td></tr><tr><td>status</td><td>Final execution status</td><td>["ReadyForInvoice", "Error"]</td></tr><tr><td>errorDetails</td><td>Only present if there was an error during the execution.</td><td>The details of any error thrown by the protocol or its services</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>signerAddress</td><td>Truebit Verify Hub address</td><td>Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

**Execution Complete Statuses**

| Status          | Description                                                                           |
| --------------- | ------------------------------------------------------------------------------------- |
| ReadyForInvoice | The API was executed, so the protocol is ready to process the execution's invoices    |
| Error           | There was an error during the API execution. Please check the **errorDetails** field. |

</details>

<details>

<summary>execution_metadata</summary>

<table><thead><tr><th width="234">Property</th><th width="257.03515625">Description</th><th>Values</th></tr></thead><tbody><tr><td>type</td><td>Message type</td><td>execution_metadata</td></tr><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>message</td><td>Truebit Protocol version</td><td>Array of<br>["version"]</td></tr><tr><td>msgHash</td><td>Hash that represents the message</td><td>Text</td></tr><tr><td>signature</td><td>Truebit Verify Hub signature</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>timestamp</td><td>Message sent timestamp</td><td>unixTimestamp</td></tr></tbody></table>

</details>


# Invoice Transcript

### **Overview**

This transcript serves as the official record of the computation’s cost and resource usage across the platform. Whether you are running Truebit Functions or API Tasks, it provides a verifiable breakdown of the fees and execution steps, ensuring that billing is as transparent as the computation itself.

### **Description**

<details>

<summary>Function Invoice Transcript</summary>

{% code fullWidth="true" expandable="true" %}

```json
{
    "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd",
    "taskId": "api_142456019dd5b351e82b6f679bf7b36af9e9a0fd523f30844a2c479d908b913e",
    "taskCreated_timeStamp": 1762441264136,
    "invoiceId": "4750340717624412641106",
    "byteGasPrice": 0.0002,
    "accounting_signature": {
        "v": 27,
        "r": "2cb73383f446dbaa2de9bfeec669bf159a72b7662ec15df9b391dcdf1267436b",
        "s": "3e245d19087c9c5c448fdf9a26d0a219c98eae8d9fb0fa360a63a94c252443e0"
    },
    "lineItem": [
        {
            "operation": "charge",
            "account": "0x************************************C8F7",
            "totalTransferredBytes": {
                "request": 0,
                "response": 0
            }
        }
    ]
}

```

{% endcode %}

</details>

<details>

<summary>API Invoice Transcript</summary>

{% code expandable="true" %}

```json
{
    "executionId": "e7e444fa-96c5-45c9-9c65-dd9f8edfdafd",
    "taskId": "api_142456019dd5b351e82b6f679bf7b36af9e9a0fd523f30844a2c479d908b913e",
    "taskCreated_timeStamp": 1762441264136,
    "invoiceId": "4750340717624412641106",
    "byteGasPrice": 0.0002,
    "accounting_signature": {
        "v": 27,
        "r": "2cb73383f446dbaa2de9bfeec669bf159a72b7662ec15df9b391dcdf1267436b",
        "s": "3e245d19087c9c5c448fdf9a26d0a219c98eae8d9fb0fa360a63a94c252443e0"
    },
    "lineItem": [
        {
            "operation": "charge",
            "account": "0x************************************C8F7",
            "totalTransferredBytes": {
                "request": 0,
                "response": 0
            }
        }
    ]
}
```

{% endcode %}

</details>

### Execution Lifecycle Messages

<details>

<summary>root message</summary>

The `root message` serves as the initial entry in the Function Invoice transcript. It includes critical details like the **execution ID**, **taskId**, and a list of **liteItems**, which capture all recorded operations on the invoice, such as "charge," "pay," and "penalty."

<table><thead><tr><th width="208.2890625">Property</th><th width="331.3333333333333">Description</th><th>Values</th></tr></thead><tbody><tr><td>executionId</td><td>Current execution ID</td><td>Text</td></tr><tr><td>taskId</td><td>Executed Function task</td><td>Text</td></tr><tr><td>taskCreated_timeStamp</td><td>Timestamp for task creation message</td><td>unixTimestamp</td></tr><tr><td>invoiceId</td><td>InvoiceId</td><td>Number</td></tr><tr><td>stepGasPrice / byteGasPrice</td><td><ul><li><strong>stepGasPrice</strong>: Amount of GAS paid for each execution step</li><li><strong>byteGasPrice</strong>: Amount of GAS paid for each transferred byte.</li></ul></td><td>Number</td></tr><tr><td>accounting_signature</td><td>Truebit Verify Hub</td><td>v: Text<br>r: Text<br>s: Text</td></tr><tr><td>lineItem</td><td>List of all operations generated during the task execution.</td><td>Array</td></tr></tbody></table>

</details>

***

<details>

<summary>lineItem Function Task</summary>

For each participant in the Task execution, there is a `lineItem` representing an action applied to an "address".

* **Charge**: The Task requester is billed for the execution request.
* **Pay**: The Truebit Verify node is rewarded for executing and submitting the Task result.
* **Penalty**: The Truebit Verify node is penalized for submitting an incorrect response.

<table><thead><tr><th width="195.58984375">Property</th><th width="264.2005208333333">Description</th><th>Values</th></tr></thead><tbody><tr><td>operation</td><td>Operation Type</td><td>["charge","pay","penalty"]</td></tr><tr><td>account</td><td><ul><li>If messageType is "charge", you will see the Task Requester Address</li><li>If messageType is "pay" or "penalty", you will see the Truebit Verify Address*</li></ul></td><td>Text</td></tr><tr><td>total_steps_computed</td><td>Total amount of steps executed by the Truebit Verify Node.</td><td>Text</td></tr><tr><td>peak_memory_used</td><td>Peak memory used by the Truebit Verify Node.</td><td>Text</td></tr></tbody></table>

</details>

<details>

<summary>lineItem API Task</summary>

The `lineitem` details the charge operation for the Task Requester.

<table><thead><tr><th width="195.58984375">Property</th><th width="264.2005208333333">Description</th><th>Values</th></tr></thead><tbody><tr><td>operation</td><td>Operation Type</td><td>charge</td></tr><tr><td>account</td><td>Task Requester Address</td><td>Text</td></tr><tr><td>totalTransferredBytes</td><td>Amount of bytes transferred during the API execution</td><td><ul><li><strong>request</strong></li><li><strong>response</strong></li></ul></td></tr></tbody></table>

</details>


# Audit Layer

**Truebit Verify uses a blockchain-backed Audit Layer to underpin its security model and enforce its core protocols**. The Audit Layer performs several key functions:

## **Node Registry Smart Contract**

**NodeRegistry Address:** `0x1e1802b2807FfE7fF22dCa24E8ff7d30a3a8150c`

Node Registration is set up on the blockchain. **It maintains a transparent list of all active Truebit Verify Nodes.** Registered nodes can participate in the computation of a task solution if selected.

When a node is registered on the Node Registration Ledger, its unique Ethereum (ETH) address is added to the NodeRegistry smart contract's storage; similarly before the shutdown, it needs to de-register to ensure a graceful shutdown.

The NodeRegistry is an EVM-compatible smart contract and it manages the list of active nodes within the Node Registration Ledger. Each position on the list contains one registered Node Address.

## Task Registry Smart Contract

**TaskRegistry Address:** `0x6825142A0e85dDB3cBf872a26eE2beefaedbc465`

Task Registration is set up on the blockchain. **It keeps a clear list of all registered and verifiable** **tasks.** Once registered, tasks can be executed directly using the Truebit API's execute endpoint.

The TaskRegistry is an EVM-compatible smart contract that includes all necessary methods for managing namespaces and tasks, allowing anyone to register their deployed tasks.

## Task Authorization Smart Contract

**TaskAuthorization Address:** `0x6da8eE7DF16BD92eb71F314f4b701C6c5b0b2721`

Task Authorization is set up on the blockchain, **maintaining a clear list of all authorized addresses that can execute tasks within a namespace**. It also keeps a list of registered API\_KEY hashes, allowing other users to execute tasks while making the user who registered the API\_KEY responsible for the task execution payment.

The TaskRegistry is an EVM-compatible smart contract that includes all necessary methods for managing accesses over a namespace.


# Introduction

### Developing Truebit Tasks

**Truebit Verify is designed to be an easy-to-use and flexible platform for you to host and run verified, decentralized code.**&#x20;

You may need to think a bit differently about how to design functions that are optimized and decentralized networks. We highlight some [key concepts](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts) including [determinism](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/determinism) and the [WASM](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/webassembly) sandbox to get you started. &#x20;

Within each section, there are some simple examples of Truebit Tasks to help you become familiar with the platform.

### **Function Tasks**&#x20;

**Serverless function code modules that are compiled to** [WASM](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/webassembly), **then executed and verified on** [Truebit Verify Nodes](/architecture/introduction/truebit-verify-nodes).&#x20;

You develop the function code in one of the [supported languages](/developing-truebit-tasks/how-to-create-function-tasks/supported-languages) and then use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to build, test, and deploy your code to the Truebit platform.

### **API Tasks**

**Verified calls to any web services API endpoint using TEE technology.**&#x20;

You create an OpenAPI manifest file that describes different endpoints, then use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to test and deploy your code to the Truebit platform.


# Truebit CLI reference

**This guide provides a practical overview of the Truebit CLI, a command-line tool for developers to interact with the Truebit network**. It explains how to submit and run computation tasks, manage wallets, monitor task execution, and integrate results into your workflows. Each command comes with detailed help options, making it easy to discover functionality and incorporate the CLI into scripts, automation pipelines, or custom developer tooling.

{% hint style="info" %}
**Installing the Truebit CLI**

The Truebit CLI is supported on recent versions of Linux, Windows, and MacOS.&#x20;

See the [Truebit CLI Guide](/overview/getting-started-guide) for detailed installation instructions.
{% endhint %}

{% code fullWidth="true" %}

```
Usage: truebit [options] [command]

  _____                _     _ _    __     __        _  __       
 |_   _| __ _   _  ___| |__ (_) |_  \ \   / /__ _ __(_)/ _|_   _ 
   | || '__| | | |/ _ \ '_ \| | __|  \ \ / / _ \ '__| | |_| | | |
   | || |  | |_| |  __/ |_) | | |_    \ V /  __/ |  | |  _| |_| |
   |_||_|   \__,_|\___|_.__/|_|\__|    \_/ \___|_|  |_|_|  \__, |
   ____ _     ___                                          |___/ 
  / ___| |   |_ _|                                               
 | |   | |    | |                                                
 | |___| |___ | |                                                
  \____|_____|___|                                               
                                                                 
A CLI to interact with Truebit Verify node
By accessing and using the Protocol, you hereby agree to our Terms of Use and our Privacy Policy. Patents pending.
Terms of Use: https://www.truebit.io/terms
Privacy Policy: https://www.truebit.io/privacy-policy

Options:
  -V, --version                                                     output the version number
  -h, --help                                                        Display help for command

Commands:
  help [command]                                                    display help for command
  setup                                                             Initialize user profile configuration
  start [options] <taskId> <input>                                  Run a Truebit Task
  deploy [options] <namespace> <taskName>                           Deploy and register a new Truebit Task
  build [options] <sourceCodePath>                                  Create a Function Task
  create-api <manifestPath>                                         Create an API Task
  start-api <manifestPath> <input> [authType] [authString]          Run an API Task
  status <executionId>                                              Get execution status
  quota                                                             Check quota status
  web-login                                                         Sign in to Web UI
  contract                                                          Manage contract bindings
  api-auth <namespace> <taskname> <taskId> <authType> <authString>  Set API Task authentication
  namespace                                                         Manage Namespace operations
  task                                                              Manage Task operations
  auth                                                              Manage authorization operationstrue
```

{% endcode %}

## Managing Truebit Account

### Setup

```
Usage: truebit setup [options]

Setup generate a secret.json in your home directory with your information

Options:
  -h, --help  Display help for command
```

### Quota

{% code overflow="wrap" %}

```
Usage: truebit quota [options]

Displays the current quota status for the registered user, including subscription tier, monthly limits, and reset date.

Options:
  -h, --help  Display help for command
```

{% endcode %}

### web-login

{% code overflow="wrap" %}

```
Usage: truebit web-login [options]

Opens the Truebit Web UI and signs you in automatically using your wallet credentials.

Options:
  -h, --help  Display help for command
```

{% endcode %}

### chain

{% code overflow="wrap" %}

```
Usage: truebit chain [options] [command]

Inspect supported chains.

Options:
  -h, --help      Display help for command

Commands:
  list            Print every supported chainId with its name, symbol, and network class.
  help [command]  display help for command
```

{% endcode %}

### contract

{% code overflow="wrap" %}

```
Usage: truebit contract [options] [command]

Manage contract address bindings for quota enforcement.

Options:
  -h, --help                  Display help for command

Commands:
  add [options] <address>     Bind a contract address to your account.
  remove [options] <address>  Unbind a contract address from your account.
  list                        List all contracts bound to your account.
  help [command]              display help for command
```

{% endcode %}

#### add

Using the “contract add” command, you can associate an existing smart contract that uses Verify Oracles with your Truebit account. Once linked, the contract becomes part of your account, allowing it to benefit from your available quota and the advantages associated with your role.

{% code overflow="wrap" %}

```
Usage: truebit contract add [options] <address>

Bind a contract address to your account.

Arguments:
  address            Contract address to bind

Options:
  --chain <chainId>  Numeric chain ID (e.g. 43113 for Avalanche Fuji, 11155111 for Ethereum Sepolia)
  -h, --help         Display help for command
```

{% endcode %}

#### remove

Using the “contract remove” command, you can detach an existing smart contract from your Truebit account. Once removed, the contract will no longer have access to your account quota or the benefits associated with your role.

{% code overflow="wrap" %}

```
Usage: truebit contract remove [options] <address>

Unbind a contract address from your account.

Arguments:
  address            Contract address to unbind

Options:
  --chain <chainId>  Numeric chain ID
  -h, --help         Display help for command
```

{% endcode %}

#### list

The “contract list” command displays all smart contracts currently associated with your Truebit account. From here, you can review linked contracts and manage which ones have access to your account quota and role-based benefits.

{% code overflow="wrap" %}

```
Usage: truebit contract list [options]

List all contracts bound to your account.

Options:
  -h, --help  Display help for command
```

{% endcode %}

## Developing Function Tasks

Use the `build` and `start` commands to test your function tasks before deploying them to the [Coordination Hub](/architecture/introduction#truebit-verify-hub).

### Build

{% code overflow="wrap" %}

```
Usage: truebit build [options] <sourceCodePath>

Compiles source code to obtain compiled and instrumented Truebit task and pushes it to the Truebit node.

Arguments:
  sourceCodePath                     Path of the task source code.

Options:
  -l, --lang [programming-language]  Specify the programming language in which the task was
                                     developed (default: "rs")
  -h, --help                         Display help for command

```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Building the Function task
Your Function task is ready.
Use the following taskId for execution or deployment: <taskId>
```

{% endcode %}

As a result of running the `build` command, you will receive a `TaskId`, which serves as the unique identifier for your task.

#### -l, --lang Options

<table><thead><tr><th width="138">Language</th><th>Value</th></tr></thead><tbody><tr><td><strong>Rust</strong></td><td><strong>rs  (default value)</strong></td></tr><tr><td>Javascript</td><td>js</td></tr><tr><td>Python</td><td>py</td></tr><tr><td>C</td><td>c</td></tr><tr><td>C++</td><td>c++</td></tr></tbody></table>

#### Example

```
truebit build examples/js/fibonacci/dist -l js
```

#### Source Code Structure

In order to compile your source code, make sure you have the following file structure within the `<sourceCodePath>` folder that will be built:

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

* 📁 src&#x20;
  * 📄 main.rs&#x20;
* 📁 target
* 📄 Cargo.toml
* 📄 Cargo.lock

{% hint style="info" %}
Running the truebit-cli "build" command automatically generates the **target** folder and **Cargo.lock** file.&#x20;
{% endhint %}
{% endtab %}

{% tab title="C" %}

* 📁 src&#x20;
  * 📄 main.c
* 📄 compile.sh
  {% endtab %}

{% tab title="C++" %}

* 📁 src&#x20;
  * 📄 main.cpp
* 📄 compile.sh
  {% endtab %}

{% tab title="Js" %}

* 📁 src&#x20;
  * 📄 main.js
* 📁 dist
  * 📄 main.js
* 📄 package-lock.json
* 📄 package.json
* 📄 rollup.config.mjs

{% hint style="info" %}
The task source filepath must be **src/main.js**.\
To create **dist/main.js**, use the \`npx rollup -c\` command, as explained in [JS Task Preparation](/developing-truebit-tasks/how-to-create-function-tasks/supported-languages/javascript#task-preparation).
{% endhint %}
{% endtab %}

{% tab title="Python" %}

* 📁 src&#x20;
  * 📄 task.py

{% hint style="info" %}
The task source filepath must be **src/task.py**.
{% endhint %}
{% endtab %}
{% endtabs %}

### Start

{% code overflow="wrap" %}

```
Usage: truebit start [options] <taskId> <input>

Executes a task within the context of Truebit Verify node. The task should be already uploaded to local-storage.

Arguments:
  taskId           Id of the task
  input            Input for task execution

Options:
  --update-config  Automatically update resource limits in config.json according to peak usage
                   report
  -h, --help       Display help for command


```

{% endcode %}

#### Output

```bash
Executing the Function task
Function Task executed with status: succeed
Function Task executed with result: 55
Function Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬────────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity   │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼────────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 146203      │ '7520445x' │
│ Nested calls  │ 'Calls'       │ 1048576       │ 29    │ 0           │ '36158x'   │
│ Frame memory  │ 'Bytes'       │ 1048576       │ 137   │ 0           │ '7654x'    │
│ System memory │ '64 Kb pages' │ 0             │ 'N/A' │ 'N/A'       │ 'N/A'      │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴────────────┘
```

#### **Resources**

<table><thead><tr><th width="118">Name</th><th>Description</th></tr></thead><tbody><tr><td>Gas</td><td>Maximum amount of task execution steps.</td></tr><tr><td>Call</td><td>Amount of nested calls during the task execution.</td></tr><tr><td>Frame</td><td>Stack memory allocated for the calls.</td></tr><tr><td>Memory</td><td>Amount of memory used by the task execution.</td></tr></tbody></table>

#### Metering

<table><thead><tr><th width="119">Name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             Name</th><th>Description</th></tr></thead><tbody><tr><td><strong>Limits</strong></td><td>Maximum amount of resources assigned to task execution. See <a href="/pages/9QdmubpyGCMsA5O2eUHL">determinism</a>.</td></tr><tr><td><strong>Peak</strong></td><td>Peak resource usage collected during task execution.</td></tr><tr><td><strong>Last</strong></td><td>The amount of resources in use when the task finished execution. If it ran successfully, the final values for "Call" and "Frame" should be 0.</td></tr><tr><td><strong>Capacity</strong></td><td><p>Resources allocated in excess. <br>If the "Limit" value shows a 4000x number, it means that the required resources exceed the actual needs by that amount.</p><p>Remember: resource usage might vary on the same Truebit task depending on the input data.</p></td></tr></tbody></table>

{% hint style="info" %}
For more information about the use of the Resources, please check the [Instrumentation](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/task-instrumentation) page
{% endhint %}

## Developing API Tasks

Use the `start-api`, `create-api` commands to test your API tasks before deploying them to the [Coordination Hub](/architecture/introduction/truebit-verify-hub):

### start-api

{% code overflow="wrap" %}

```
Usage: truebit start-api [options] <manifestPath> <input> [authType] [authString]

Start the Truebit API Task, verify with enforcer and request the api. As a result, it returns the
API response

Arguments:
  manifestPath  Path of the manifest.
  input         Input request JSON file path
  authType      Type of authentication needed for API task usage. One of:
                <aws-signature,basic-auth,custom-header>
  authString    Auth string is a comma separated value that represents auth method.
  
  	Examples:
  		AWS_SIGNATURE = "accessKey:<accesskey>,secretKey:<secretkey>"
  		BASIC_AUTH = "username:<username>,password:<password>"
  		CUSTOM_HEADER = "<customheader>"

Options:
  -h, --help    Display help for command

```

{% endcode %}

#### Output

```bash
Executing the API task
API Task executed with status: ['OK', 'Error']
API Task Output
Input request
{
    path: '',
    method: ['POST','GET','DELETE','PUT','PATCH'],
    body: {
    },
    params:
  }
Base URL =
OpenAPI manifest check - ['OK', 'Error']
API Task response
{
}
```

<table><thead><tr><th width="180">Name</th><th>Description</th></tr></thead><tbody><tr><td>path</td><td>API endpoint path.</td></tr><tr><td>method</td><td>["GET", "POST", "DELETE", "PUT", "PATCH"]</td></tr><tr><td>body</td><td>API input parameters.</td></tr><tr><td>params</td><td>API input parameters.</td></tr><tr><td>Base URL</td><td>API Base URL.</td></tr><tr><td>OpenAPI Manifest check</td><td>Manifest check. <br>OK: Manifest is well written and executed.<br>FAIL: There are errors on the manifest schema.</td></tr><tr><td>API Task response</td><td>API endpoint output.</td></tr></tbody></table>

### create-api

{% code overflow="wrap" %}

```
Create the Truebit API Task and upload the Manifest to the local storage. As a result, it returns the taskId.
  
Usage:
  truebit create-api [options] <manifestPath>

Arguments:
  <manifestPath>  Path of the manifest.

OPTIONS:
  -h, --help    display help for command
```

{% endcode %}

#### Output

```
Executing the API task.
Your API task is ready.
Use the following taskId for execution or deployment: <taskId>
```

{% hint style="info" %}
Check this [example](/developing-truebit-tasks/how-to-create-api-tasks/api-task-examples) to get more details about the [Truebit API Task ](/developing-truebit-tasks/how-to-create-api-tasks)Manifest.
{% endhint %}

## Deploying Truebit Tasks

Use the `deploy` command to deploy your Truebit Task to the Coordination Hub. If API task authentication is required, use the `api-auth` command.

### deploy

{% code overflow="wrap" %}

```
Usage: truebit deploy [options] <namespace> <taskName>

Deploys and registers a new Truebit task specified by the --taskId parameter. Using the deploy command makes the Truebit task available for execution.

Arguments:
  namespace          Namespace to register the task in (lowercase)
  taskName           Name of the task (lowercase)

Options:
  --taskId <taskId>  Id of the task <Required>
  --meta <meta>      Meta information for the task (string between single quotes)
  -h, --help         Display help for command
```

{% endcode %}

#### Output

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>The function task has been deployed successfully.
</strong>The Task &#x3C;taskName> version &#x3C;version> was registered successfully in namespace &#x3C;namespace>
</code></pre>

### **api-auth**

{% code overflow="wrap" %}

```
Usage: truebit api-auth [options] <namespace> <taskname> <taskId> <authType> <authString>

Specify authentication for a truebit api task

Arguments:
  namespace   Namespace to register
  taskname    Taskname to register
  taskId      Id of the task
  authType    Type of authentication need for api task usage. One of: <aws-signature,basic-auth,custom-header>
  authString  Auth string is a comma separated value that represent auth method.
  
  	Examples:
  		AWS_SIGNATURE = "accessKey:<accesskey>,secretKey:<secretkey>"
  		BASIC_AUTH = "username:<username>,password:<password>"
  		CUSTOM_HEADER = "<customheader>"

Options:
  -h, --help  Display help for command
```

{% endcode %}

{% hint style="danger" %}
Only the user who deployed the task can upload the credentials.&#x20;
{% endhint %}

#### Output

```bash
Deploying the API Authentication credentials
The credentials were deployed successfully
```

## Managing Truebit Tasks

Use the `namespace` and `task` commands to manage access to your Truebit Tasks within your development team. To grant execution access for a deployed task, use the `auth` command.

### namespace

{% code overflow="wrap" %}

```
Usage: truebit namespace [options] [command]

The namespace command helps you group and manage different tasks under a single name, like an umbrella.
This name, called a namespace, can be anything that represents your tasks, such as the name of your company. Each task you create will be associated with a namespace.

Options:
  -h, --help                      Display help for command

Commands:
  register <namespace>            Register a new namespace
  transfer <namespace> <address>  Transfer a namespace
  grant <namespace> <address>     Grant access to a namespace
  revoke <namespace> <address>    Revoke access to a namespace
  help [command]                  display help for command

```

{% endcode %}

#### namespace register

{% code overflow="wrap" %}

```
Usage: truebit namespace register [options] <namespace>

Register a new namespace. The user who calls this command will become the owner of the registered namespace. Each namespace can have only one owner. The owner can grant access to other users using the grant command.

Arguments:
  namespace   Namespace to register

Options:
  -h, --help  Display help for command

```

{% endcode %}

#### Output

<pre class="language-bash"><code class="lang-bash">Registering namespace &#x3C;namespace>
<strong>The Namespace &#x3C;namespace> has been successfully registered.
</strong></code></pre>

#### namespace transfer

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit namespace transfer [options] <namespace> <address>

Change the owner of a namespace.
Only the current owner can use this command to grant access.

Arguments:
  namespace   Namespace to transfer
  address     Address to transfer namespace to

Options:
  -h, --help  Display help for command

```

{% endcode %}

#### Output

```bash
Transferring namespace <namespace> to the address <address>
The Namespace <namespace> has been successfully transferred to the <address>.
```

#### namespace grant

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit namespace grant [options] <namespace> <address>

Give a user access to the namespace.
Only the current owner can use this command to grant access.

Arguments:
  namespace   Namespace to grant access to
  address     Address to grant access to

Options:
  -h, --help  Display help for command

```

{% endcode %}

#### Output

```bash
Granting access to namespace <namespace> to the address <address>
The address <address> now has access to the namespace <namespace>.
```

#### namespace revoke

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit namespace revoke [options] <namespace> <address>

Take away a user's access to the namespace.
Only the current owner can use this command to revoke access.

Arguments:
  namespace   Namespace to revoke access from
  address     Address to revoke access from

Options:
  -h, --help  Display help for command

```

{% endcode %}

#### Output

```bash
Revoking access to namespace <namespace> to the address <address>
The address <address> does not have access to the namespace <namespace>.
```

### task

{% code overflow="wrap" %}

```
Usage: truebit task [options] [command]

Manages tasks within a specified namespace, facilitating the organization, tracking, and management of tasks across different projects or domains. This command serves as a gateway to various task-related operations such as registration, modification, and querying, thereby
enhancing project management and operational efficiency.

Options:
  -h, --help                                 Display help for command

Commands:
  label [options] <namespace> <taskName>     Assign a label to a registered task.
  disable [options] <namespace> <taskName>   Disable a registered task.
  enable [options] <namespace> <taskName>    Enable a registered task.
  get-task [options] <namespace> <taskName>  Retrieve information from a namespace and a taskName
  help [command]                             display help for command
```

{% endcode %}

#### task label

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit task label [options] <namespace> <taskName>

Set label for a task in a namespace

Arguments:
  namespace        Namespace of the task
  taskName         Name of the task

Options:
  --label <label>  Label for the task <Required>
  --ver <version>  Version of the task <Required>
  -h, --help       Display help for command

```

{% endcode %}

#### Output

```
Setting label {label} for the task: {taskName}.
The Label {label} has been successfully set for the task {taskName}.
```

#### task disable

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit task disable [options] <namespace> <taskName>

Disable task in a namespace --ver <version> or --label <label> can be used to disable specific task

Arguments:
  namespace        Namespace of the task
  taskName         Name of the task

Options:
  --ver <version>  Version of the task to disable <Required>
  --label <label>  Label for the task to disable <Required>
  -h, --help       Display help for command

```

{% endcode %}

#### Output

```bash
Disabling task {taskName}.
The Task {taskName} has been successfully disabled.
```

#### task enable

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit task enable [options] <namespace> <taskName>

Enable a task in a namespace --ver <version> or --label <label> can be used to enable specific task

Arguments:
  namespace            Namespace of the task
  taskName             Name of the task

Options:
  --ver <version>  Version of the task <Optional>
  --label <label>  Label for the task <Optional>
  -h, --help       Display help for command

```

{% endcode %}

#### Output

```bash
Enabling task {taskName}.
The Task {taskName} has been successfully enabled.
```

#### task get-task

{% code overflow="wrap" %}

```
Usage: truebit task get-task [options] <namespace> <taskName>

Get task information from a namespace and a taskname --ver or --label can be used to get specific task

Arguments:
  namespace        Namespace of the task
  taskName         Name of the task

Options:
  --ver <version>  Version of the task <Optional>
  --label <label>  Label for the task <Optional>
  -h, --help       Display help for command

```

{% endcode %}

#### Output

```
Getting information from the task {taskName}
{
  namespace: {namespace},
  taskId: {taskId},
  version: {version},
  meta: {metadata},
  nameSpaceOwner: {owner}
}
```

### auth

{% code overflow="wrap" %}

```
Usage: truebit auth [options] [command]

The auth command is responsible for managing the authorization for task execution. It allows the namespace owner to grant or deny access to addresses, ensuring that only authorized individuals can execute specific tasks.

Options:
  -h, --help                                 Display help for command

Commands:
  grant <namespace> <grantee>                Grant authorization to a grantee
  revoke <namespace> <grantee>               Revoke authorization from a grantee
  register <apiKey>                          Register an authorized API key
  deregister <apiKey>                        Deregister an authorized API key
  check-authorization <namespace> <grantee>  Check if an address is authorized
  get-payer <apiKeyHash>                     Get payer address from an API key
  new-apikey                                 Generate a new Api Key
  help [command]                             display help for command
```

{% endcode %}

#### auth grant

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit auth grant [options] <namespace> <grantee>

The auth grant command is responsible for granting access to a specific address within a namespace. The grantee will have the ability to execute the tasks stored within that namespace.

Arguments:
  namespace   Namespace containing the desired tasks
  grantee     Grantee to be authorized

Options:
  -h, --help  Display help for command
```

{% endcode %}

#### Output

```
Granting authorization to <grantee> in the namespace <namespace>
Authorization granted to <grantee> in the namespace <namespace>
```

#### auth revoke

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

<pre data-overflow="wrap"><code><strong>Usage: truebit auth revoke [options] &#x3C;namespace> &#x3C;grantee>
</strong>
The auth revoke command is responsible for revoking access from a specific address within a namespace. This command ensures that the specified address can no longer execute the tasks stored within that namespace.

Arguments:
  namespace   Namespace containing the desired tasks
  grantee     Grantee to be unauthorized

Options:
  -h, --help  Display help for command
</code></pre>

#### Output

```
Revoking authorization from <grantee> in the namespace <namespace>
Authorization revoked from <grantee> in the namespace <namespace>
```

#### auth register

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit auth register [options] <apiKey>

The auth register command is responsible for registering a specific API_KEY. Every execution made with this API_KEY will be charged to the user who registered it. This way, you can ensure that the user who registered the API_KEY is responsible for paying for all executions made with it.

Arguments:
  apiKey      API key to be registered

Options:
  -h, --help  Display help for command
```

{% endcode %}

#### Output

```
Registering API key <apiKey>
The API key <apiKey> was registered with the hash: <hashedApiKey>
```

#### auth deregister

{% hint style="info" %}
AVAX funds are required to execute this command.
{% endhint %}

{% code overflow="wrap" %}

```
Usage: truebit auth deregister [options] <apiKey>

The auth deregister command will revoke access to a specific API_KEY. After deregistration, any execution attempt using this API_KEY will result in a "not authorized" message.

Arguments:
  apiKey      API key to be deregistered

Options:
  -h, --help  Display help for command
```

{% endcode %}

#### Output

<pre><code>Deregistering API key &#x3C;apiKey>
<strong>The API key &#x3C;apiKey> was successfully deregistered
</strong></code></pre>

#### auth check-authorization

<pre data-overflow="wrap"><code>Usage: truebit auth check-authorization [options] &#x3C;namespace> &#x3C;grantee>
<strong>
</strong>The auth check-authorization command verifies if a specific address has permission to execute tasks in a particular namespace.

Arguments:
  namespace   Namespace of the tasks
  grantee     Check authorization for the grantee

Options:
  -h, --help  Display help for command
</code></pre>

#### Output

```
Checking authorization for <grantee> in namespace <namespace>
Grantee <grantee> is authorized in namespace <namespace>
```

#### auth get-payer

{% code overflow="wrap" %}

```
Usage: truebit auth get-payer [options] <apiKeyHash>

The auth get-payer command retrieves the payer address associated with a specific API_KEY.

Arguments:
  apiKeyHash  API key hash

Options:
  -h, --help  Display help for command
```

{% endcode %}

#### Output

```
Getting payer address from <apiKeyHash>
The payer address from the API Key Hash: <apiKeyHash> is <payerAddress>
```

#### auth new-apikey

```
Usage: truebit auth new-apikey [options]

Generate a new Api Key to be used for execution payment. The Api Key is a
unique identifier for the payer.

Options:
  -h, --help  Display help for command
```

#### Output

```bash
Api Key: <uuid>
```

## secret.json

The `secret.json` file is generated when you accept the Terms and Conditions for the first time. I**t stores essential user information, including your wallet and private key.** Keep this file secure, as it contains your credentials for accessing Truebit Verify.

```
{
  "privateKey": "0x************************************f108",    
  "address": "0x************************************6670F",
  "eula": "1740428091368"
  "RPC_URL": ""
}
```

<table><thead><tr><th align="center">Parameter</th><th align="center" valign="middle">Description</th></tr></thead><tbody><tr><td align="center">privateKey</td><td align="center" valign="middle">Your private key</td></tr><tr><td align="center">address</td><td align="center" valign="middle">Your wallet address</td></tr><tr><td align="center">eula</td><td align="center" valign="middle">Eula acceptance timestamp</td></tr><tr><td align="center">RPC_URL</td><td align="center" valign="middle"></td></tr></tbody></table>


# How to Create Function Tasks

Function Tasks verify and provide a transcript for the execution of serverless function code.

{% hint style="info" %}
Check the [Supported Languages](/developing-truebit-tasks/how-to-create-function-tasks/supported-languages) section to see the specific task preparation steps required for your development language.
{% endhint %}

## Prerequisites

There are several important considerations when writing Function Task code:&#x20;

* **Execution environment**: The task must run the same on any computer architecture and operating system. Therefore, Function Tasks execute in an isolated WebAssembly sandbox using our deterministic WASI implementation. Please, check the [WebAssembly ](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/webassembly)section for more information.
* **No network calls:** To provide maximum security, the execution environment does not provide network access. If you need to access data from an external source, consider using an [API Task](/developing-truebit-tasks/how-to-create-api-tasks).
* **Determinism**: The execution environment guarantees [determini](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/determinism)[sm](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/determinism) - All Function Tasks will produce the same outputs for given inputs when executed by any Truebit Verify node.

## Building A Function Task&#x20;

{% stepper %}
{% step %}

### Write Your Function Task Code

The task developer will create the code, following the best practices described below:

**Replace network operation with filesystem reads and writes**

If your program would normally read and write to network endpoints, you'll need to replace this with filesystem operations.

For example, instead of making an HTTP request to `example.com`,  read from the input.txt file. Click [here](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/fibonacci#in-out-parameters) to see an example.&#x20;

You can write results to the filesystem into an output file. Click [here](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/fibonacci#in-out-parameters) to see an example.

**Random Numbers**

If your program normally uses random numbers, in Truebit you will always get the same sequence. This is done to ensure a deterministic execution.

**Dates and Times**&#x20;

If your program would normally get date-time values, in Truebit you will always get the same value, which is "`1970.1.1 0:1:40`". This is done to ensure a deterministic execution.

**Output value**

The task must return a value. If the result is empty, the task will be marked as failed.
{% endstep %}

{% step %}

### Test Your Function Task

Once your code is ready for testing, the **development workflow involves two primary steps** using the Truebit CLI:

* **Build and Prepare**: Execute the [`build`](/developing-truebit-tasks/truebit-cli-reference) command to generate a WebAssembly [(WASM) file](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/webassembly). Truebit utilizes WebAssembly to ensure cross-platform consistency across any hardware or operating system. During this stage, the file is automatically instrumented to guarantee deterministic execution.
* **Execute and Test**: Run the [`start`](/developing-truebit-tasks/truebit-cli-reference#start) command to deploy and verify your compiled code within the Truebit environment.

{% hint style="success" %}
Repeat this process every time your source code has been changed.
{% endhint %}
{% endstep %}

{% step %}

### Deploy The Function Task

Once the task is ready for being used by others, the [Task Developer](/overview/how-do-you-intend-to-use-truebit#task-developers) will deploy it to make it available for being called by the [Task Requester](/overview/how-do-you-intend-to-use-truebit#task-requesters).

#### Authorize The Task execution

The Task Authorization process is an optional step. This step allows the [Task Developer](/overview/how-do-you-intend-to-use-truebit#task-developers) to define who has permission to execute the deployed task.

{% hint style="info" %}
Click Here to see more information about the [**Task Authorization**](/developing-truebit-tasks/task-authorization) process.&#x20;
{% endhint %}
{% endstep %}

{% step %}

### Execute The Function Task

The [Task Requester](/overview/how-do-you-intend-to-use-truebit#task-requesters) executes the task using the [Task Execution Endpoint](/integrating-truebit-tasks/api-task-execution) from the Truebit API
{% endstep %}
{% endstepper %}

.


# Function Task Examples

### Common Language Examples

|                                                         Example                                                        |                                    Description                                   |
| :--------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------: |
|        [**Fibonacci**](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/fibonacci)        | A simple function to calculate the Fibonacci sequence based on an input integer. |
| [**Reverse Alphabet**](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet) |            A simple function to reverse characters in an input string.           |

### Js Examples

<table><thead><tr><th align="center">Example</th><th align="center">Description</th><th data-hidden></th></tr></thead><tbody><tr><td align="center"><a href="/pages/yWSjj2mdyWhQPuqsDkSk"><strong>Sha256 using bun.js</strong></a></td><td align="center">A simple function to encrypt using bun.js.</td><td></td></tr><tr><td align="center"><a href="/pages/CBRUmJJ9lOFiuroNTbSq"><strong>Sha256 using Deno</strong></a></td><td align="center">A simple function to encrypt using Deno.</td><td></td></tr><tr><td align="center"><a href="/pages/4QaOEZU1hmjgK1CB0oWN"><strong>ECDSA Signature Verification</strong></a></td><td align="center">A simple signature verification using the ECDSA algorithm.</td><td></td></tr></tbody></table>

### Python Examples

<table><thead><tr><th align="center">Example</th><th align="center">Description</th><th data-hidden></th></tr></thead><tbody><tr><td align="center">​<a href="https://app.gitbook.com/o/-MZ9ineVYRIEI8Pk97Ka/s/AfNTfJ48HTdTVB8EdvCs/~/diff/~/changes/310/developing-truebit-tasks/writing-function-tasks/function-task-examples/numpy-example"><strong>NumPy</strong></a></td><td align="center">A simple example showing how to interact with the library and process an external file.</td><td></td></tr></tbody></table>


# Fibonacci

### Description

**The Fibonacci sequence is a set of integers** (the Fibonacci numbers) that starts with a zero, followed by a one, then by another one, and then by a series of steadily increasing numbers. The sequence follows the rule that each number is equal to the sum of the preceding two numbers.

The Fibonacci sequence begins with the following 14 integers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ...

From the third number onward, each one follows the same rule. For example, the seventh number is 8, which comes after 3 and 5, and 3 + 5 = 8.

The sequence can theoretically continue to infinity, using the same formula for each new number. Some resources show the Fibonacci sequence starting with a one instead of a zero, but this is fairly uncommon.

### Executing Fibonacci <a href="#using-bacalhau-to-execute-duckdb-processing" id="using-bacalhau-to-execute-duckdb-processing"></a>

We use Truebit to execute the Fibonacci task to get a verified result.

### The Code

You can find the Fibonacci example within the folder *truebit-nextgen-examples/function-tasks/\<language>/fibonacci*.&#x20;

{% tabs %}
{% tab title="Rust" %}
📁 src\
└─ 📄 main.rs \
📄 Cargo.toml\
📄 Cargo.lock

{% hint style="info" %}
The target folder and the Cargo.lock file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli
{% endhint %}
{% endtab %}

{% tab title="C" %}
📁 src \
└─ 📄 main.c\
📄 compile.sh

{% hint style="info" %}
The xxx folder and the xxxx file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli
{% endhint %}
{% endtab %}

{% tab title="C++" %}
📁 src \
└─ 📄 main.cpp\
&#x20;📄 compile.sh

{% hint style="info" %}
The xxx folder and the xxxx file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli
{% endhint %}
{% endtab %}

{% tab title="Js" %}
📁 src \
└─ 📄 main.js\
&#x20;📁 dist\
└─ 📄 main.js\
📄 package-lock.json\
📄 package.json

{% hint style="info" %}
The ***dist*** folder and the ***main.js*** file are going to be generated after running the `npx rollup -c` command. More information click [here](/developing-truebit-tasks/how-to-create-function-tasks/supported-languages#development-flow).
{% endhint %}
{% endtab %}

{% tab title="Python" %}
📁 src \
└─ 📄 task.py
{% endtab %}
{% endtabs %}

#### Source

{% tabs %}
{% tab title="Rust" %}
**main.rs**

<pre class="language-rust" data-overflow="wrap" data-line-numbers><code class="lang-rust"><strong>fn fibonacci(n: u32) -> u64 {
</strong>    if n == 0 {
        return 0;
    } else if n == 1 {
        return 1;
    }

    let mut a = 0;
    let mut b = 1;
    let mut c = 0;

    for _i in 2..=n {
        c = a + b;
        a = b;
        b = c;
    }

    return c;
}

fn run_task(input: String) -> String {
    fibonacci(input.parse().unwrap()).to_string()
}

fn main() {
    let input: String =
        std::fs::read_to_string("input.txt").expect("Could not read from input.txt");
    let output: String = run_task(input);
    std::fs::write("output.txt", output).expect("Could not write to output.txt");
}
</code></pre>

{% endtab %}

{% tab title="C" %}
**main.c**

{% code overflow="wrap" lineNumbers="true" %}

```c
#include <stdio.h>
#include <stdlib.h>

unsigned long long fibonacci(int n) {
    if (n == 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    }

    unsigned long long a = 0;
    unsigned long long b = 1;
    unsigned long long c = 0;

    for (int i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }

    return c;
}

char* runTask(const char* input) {
    int inputValue = atoi(input);
    unsigned long long result = fibonacci(inputValue);
    
    char* output = (char*)malloc(20); 
    sprintf(output, "%llu", result);
    
    return output;
}

int main() {
    FILE* inputFile = fopen("input.txt", "r");
    if (inputFile == NULL) {
        perror("Error opening input.txt");
        return 1;
    }

    char inputBuffer[256]; 
    if (fgets(inputBuffer, sizeof(inputBuffer), inputFile) == NULL) {
        perror("Error reading input.txt");
        fclose(inputFile);
        return 1;
    }

    fclose(inputFile);

    char* output = runTask(inputBuffer);

    FILE* outputFile = fopen("output.txt", "w");
    if (outputFile == NULL) {
        perror("Error opening output.txt");
        free(output);
        return 1;
    }

    fprintf(outputFile, "%s", output);
    fclose(outputFile);
    free(output);

    printf("output.txt\n");

    return 0;
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
**main.cpp**

{% code overflow="wrap" lineNumbers="true" %}

```cpp
#include <iostream>
#include <fstream>
using namespace std;

unsigned long long fibonacci(int n) {
    if (n == 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    }

    unsigned long long a = 0;
    unsigned long long b = 1;
    unsigned long long c = 0;

    for (int i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }

    return c;
}

string runTask(const string& input) {
    int inputValue = stoi(input);
    return to_string(fibonacci(inputValue));
}

int main() {
    ifstream inputFile("input.txt");
    if (!inputFile) {
        cerr << "Could not read from input.txt" << endl;
        return 1;
    }

    string input;
    getline(inputFile, input);
    inputFile.close();

    string output = runTask(input);

    ofstream outputFile("output.txt");
    if (!outputFile) {
        cerr << "Could not write to output.txt" << endl;
        return 1;
    }

    outputFile << output << endl;
    outputFile.close();

    cout << "Output written to output.txt" << endl;

    return 0;
}
```

{% endcode %}
{% endtab %}

{% tab title="Js" %}
**fibonacci.js**

{% code overflow="wrap" lineNumbers="true" %}

```javascript
import fs from 'fs';

function fibonacci(n) {
    if (n === 0) {
        return 0;
    } else if (n === 1) {
        return 1;
    }

    let a = 0;
    let b = 1;
    let c = 0;

    for (let i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }

    return c;
}

function runTask(input) {
    return fibonacci(parseInt(input)).toString();
}

let data = fs.readFileSync('input.txt', 'utf8')
const output = runTask(data);
fs.writeFileSync('output.txt', output)
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code overflow="wrap" lineNumbers="true" %}

```python
def fibonacci(n):
    """Calculate the nth Fibonacci number iteratively."""
    if n == 0:
        return 0
    elif n == 1:
        return 1

    a, b = 0, 1
    for _ in range(2, n + 1):
        c = a + b
        a = b
        b = c
    return c

def run_task(input_string):
    """Convert input string to integer, compute Fibonacci, and return as string."""
    return str(fibonacci(int(input_string)))

def main():
    """Main function to read, process, and write Fibonacci number to a file."""
    try:
        with open("input.txt", "r") as file:
            input_string = file.read().strip()
    except FileNotFoundError:
        print("Error: The file 'input.txt' does not exist.")
        return
    except Exception as e:
        print(f"An error occurred while reading 'input.txt': {e}")
        return

    try:
        output_string = run_task(input_string)
    except ValueError:
        print("Error: Input must be an integer.")
        return
    except Exception as e:
        print(f"An error occurred while processing the input: {e}")
        return

    try:
        with open("output.txt", "w") as file:
            file.write(output_string)
    except Exception as e:
        print(f"An error occurred while writing to 'output.txt': {e}")

if __name__ == "__main__":
    main()
```

{% endcode %}

{% endtab %}
{% endtabs %}

#### In/Out Parameters

In order to send parameters to the Truebit task, you need to open the "input.txt" file and get the value from there. For now, only one input parameter is allowed.

{% tabs %}
{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
let input: String = std::fs::read_to_string("input.txt").expect("Could not read from input.txt");
```

{% endcode %}
{% endtab %}

{% tab title="C" %}
{% code overflow="wrap" %}

```c
FILE* inputFile = fopen("input.txt", "r");
if (inputFile == NULL) {
    perror("Error opening input.txt");
    return 1;
}

char inputBuffer[256]; 
if (fgets(inputBuffer, sizeof(inputBuffer), inputFile) == NULL) {
    perror("Could not read from input.txt");
    fclose(inputFile);
    return 1;
}

fclose(inputFile);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code overflow="wrap" %}

```cpp
ifstream inputFile("input.txt");
if (!inputFile) {
    cerr << "Could not read from input.txt" << endl;
    return 1;
}

string input;
getline(inputFile, input);
inputFile.close();
```

{% endcode %}
{% endtab %}

{% tab title="Js" %}
{% code overflow="wrap" %}

```javascript
let data = fs.readFileSync('input.txt', 'utf8')
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}

```python
with open("input.txt", "r") as file:
input_string = file.read().strip()
```

{% endtab %}
{% endtabs %}

To retrieve the output value from the Truebit task, you need save it in the "output.txt" file.

{% tabs %}
{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
std::fs::write("output.txt", output).expect("Could not write to output.txt");
```

{% endcode %}
{% endtab %}

{% tab title="C" %}
{% code overflow="wrap" %}

```c
FILE* outputFile = fopen("output.txt", "w");
if (outputFile == NULL) {
    perror("Error opening output.txt");
    free(output);
    return 1;
}

fprintf(outputFile, "%s", output);
fclose(outputFile);
free(output);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code overflow="wrap" %}

```cpp
ofstream outputFile("output.txt");
if (!outputFile) {
    cerr << "Could not write to output.txt" << endl;
    return 1;
}

outputFile << output << endl;
outputFile.close();

```

{% endcode %}
{% endtab %}

{% tab title="Js" %}
{% code overflow="wrap" %}

```javascript
fs.writeFileSync('output.txt', output)
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}

```python
with open("output.txt", "w") as file:
file.write(output_string)
```

{% endtab %}
{% endtabs %}

### Trying Out

We will use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to [compile](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-2-build-the-source-code) and [test](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

#### Step 1: Create The Fibonacci Source Code

Within the src folder you will find a file called main in the case of *Rust, C, C++, JS,* and *task.py* in the case of Python. This is the fibonacci implementation that will be used for testing purpose.

#### Step 2: Build The Source Code

Execute the [build](/developing-truebit-tasks/truebit-cli-reference#build) command against Truebit node to get an instrumented Truebit task.

{% hint style="info" %}
This in an example of how to build a JS task.&#x20;
{% endhint %}

{% code overflow="wrap" %}

```bash
truebit build truebit-nextgen-examples/function-tasks/js/fibonacci/dist -l js
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Building the function task
Your function task is ready.
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

{% hint style="info" %}
The `taskId` will always starts with the language prefix + "\_" + cID
{% endhint %}

#### Step 3: Try The Code

Execute the [start](/developing-truebit-tasks/truebit-cli-reference#start) command against the Truebit node to test our Algorithm. You will need to submit the instrumented task id + the input parameter.

{% code overflow="wrap" %}

```bash
truebit start <taskId> 10
```

{% endcode %}

* \[`taskId`]: Add the taskId generated in the previous step.&#x20;

#### Output

{% code overflow="wrap" %}

```bash
Executing the function Task
Execution Id: e406e754-b90b-4c62-9394-2cf0bb2c5647
Task executed with status: succeed
Task executed with result: 55
Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬──────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼──────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 1907033199  │ 577      │
│ Nested calls  │ 'Calls'       │ 65536         │ 6387  │ 6352        │ 10       │
│ Frame memory  │ 'Bytes'       │ 524288        │ 20115 │ 19073       │ 26       │
│ System memory │ '64 Kb pages' │ 2048          │ 87    │ '𝚫 1'       │ 24       │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴──────────┘
```

{% endcode %}

#### Step 4: Deploy The Task

Last, but not least, execute the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command to deploy our task to the coordination hub, so that anyone with the namespace, taskname and the [API key](/developing-truebit-tasks/task-authorization#task-authorization-process) can execute it.

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>truebit deploy &#x3C;namespace> &#x3C;taskname> --taskId
</strong></code></pre>

* \[`taskId`]: Add the taskId generated in step 2.

**Output**

{% code overflow="wrap" %}

```bash
The function task has been deployed successfully.
The Task <taskName> version <version> was registered successfully in namespace <namespace>
```

{% endcode %}


# Reverse Alphabet

### Description

**Reverse Alphabet is a simple yet powerful tool that takes any individual word as input and promptly returns its reverse.**

### Executing Reverse Alphabet <a href="#using-bacalhau-to-execute-duckdb-processing" id="using-bacalhau-to-execute-duckdb-processing"></a>

We use Truebit to execute the Reverse Alphabet task to get a verified result.

### The Code

You can find the Reverse Alphabet example within the folder *truebit-nextgen-examples/function-tasks/\<language>/reverse-alphabet.*

{% tabs %}
{% tab title="Rust" %}
📁 src \
└─ 📄 main.rs \
📄 Cargo.toml\
📄 Cargo.lock

{% hint style="info" %}
The target folder and the Cargo.lock file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli.
{% endhint %}
{% endtab %}

{% tab title="C" %}
📁 src \
└─ 📄 main.c\
📄 compile.sh

{% hint style="info" %}
The xxx folder and the xxxx file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli.
{% endhint %}
{% endtab %}

{% tab title="C++" %}
📁 src \
└─ 📄 main.cpp\
📄 compile.sh

{% hint style="info" %}
The xxx folder and the xxxx file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli.
{% endhint %}
{% endtab %}

{% tab title="Js" %}
📁 src \
└─ 📄 main.js\
📄 package-lock.json\
📄 package.json
{% endtab %}

{% tab title="Python" %}
📁 src \
└─ 📄 task.py
{% endtab %}
{% endtabs %}

#### Source

{% tabs %}
{% tab title="Rust" %}
**main.rs**

{% code overflow="wrap" lineNumbers="true" %}

```rust
fn run_task(input: String) -> String {
    input.chars().rev().collect()
}

fn main() {
    let input: String =
        std::fs::read_to_string("input.txt").expect("Could not read from input.txt");
    let output = run_task(input);
    std::fs::write("output.txt", output).expect("Could not write to output.txt");
}
```

{% endcode %}
{% endtab %}

{% tab title="C" %}
**main.c**

```c
#include <stdio.h>
#include <stdlib.h>

int fibonacci(int n) {
    int a = 0, b = 1, c;
    for (int i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }
    return b;
}

int main() {
    FILE *inputFile = fopen("input.txt", "r");
    if (inputFile == NULL) {
        perror("Error opening input.txt");
        return 1;
    }

    int input;
    if (fscanf(inputFile, "%d", &input) != 1) {
        perror("Error reading input.txt");
        fclose(inputFile);
        return 1;
    }

    fclose(inputFile);

    int result = fibonacci(input);

    FILE *outputFile = fopen("output.txt", "w");
    if (outputFile == NULL) {
        perror("Error opening output.txt");
        return 1;
    }

    fprintf(outputFile, "%d", result);
    fclose(outputFile);

    return 0;
}
```

{% endtab %}

{% tab title="C++" %}
**main.cpp**

```cpp
#include <iostream>
#include <fstream>

int fibonacci(int n) {
    int a = 0, b = 1, c;
    for (int i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }
    return b;
}

int main() {
    std::ifstream inputFile("input.txt");
    if (!inputFile.is_open()) {
        std::cerr << "Error opening input.txt" << std::endl;
        return 1;
    }

    int input;
    if (!(inputFile >> input)) {
        std::cerr << "Error reading input.txt" << std::endl;
        inputFile.close();
        return 1;
    }

    inputFile.close();

    int result = fibonacci(input);

    std::ofstream outputFile("output.txt");
    if (!outputFile.is_open()) {
        std::cerr << "Error opening output.txt" << std::endl;
        return 1;
    }

    outputFile << result;
    outputFile.close();

    return 0;
}
```

{% endtab %}

{% tab title="Js" %}
**main.js**

```javascript
import fs from 'fs';

function run_task(input) {
    return input.split('').reverse().join('');
}

let input = fs.readFileSync('input.txt', 'utf8');
const output = run_task(input);
fs.writeFileSync('output.txt', output);
```

{% endtab %}

{% tab title="Python" %}
{% code overflow="wrap" lineNumbers="true" %}

```python
def run_task(input_str):
    """Reverses the input string.

    Args:
        input_str: The string to be reversed. 

    Returns:
        The reversed string.
    """

    return input_str[::-1]

if __name__ == "__main__":
    with open("input.txt", "r") as input_file:
        input_str = input_file.read()

    output_str = run_task(input_str)

    with open("output.txt", "w") as output_file:
        output_file.write(output_str)

    print(output_str)
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### In/Out Parameters

In order to send parameters to the Truebit task, you need to open the *"input.txt"* file and get the value from there. For now, only one input parameter is allowed.

{% tabs %}
{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
let input: String = std::fs::read_to_string("input.txt").expect("Could not read from input.txt");
```

{% endcode %}
{% endtab %}

{% tab title="C" %}

```c
FILE* inputFile = fopen("input.txt", "r");
if (inputFile == NULL) {
    perror("Error opening input.txt");
    return 1;
}

char inputBuffer[256]; 
if (fgets(inputBuffer, sizeof(inputBuffer), inputFile) == NULL) {
    perror("Could not read from input.txt");
    fclose(inputFile);
    return 1;
}

fclose(inputFile);
```

{% endtab %}

{% tab title="C++" %}

```cpp
ifstream inputFile("input.txt");
if (!inputFile) {
    cerr << "Could not read from input.txt" << endl;
    return 1;
}

string input;
getline(inputFile, input);
inputFile.close();
```

{% endtab %}

{% tab title="Js" %}

```javascript
let data = fs.readFileSync('input.txt', 'utf8')   
```

{% endtab %}

{% tab title="Python" %}

```python
with open("input.txt", "r") as file:
input_string = file.read().strip()
```

{% endtab %}
{% endtabs %}

To retrieve the output value from the Truebit task, you need save it in the *"output.txt"* file.

{% tabs %}
{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
std::fs::write("output.txt", output).expect("Could not write to output.txt");
```

{% endcode %}
{% endtab %}

{% tab title="C" %}

```c
FILE* outputFile = fopen("output.txt", "w");
if (outputFile == NULL) {
    perror("Error opening output.txt");
    free(output);
    return 1;
}

fprintf(outputFile, "%s", output);
fclose(outputFile);
free(output);tr    
```

{% endtab %}

{% tab title="C++" %}

```cpp
ofstream outputFile("output.txt");
if (!outputFile) {
    cerr << "Could not write to output.txt" << endl;
    return 1;
}

outputFile << output << endl;
outputFile.close();
```

{% endtab %}

{% tab title="Js" %}

```javascript
fs.writeFileSync('output.txt', output)
```

{% endtab %}

{% tab title="Python" %}

```python
with open("output.txt", "w") as file:
file.write(output_string)
```

{% endtab %}
{% endtabs %}

### Trying Out

We will use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to [compile](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-2-build-the-source-code) and [test](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

#### Step 1: Create The Reverse Alphabet Source Code

Within the *src folder* you will find a file called main in the case of *Rust, C, C++, JS,* and *task.py* in the case of *Python*. This is the Reverse Alphabet implementation that will be used for testing purpose.

#### Step 2: Build The Source Code

Execute the [build](/developing-truebit-tasks/truebit-cli-reference#build) command against Truebit node to get an instrumented Truebit task

{% hint style="info" %}
This in an example of how to build a JS task.&#x20;
{% endhint %}

{% code overflow="wrap" %}

```bash
truebit build truebit-nextgen-examples/function-tasks/js/reverse-alphabet/dist -l js
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Building the function task
Your function task is ready.
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

{% hint style="info" %}
The taskId will always starts with the language prefix + "\_" + cID
{% endhint %}

#### Step 3: Try The Code

Execute the [start](/developing-truebit-tasks/truebit-cli-reference#start) command against the Truebit node to test our Algorithm. You will need to submit the instrumented task id + the input parameter.

{% code overflow="wrap" %}

```bash
truebit start js_d9254bbb26c626f7b1c6d20550aed4df34cbd6a9bf7558ae42396e6a4676d5a9 Hello_World
```

{% endcode %}

\[taskId]: Add the `taskId` generated in the previous step.&#x20;

#### Output

```bash
Executing the function Task
Execution Id: 50e9408a-2a04-469d-b493-d9b27a12c771
Task executed with status: succeed
Task executed with result: dlroW_olleH
Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬──────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼──────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 1906503210  │ 577      │
│ Nested calls  │ 'Calls'       │ 65536         │ 6372  │ 6339        │ 10       │
│ Frame memory  │ 'Bytes'       │ 524288        │ 20023 │ 19034       │ 26       │
│ System memory │ '64 Kb pages' │ 2048          │ 87    │ '𝚫 1'       │ 24       │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴──────────┘
```

#### Step 4: Deploy the task

Last, but not least, execute the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command to effectively deploy our task to the coordination hub, so that anyone with the namespace, taskname and the [API key](/developing-truebit-tasks/task-authorization#task-authorization-process) can execute it.

{% code overflow="wrap" %}

```bash
truebit deploy <namespace> <taskname> --taskId 
```

{% endcode %}

* \[`taskId`]: Add the taskId generated in step 2

#### Output

{% code overflow="wrap" %}

```bash
The function task has been deployed successfully.
The Task <taskName> version <version> was registered successfully in namespace <namespace>
```

{% endcode %}


# Encrypt Sha256 Using bun.js

### Description

**This is a simple example of how to calculate a message hash and output the results formatted as a hex string.**

### Encrypting Sha256 Using Bun.js <a href="#using-bacalhau-to-execute-duckdb-processing" id="using-bacalhau-to-execute-duckdb-processing"></a>

To get a verified result, we can use Truebit to execute the *Sha256* task.

### The Code

You can find the "Encrypt Sha256" using *bun.js* example within the folder *truebit-nextgen-examples/function-tasks/js/sha256-bunjs.*

{% tabs %}
{% tab title="Js" %}
📄 main.js
{% endtab %}
{% endtabs %}

### Trying Out

We will use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to [compile](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-2-build-the-source-code) and [test](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

#### Step 1: Create The Sha256 Source Code

You will find a file called main.js in the root folder.

#### Step 2: Build The Source Code

Execute the [build](/developing-truebit-tasks/truebit-cli-reference#build) command against Truebit node to get an instrumented Truebit task.

{% code overflow="wrap" %}

```bash
truebit build truebit-nextgen-examples/function-tasks/js/sha256-bunjs -l js
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Building the function task
Your function task is ready.
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

#### Step 3: Try The Code

Execute the [start](/developing-truebit-tasks/truebit-cli-reference#start) command against the Truebit node to test our Algorithm.&#x20;

{% code overflow="wrap" %}

```bash
truebit start <taskId> Truebit
```

{% endcode %}

* \[taskId]: Add the `taskId` generated in the previous step.&#x20;

#### Output

{% code overflow="wrap" fullWidth="false" %}

```bash
Executing the function Task
Execution Id: fa1ec9a7-aa7f-4676-a4fc-fedfa7fbd033
Task executed with status: succeed
Task executed with result: 359030d9e4e3b12d50b0b3bec7a25e9491d6618a4432ced99448f947cfc71d01
Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬──────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼──────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 7114147279  │ 155      │
│ Nested calls  │ 'Calls'       │ 65536         │ 15011 │ 14964       │ 4        │
│ Frame memory  │ 'Bytes'       │ 524288        │ 46220 │ 44909       │ 11       │
│ System memory │ '64 Kb pages' │ 2048          │ 160   │ '𝚫 1'       │ 13       │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴──────────┘
```

{% endcode %}

#### Step 4: Deploy The Task

Last, but not least, Execute the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command to deploy our task to the coordination hub, so that anyone with the namespace, taskname and the [API key](/developing-truebit-tasks/task-authorization#task-authorization-process) can execute it.

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>truebit deploy &#x3C;namespace> &#x3C;taskname> --taskId &#x3C;taskId>
</strong></code></pre>

* \[`taskId`]: Add the taskId generated in step 2.

#### Output

{% code overflow="wrap" %}

```
The function task has been deployed successfully.
The Task <taskName> version <version> was registered successfully in namespace <namespace>
```

{% endcode %}


# Encrypt Sha256 Using Deno

### Description

**This is a simple example of how to calculate a message hash and output the results formatted as a hex string.**

### Encrypting Sha256 Using Deno <a href="#using-bacalhau-to-execute-duckdb-processing" id="using-bacalhau-to-execute-duckdb-processing"></a>

To get a verified result, we can use Truebit to execute the *sha256* task.

### The Code

You can find the "*encrypt sha256*" using deno example within the folder *truebit-nextgen-examples/function-tasks/js/sha256-deno.*

{% tabs %}
{% tab title="Js" %}
📄 main.js
{% endtab %}
{% endtabs %}

### Trying Out

We will use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to [compile](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-2-build-the-source-code) and [test](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

#### Step 1: Create The Sha256 Source Code

You will find a file called main.js in the root folder.

#### Step 2: Build The Source Code

Execute the [build](/developing-truebit-tasks/truebit-cli-reference#build) command against Truebit node to get an instrumented Truebit task.

{% code overflow="wrap" %}

```bash
truebit build truebit-nextgen-examples/function-tasks/js/sha256-deno -l js
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Building the function task
Your function task is ready.
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

#### Step 3: Try The Code

Execute the [start](/developing-truebit-tasks/truebit-cli-reference#start) command against the Truebit node to test our Algorithm.&#x20;

{% code overflow="wrap" %}

```bash
truebit start <taskId> Truebit
```

{% endcode %}

* \[taskId]: Add the `taskId` generated in the previous step.&#x20;

#### Output

{% code overflow="wrap" fullWidth="false" %}

```bash
Executing the function Task
Execution Id: f8881ca9-3d20-41da-9de8-5e789f59f12f
Task executed with status: succeed
Task executed with result: 359030d9e4e3b12d50b0b3bec7a25e9491d6618a4432ced99448f947cfc71d01
Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬──────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼──────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 2287576597  │ 481      │
│ Nested calls  │ 'Calls'       │ 65536         │ 7255  │ 7216        │ 9        │
│ Frame memory  │ 'Bytes'       │ 524288        │ 22735 │ 21665       │ 23       │
│ System memory │ '64 Kb pages' │ 2048          │ 93    │ '𝚫 1'       │ 22       │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴──────────┘
```

{% endcode %}

#### Step 4: Deploy The Task

Last, but not least, Execute the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command to deploy our task to the coordination hub, so that anyone with the namespace, taskname and the [API key](/developing-truebit-tasks/task-authorization#task-authorization-process) can execute it.

{% code overflow="wrap" %}

```bash
truebit deploy <namespace> <taskname> --taskId <taskId>
```

{% endcode %}

* \[`taskId`]: Add the taskId generated in step 2

#### Output

{% code overflow="wrap" %}

```
The function task has been deployed successfully.
The Task <taskName> version <version> was registered successfully in namespace <namespace>
```

{% endcode %}


# ECDSA Signature Verification

### Description

**This task is an example on how to compute a signature verification using the ECDSA algorithm,** the one used in EVM blockchains like Ethereum, Polygon, Hyperledger Besu, Avalanche C-Chain and others. It takes several paramaters as an input, all of them contained in an input.txt file provided as example:&#x20;

1. Test string that was signed.
2. Signature with the r, s, v components.
3. Address that signed the message.

It will return a boolean indicating if the signature validates correctly.

### Executing ECDSA Verification Example <a href="#using-bacalhau-to-execute-duckdb-processing" id="using-bacalhau-to-execute-duckdb-processing"></a>

In order to get a verified result, we can use Truebit to execute the sign-verify task.

### The Code

You can find the ECDSA signature verification example within the folder *truebit-nextgen-examples/function-tasks/js/ecdsa-sign-verify*

{% tabs %}
{% tab title="Js" %}
📁 src \
└─📄 ecdsa-verify.js\
📁 dist\
└─main.js\
📄 package-lock.json\
📄 package.json\
📄 rollup.config.mjs

{% hint style="info" %}
The ***dist*** folder and the ***main.js*** file are going to be generated after running the `npx rollup -c` command. More information click [here](/developing-truebit-tasks/how-to-create-function-tasks/supported-languages#development-flow).
{% endhint %}
{% endtab %}
{% endtabs %}

#### Source

{% tabs %}
{% tab title="Js" %}
**ecdsa-verify.js**

{% code overflow="wrap" lineNumbers="true" %}

```javascript
/*
    Signee address recoverer and validator
    ======================================
    
    This task is an example on how to compute a signature verification using the ECDSA algorithm, the one used in EVM blockchains like Ethereum, Polygon, Hyperledger Besu, Avalanche C-Chain and others. It takes several paramaters as an input, all of them contained in an input.txt file provided as example: 

    Input parameters (input.txt)
    ----------------------------

        A json-formatted file. See the example below:

            {
                "messageHash": "0x13260446136602c31107aa5e08571c276026b60c5156c1a564e268f3ab08492c",
                "signature": {
                    "r": "0x7097b9a0810d13e60182f261708c2c260e86ea09853cd48b184a5a4b4ea08c02",
                    "s": "0x087bd86b8cdee3aec88ac365ec533c9a111e5b5586c4941a790ca46970c3f380",
                    "v": 28
                },
                "address": "0x63f9a92d8d61b48a9fff8d58080425a3012d05c8"
            }
        
        Fields:

            messageHash: "0x" + hex-encoded data (ASCII string, 66 chars).
            signature: ECDSA signature, divided in its 'r', 's' and 'v'
                       components, as specified below.
                r: "0x" + hex-encoded data (ASCII string, 64 chars).
                s: "0x" + hex-encoded data (ASCII string, 64 chars).
                v: numeric parameter.
            address: "0x" + hex-encoded data (ASCII string, 42 chars).

    Output values (output.txt)
    --------------------------

        A JSON-formatted file. See the example below:

            {
                "declaredAddress": "0x63f9a92d8d61b48a9fff8d58080425a3012d05c8",
                "derivedAddress": "0x63f9a92d8d61b48a9fff8d58080425a3012d05c8",
                "match": true
            }
*/

const fs = require('fs');
const elliptic = require('elliptic');
const keccak256 = require('js-sha3').keccak256;
const bn = require('bn.js');

function checkSignature(messageHash, signature, address) {
    const ec = new elliptic.ec('secp256k1');
    const bnHash = new bn(messageHash, 16);
    const recoveryByteV = signature.v - 27;
    const pubKeyRecovered = ec.recoverPubKey(bnHash, signature, recoveryByteV).encode('hex');
    const pubKeyHash = keccak256(Buffer.from(pubKeyRecovered.slice(2), 'hex'));
    const derivedAddress = pubKeyHash.slice(-40);

    return {
        declaredAddress: '0x' + address,
        derivedAddress: '0x' + derivedAddress,
        match: address === derivedAddress
    }
}

function fixHash(input, key) {
    if (typeof input[key] !== 'string') {
        throw (`invalid type on input key '${key}', not a string.`);
    }
    input[key] = input[key].replace('0x', '').toLowerCase();
}


const main = () => {
    const inputJson = fs.readFileSync('input.txt', 'utf-8');
    let inputObj = JSON.parse(inputJson);

    fixHash(inputObj, 'messageHash');
    fixHash(inputObj.signature, 'r');
    fixHash(inputObj.signature, 's');
    fixHash(inputObj, 'address');

    const outputObj = checkSignature(inputObj.messageHash, inputObj.signature, inputObj.address);
    const outputJson = JSON.stringify(outputObj, null, 4);
    fs.writeFileSync('output.txt', outputJson);
    console.log(outputJson);
}

main();
```

{% endcode %}

Recommended configuration for Rollup tool (file ***rollup.config.mjs***):&#x20;

```javascript
import nodeResolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import pluginJson from '@rollup/plugin-json';

export default [
    {
        input: 'src/ecdsa-verify.js',
        output: {
            file: 'dist/main.js',
            format: 'es',
            name: 'ecdsa',
        },
        plugins: [
            nodeResolve(),
            commonjs(),
            pluginJson(),
        ],
    }
]
```

{% endtab %}
{% endtabs %}

#### In/Out Parameters

In order to send parameters to the Truebit task, you need to open the "input.txt" file and get the value from there. For now, only one input parameter is allowed.

{% tabs %}
{% tab title="Js" %}
{% code overflow="wrap" %}

```javascript
inputJson = fs.readFileSync('input.txt', 'utf-8');
```

{% endcode %}
{% endtab %}
{% endtabs %}

In order to retrieve the output value from the Truebit task, you need save it in the "output.txt" file.

{% tabs %}
{% tab title="Js" %}
{% code overflow="wrap" %}

```javascript
fs.writeFileSync('output.txt', outputJson);
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Trying Out

We will use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to [compile](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-2-build-the-source-code) and [test](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

#### Step 1: Create The Ecdsa-Verify Source Code

{% hint style="info" %}
If you are working in JS, remember to run the Rollup command in order to bundle all the code and dependencies within a single main.js file located at `/dist` folder.&#x20;

`npx rollup -c`
{% endhint %}

You will find a file called main.js within the folder /dist (This is the file generated by the Rollup tool that will be used for testing purposes).

#### Step 2: Build The Source Code

Execute the [build](/developing-truebit-tasks/truebit-cli-reference#build) command against Truebit node to get an instrumented Truebit task.

{% code overflow="wrap" %}

```bash
truebit build truebit-nextgen-examples/function-tasks/js/ecdsa-sign-verify/dist -l js
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Building the function task
Your function task is ready.
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

#### Step 3: Try The Code

Execute the [start](/developing-truebit-tasks/truebit-cli-reference#start) command against the Truebit node to test our Algorithm. You will need to submit the instrumented task id + the input parameter.&#x20;

In this case, the input parameter is a file containing the address, signature and test data that we want to verify. Please use the file called input.txt located within the root folder.&#x20;

{% code overflow="wrap" %}

```bash
truebit start <taskId> "$(cat truebit-nextgen-examples/function-tasks/js/ecdsa-sign-verify/input.txt)"
```

{% endcode %}

* \[`taskId`]: Add the taskId generated in the previous step.&#x20;

#### Output

{% code fullWidth="false" %}

```bash
Executing the function Task
Execution Id: 72f88499-efa3-4b8d-be69-cf6f6e3a40a4
Task executed with status: succeed
Task executed with result: true
Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬──────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼──────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 16228464673 │ 68       │
│ Nested calls  │ 'Calls'       │ 65536         │ 9336  │ 9304        │ 7        │
│ Frame memory  │ 'Bytes'       │ 524288        │ 29339 │ 27929       │ 18       │
│ System memory │ '64 Kb pages' │ 2048          │ 119   │ '𝚫 1'       │ 17       │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴──────────┘
```

{% endcode %}

#### Step 4: Deploy The Task

Last, but not least, Execute the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command to deploy our task to the coordination hub, so that anyone with the namespace, taskname and the [API key](/developing-truebit-tasks/task-authorization#task-authorization-process) can execute it.

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>truebit deploy &#x3C;namespace> &#x3C;taskname> --taskId &#x3C;taskId>
</strong></code></pre>

* \[`taskId`]: Add the taskId generated in step 2

#### Output

{% code overflow="wrap" %}

```bash
The function task has been deployed successfully.
The Task <taskName> version <version> was registered successfully in namespace <namespace>
```

{% endcode %}


# NumPy Example

### Description

**This example demonstrates how to import external files using the TAR functionality and how to use built-in libraries like NumPy.** In this example, the user specifies an input file (defined as an input parameter) that should already be packaged in the `fs.tar` file. The script will import the NumPy library, open the file, perform some basic operations on the data, and then display an output value.

{% hint style="info" %}
Click here to see the full list of compatible libraries
{% endhint %}

### Executing NumPy Example <a href="#using-bacalhau-to-execute-duckdb-processing" id="using-bacalhau-to-execute-duckdb-processing"></a>

We use Truebit to execute the NumPy task to get a verified result.

### The Code

You can find the Numpy example within the folder *truebit-nextgen-examples/function-tasks/js/numpy-pandas*

📄 task.py\
📄 create-fs.sh\
📄 gendata.py

### task.py

<details>

<summary>task.py</summary>

```python
import numpy as np
import os

def main():
	# Load filepath of input CSV
	try:
		with open("input.txt", "r") as file:
		    input_file = file.read().strip()
	except FileNotFoundError:
		print("Error: The file 'input.txt' does not exist.")
		return
	except Exception as e:
		print(f"An error occurred while reading 'input.txt': {e}")
		return

	# Read the input file (assuming it contains CSV data)
	data = []
	try:
		with open(input_file, 'r') as file:
			header = file.readline().strip().split(',')
			for line in file:
				values = line.strip().split(',')
				data.append(values)
	except FileNotFoundError:
		print("Error: The file '{input_file}' does not exist.")
		return
	except Exception as e:
		print(f"An error occurred while reading '{input_file}': {e}")
		return

	# Convert columns to appropriate types
	A = np.array([float(row[0]) for row in data])
	B = np.array([float(row[1]) for row in data])
	C = np.array([row[2] for row in data])

	# Display the original data
	original_output = "Original Data:\n" + str(data)

	# Calculate basic statistics using numpy
	mean_A = np.mean(A)
	std_A = np.std(A)
	sum_B = np.sum(B)
	max_B = np.max(B)

	statistics = (
		f"\nMean of column 'A': {mean_A}\n"
		f"Standard deviation of column 'A': {std_A}\n"
		f"Sum of column 'B': {sum_B}\n"
		f"Maximum value of column 'B': {max_B}"
	)

	# Add a new column with the natural logarithm of 'B' values using numpy
	log_B = np.log(B + 1)  # +1 to avoid log(0)

	# Create a correlation matrix using numpy
	correlation_matrix = np.corrcoef(A, B)
	correlation_output = "Correlation matrix between 'A' and 'B':\n" + str(correlation_matrix)

	# Normalize column 'A' using numpy
	A_normalized = (A - mean_A) / std_A

	# Filter rows where column 'A' is greater than its mean
	filtered_data = np.array([row for row in data if float(row[0]) > mean_A])

	# Add a date column (as a string for simplicity)
	dates = np.arange('2023-01-01', '2024-01-01', dtype='datetime64[D]').astype(str)

	# Group by column 'C' (assuming C is categorical with values 'X', 'Y', 'Z')
	unique_C, indices_C = np.unique(C, return_inverse=True)
	group_means_A = [np.mean(A[indices_C == i]) for i in range(len(unique_C))]
	grouped_output = "Mean of 'A' grouped by 'C':\n" + str(dict(zip(unique_C, group_means_A)))

	# Apply a lambda function to create a new column 'A_category'
	A_category = np.array(['High' if x > 50 else 'Low' for x in A])

	# Handling missing values: introduce some NaN values in 'B' and then fill them
	B_with_nan = B.copy()
	B_with_nan[::3] = np.nan
	B_filled = np.where(np.isnan(B_with_nan), np.nanmean(B_with_nan), B_with_nan)

	# Prepare the output to be written to output.txt
	output_content = (
		original_output + statistics + "\n\n" +
		"Log of B:\n" + str(log_B) + "\n\n" +
		"Normalized A:\n" + str(A_normalized) + "\n\n" +
		"Filtered Data (A > Mean of A):\n" + str(filtered_data) + "\n\n" +
		correlation_output + "\n\n" +
		grouped_output + "\n\n" +
		"A Category:\n" + str(A_category) + "\n\n" +
		"B with NaNs filled:\n" + str(B_filled)
	)

	# Save the results to output.txt
	with open('output.txt', 'w') as file:
		file.write(output_content)

	print(f"Results written to 'output.txt'.")

if __name__ == "__main__":
    main()
```

</details>

### In/Out Parameters

In order to send parameters to the Truebit task, you need to open the "input.txt" file and get the value from there. For now, only one input parameter is allowed.

```python
with open("input.txt", "r") as file:
input_string = file.read().strip()
```

In order to retrieve the output value from the Truebit task, you need save it in the "output.txt" file.

```python
with open("output.txt", "w") as file:
file.write(output_string)
```

### create-fs.sh

This example uses external files to import data for processing. The `create-fs.sh` script is a batch file that runs the `tar` command to package the files into a single archive. The resulting `fs.tar` file will be used as input data in the Function Task.

### Trying Out

We will use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to [compile](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-2-build-the-source-code) and [test](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

#### Step 1: Create The NumPy Example Source Code

Within the numpy folder you will find a file called `task.py`.

#### Step 2: Build The Source Code

Execute the build command against Truebit node to get an instrumented Truebit task.

```bash
truebit build truebit-nextgen-examples/function-tasks/py/numpy-pandas/src -l py
```

#### Output

{% code overflow="wrap" %}

```bash
Building the function task
Your function task is ready.
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

{% hint style="info" %}
The taskId will always starts with the language prefix + "\_" + cID
{% endhint %}

#### Step 3: Try The Code

Execute the [start](/developing-truebit-tasks/truebit-cli-reference#start) command against the Truebit node to test our Algorithm. You will need to submit the instrumented task id + the input parameter.

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>truebit start &#x3C;taskId> data/frame1.csv
</strong></code></pre>

* \[`taskId`]: Add the taskId generated in the previous step.&#x20;

#### Output

```bash
Executing the function Task
Execution Id: 5f86c995-82a2-467d-aec0-da668ae96b32
Task executed with status: succeed
Task executed with result: Original DataFrame:
 A        B C
17 0.985450 Y
31 0.199326 Y
18 0.432207 Z
69 0.609930 Z
 8 0.193569 Y
58 0.113935 Y
54 0.656381 Y
63 0.269771 Z
91 0.790736 X
35 0.999061 Z
Mean of column 'A': 44.4
Standard deviation of column 'A': 25.377943179067916
Sum of column 'B': 5.250366498443773
Maximum value of column 'B': 0.9990610723341307

Modified DataFrame:
 A        B C    log_B  A_normalized       date A_category  B_filled
17      NaN Y 0.685846     -1.079678 2024-01-01        Low  0.333257
31 0.199326 Y 0.181760     -0.528018 2024-01-02        Low  0.199326
18 0.432207 Z 0.359217     -1.040273 2024-01-03        Low  0.432207
69      NaN Z 0.476191      0.969346 2024-01-04       High  0.333257
 8 0.193569 Y 0.176948     -1.434316 2024-01-05        Low  0.193569
58 0.113935 Y 0.107899      0.535898 2024-01-06       High  0.113935
54      NaN Y 0.504635      0.378281 2024-01-07       High  0.333257
63 0.269771 Z 0.238837      0.732920 2024-01-08       High  0.269771
91 0.790736 X 0.582627      1.836240 2024-01-09       High  0.790736
35      NaN Z 0.692678     -0.370400 2024-01-10        Low  0.333257

Filtered DataFrame (A > Mean of A):
 A        B C    log_B  A_normalized
69 0.609930 Z 0.476191      0.969346
58 0.113935 Y 0.107899      0.535898
54 0.656381 Y 0.504635      0.378281
63 0.269771 Z 0.238837      0.732920
91 0.790736 X 0.582627      1.836240

Correlation matrix between 'A' and 'B':
[[1.         0.09016586]
 [0.09016586 1.        ]]

Mean of 'A' grouped by 'C':
C     A
X 91.00
Y 33.60
Z 46.25
Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬──────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼──────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 15073880553 │ 73       │
│ Nested calls  │ 'Calls'       │ 65536         │ 400   │ 0           │ 164      │
│ Frame memory  │ 'Bytes'       │ 524288        │ 5054  │ 0           │ 104      │
│ System memory │ '64 Kb pages' │ 4096          │ 2232  │ '𝚫 1'       │ 2        │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴──────────┘
```

#### Step 4: Deploy The Task

Last, but not least, Execute the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command to deploy our task to the coordination hub, so that anyone with the namespace, taskname and the [API key](/developing-truebit-tasks/task-authorization#task-authorization-process) can execute it.

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>truebit deploy &#x3C;namespace> &#x3C;taskname> --taskId &#x3C;taskId>
</strong></code></pre>

* \[`taskId`]: Add the taskId generated in step 2

**Output**

```bash
The function task has been deployed successfully.
The Task <taskName> version <version> was registered successfully in namespace <namespace>
```


# Supported Languages

Truebit Verify supports Javascript, Python\*, Rust or C/C++

## Language Capabilities

Function Tasks are executed in a specially instrumented version of the WasmEdge runtime.\
Functions written in Rust or C++ are compiled directly to [WebAssembly (WASM),](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/webassembly) while JavaScript and Python are executed by a WASM-compiled interpreter. As is generally true, compiled functions tend to execute faster than interpreted ones.

<table data-full-width="false"><thead><tr><th width="128" align="center">Language</th><th width="195" align="center">Task Instrumentation</th><th width="180" align="center">Task preparation</th><th align="center">Dependencies</th></tr></thead><tbody><tr><td align="center"><a href="/pages/JawcFJ0XEUZkDFNiG5PL">Rust</a></td><td align="center"><a href="/pages/U7e9U4cLqjafj5LwD9Na">Yes</a></td><td align="center"><a href="/pages/JawcFJ0XEUZkDFNiG5PL#task-preparation">Built-in</a></td><td align="center"><p>Rust v1.81 <strong>only</strong></p><p>WASM32-WASI target</p></td></tr><tr><td align="center"><a href="/pages/69qYDI6K5X8tG6JkJk18">C / C++</a></td><td align="center"><a href="/pages/U7e9U4cLqjafj5LwD9Na">Yes</a></td><td align="center">Custom</td><td align="center"><p>Wasienv</p><p>WASI-SDK 16</p></td></tr><tr><td align="center"><a href="/pages/plwj2UkIkgNtZhDaNkm0">Javascript</a></td><td align="center">No</td><td align="center"><a href="/pages/plwj2UkIkgNtZhDaNkm0#task-preparation">Js Task preparation</a> </td><td align="center">Node.js v22 LTS</td></tr><tr><td align="center"><a href="/pages/FVQC0oXst75T8MZIpwiW">Python</a></td><td align="center">No</td><td align="center"><a href="/pages/FVQC0oXst75T8MZIpwiW#task-preparation">Py Task preparation</a></td><td align="center">Python 3.12 <strong>only</strong></td></tr></tbody></table>

## Setup

You can write Function Tasks in various development languages. Here's how to install different versions of these languages:

{% tabs %}
{% tab title="Rust" %}
Currently, we support Rust version **1.81 only**. Please install it by running the following command-line commands:

```bash
curl https://sh.rustup.rs -sSf | sh
source "$HOME/.cargo/env"
rustup install 1.81.0
rustup default 1.81
```

Please run the following line to install WebAssembly and WASI Preview 1 support for Rust:

```
rustup target add wasm32-wasip1
```

{% endtab %}

{% tab title="C/C++" %}
Please run the following command-line commands to download and install the C and C++ compilers and utilities:

**Linux**

{% code overflow="wrap" %}

```bash
sudo apt install wabt
wget https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-16/wasi-sdk-16.0-linux.tar.gz
tar xvf wasi-sdk-16.0-linux.tar.gz -C ${HOME}
echo "export WASI_SDK_PATH=${HOME}/wasi-sdk-16.0/" >> ~/.profile
source ~/.profile
```

{% endcode %}
{% endtab %}

{% tab title="JS" %}
Currently, we support Node version **22 LTS or above**.&#x20;

We recommend to visit <https://nodejs.org/en/download> and install the latest **v22 LTS** version.
{% endtab %}

{% tab title="Python" %}
Currently, we support Python version **3.12 only**.&#x20;

We recommend to visit <https://www.python.org/downloads/> and install version **v3.12**.
{% endtab %}
{% endtabs %}

### -l, --lang Options

<table><thead><tr><th>Language</th><th valign="middle">Value</th></tr></thead><tbody><tr><td>Rust</td><td valign="middle">Rs (default value)</td></tr><tr><td>Javascript</td><td valign="middle">js</td></tr><tr><td>Python</td><td valign="middle">py</td></tr><tr><td>C</td><td valign="middle">c</td></tr><tr><td>C++</td><td valign="middle">c++</td></tr></tbody></table>


# Rust

## Source Code Structure

In order to compile your source code, make sure you have the following file structure within the `❮sourceCodePath❯` folder that will be built.

📁 src\
└─ 📄 main.rs \
📄 Cargo.toml\
📄 Cargo.lock


# C/C++

To execute Function tasks, you may need to perform additional steps before creating them. Please refer to the following instructions to create a Function task in C/C++.

## **Task Preparation**

### Source Code Structure

In order to compile your source code, make sure you have the following file structure within the `❮sourceCodePath❯` folder that will be built.

📁 src \
└─ 📄 main.c\
📄 compile.sh

### Compile&#x20;

You will need to create a `compile.sh` file to build your code and place all the required libraries your project needs.

#### Compile.sh example

{% code overflow="wrap" %}

```bash
#!/bin/sh
${WASI_SDK_PATH}/bin/clang --sysroot=${WASI_SDK_PATH}/share/wasi-sysroot src/main.c -g -o task.wasm "-Wl,--stack-first,-zstack-size=1048576"
```

{% endcode %}


# Javascript

To execute Function Tasks, you may need to perform additional steps before creating them.  Please refer to the following instructions to create a Function Task in Javascript.

## Limitations

* The "os" module (files, setTimeout, etc.) support is not available yet.
* We support ES6 modules but use rollup to bundle dependencies in a single file.
* The use of sub-directories is not available yet.
* Node libraries are not available (alternative libraries with no Node dependencies should be used instead).
* Currently, only calling synchronous functions is permitted within the context of the [fs module](https://nodejs.org/api/fs.html).

## Task Preparation

### Source Code Structure

In order to compile your source code, make sure you have the following file structure within the `❮sourceCodePath❯` folder that will be built.

📁 src \
└─ 📄 main.js\
&#x20;📁 dist\
└─ 📄 main.js\
📄 package-lock.json\
📄 package.json

{% hint style="info" %}
The ***dist*** folder and the ***main.js*** file are going to be generated after running the `npx rollup -c` command.&#x20;
{% endhint %}

### Setup Rollup

We need to roll up your JS code with all required dependencies into a single file to be able to execute it. Please follow the following steps to merge all the files into a single one.&#x20;

1. Install the Rollup Tool with the following command

```bash
npm i rollup
npm i
```

2. Once the task is developed and working correctly, use the following command to bundle dependencies in a single file. After running this command you will get the following file *dist/main.js*

<pre class="language-bash"><code class="lang-bash"><strong>npx rollup -c
</strong></code></pre>

3. The rollup command generates a single JS file that includes your code and all its dependencies. Now you can test your task in Truebit (run the 'Build' and 'Start' commands in the command-line interface)
4. As you continue your development, you might need to update multiple times your [rollup config file](#rollup-config-file) to keep testing

{% hint style="danger" %}
If you encounter dependency issues, please ensure you are not relying on native Node.js libraries. If you are, try to find an alternative library to resolve the problem.
{% endhint %}

#### Rollup Config File

The `rollup.config.mjs` file is where you provide instructions to Rollup on how to bundle your JavaScript code, making it a fundamental part of the Rollup setup.

{% hint style="info" %}
For more information, visit the [rollup official website](https://rollupjs.org/)
{% endhint %}

<details>

<summary>Rollup config example</summary>

{% code overflow="wrap" %}

```javascript
import nodeResolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

export default [
  {
    input: 'src/main.js',
    output: {
      file: 'dist/main.js',
      format: 'es',
      name: 'fibonacci',
    },
    plugins: [nodeResolve(), commonjs()],
  },
];
```

{% endcode %}

</details>

#### Variables

* **Input:** Set up the file that Rollup will use as the starting point for bundling everything together&#x20;
* **Output:** Define how the output file will be generated. &#x20;
  * **file:** Output rollup file
  * **format:** Specifies the format of the generated bundle. [Available format](https://rollupjs.org/configuration-options/#output-format)
  * **name:** This is the name of the bundle
* **plugins:** Set up the  Rollup plugins that perform additional tasks during bundling. This could include things like converting code, making it smaller, or dealing with outside modules.
* **Optional sections:** You can add additional sections to configure specific aspects of your project, such as module resolution or custom settings.

### Built-in Libraries

#### Crypto Libraries

Truebit provides built-in Cryptographic library functions within our interpreter to make it easier to use and to boost execution speeds. At the moment, we support Bun.js and Deno.

#### Comparison

<table><thead><tr><th width="110">Library</th><th width="164">API</th><th width="205">Performance</th><th>Adoption</th></tr></thead><tbody><tr><td><a href="/pages/yWSjj2mdyWhQPuqsDkSk">Bun.js</a></td><td><strong>Older</strong>. It's Node.js Propietary</td><td><strong>Slower</strong>. It's implemented in JS</td><td><strong>Widely adopted</strong>. The API is easy to understand for the large community of Node.js developers.</td></tr><tr><td><a href="/pages/CBRUmJJ9lOFiuroNTbSq">Deno</a></td><td><strong>Newer</strong>. WebCrypto is a web standard</td><td><strong>Faster</strong>. It's implemented in Rust, then compiled as WebAssembly code.</td><td><strong>Limited adopted.</strong> The API is familiar to web developers and those using Deno (the next generation of Node.js).</td></tr></tbody></table>

#### Performance

When running the examples below, Deno's compiled WebAssembly performs much better than Bun.js, surpassing it by a huge margin.

#### Bun.js

To use Bun.js, import the library into the function task using the following ES6 module syntax

{% code overflow="wrap" %}

```javascript
import crypto from 'crypto';
```

{% endcode %}

#### Example using Bun.js  (Node.js crypto API):

{% code overflow="wrap" lineNumbers="true" %}

```javascript
import crypto from 'crypto';

function main() {
    const message = 'truebit'.repeat(5000);
    
    let i = 100;
    while (i--) {
    	const hash = crypto.createHash('sha256');
    	const result = hash.update(message).digest('hex');
        console.log(result);
    }
}

main();
```

{% endcode %}

{% hint style="info" %}
Click [Here](https://nodejs.org/api/crypto.html) to check the node.js crypto API documentation
{% endhint %}

#### Deno

To use Deno, import the library into the function task using the following ES6 module syntax

```javascript
import crypto from 'webcrypto';
```

#### Example Using  Deno (WebCrypto API):

{% code overflow="wrap" lineNumbers="true" %}

```javascript
import crypto from 'webcrypto';
import TextEncoder from 'encoding';

function buf2hex(buffer) {
return [...new Uint8Array(buffer)]
    .map(x => x.toString(16).padStart(2, '0'))
    .join('');
}

async function main() {
    const message = 'truebit'.repeat(5000);
    const encoder = new TextEncoder('ascii');
    const data = encoder.encode(message).buffer;
    let i = 100;
    while (i--) {
        const hash = await crypto.subtle.digest('sha-256', data);
        const result = buf2hex(hash);
        console.log(result);
    }
}
main();
```

{% endcode %}

{% hint style="info" %}
Click [Here](https://www.w3.org/TR/WebCryptoAPI/) to check the WebCrypto API documentation
{% endhint %}


# Python

To execute Function tasks, you need to perform additional steps before deploying them.  Please refer to the following instructions to create a Function task in Python.

## Task Preparation

### Source Code Structure

In order to compile your source code, make sure you have the following file structure within the `❮sourceCodePath❯` folder that will be built.

📁 src \
└─ 📄 task.py

### Supported Libraries

We support most of the [Python's Standard Library](https://docs.python.org/3/library/index.html).  Please read about using [the Python standard library on WebAssembly platforms](https://docs.python.org/3/library/intro.html#webassembly-platforms). Additionally, we are limited by requirements for determinism. Therefore, modules for **threading**, **multiprocessing**, **subprocesses**, or **sockets** are not supported.

Truebit includes some [built-in](#import-built-in) libraries for you to use in your programs. We will be adding more built-in libraries, so please keep checking this page for updates.

* [NumPy version 1.26.4](https://numpy.org/devdocs/release/1.26.4-notes.html)
* [pandas version 2.2.0](https://pandas.pydata.org/docs/dev/whatsnew/v2.2.0.html)

### External files

To include your external files,  you need to use the TAR utility to pack them together. In this manner files will be packaged into a single file and can also be easily referenced from your code.&#x20;

**Setup TAR**

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

```bash
sudo apt install TAR 
```

{% endtab %}
{% endtabs %}

**Creating The TAR file**

To create a single `fs.tar` file that includes all the folders and files you want, simply run the following command:

```bash
tar -H ustar -cvf fs.tar modules
```

In this example, the tar command will generate a file called `fs.tar` which contains all the files found in the **modules** directory.

**Considerations**

* `fs.tar` is a reserved name for tar files in Truebit. You must always name the file in that way.
* The files included in the `fs.tar` file are read-only.

{% hint style="info" %}
Click [Here](https://www.gnu.org/software/tar/manual/html_section/All-Options.html) for more information about TAR
{% endhint %}

### Input Data Files

You can use your own external data files in your function task. To include your data files,  you need to use the TAR utility to pack them together and then, reference those files in your source code.

{% hint style="info" %}
Click [here](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/numpy-example) to see an example of calling external input data files
{% endhint %}

### Modules

#### **Import External Modules**

To import external modules, pack them all together into an `fs.tar` file, then reference them in your Python code like this:

```python
sys.path.append(os.path.abspath("modules"))

from fibonacci import fibonacci
from reverse import run_task as reverse_alphabet
```

#### **Import External Functions**

To import external functions, pack them all together into an `fs.tar` file, then reference them in your Python code like this:

```python
fibonacci = import_function_from_file('modules/fibonacci.py', 'fibonacci')
reverse_alphabet = import_function_from_file('modules/reverse.py', 'run_task')
```

In the previous example, there's a function called `fibonacci` in the `modules/fibonacci.py` file, and another function called `run_task` in the `modules/reverse.py` file.

#### Import Standard

To use pure python code, just import the stardard set of libraries

```python
import os
```

#### Import Built-in&#x20;

To include the built-in libraries provided by Truebit, you will need to import them in the following way

```python
import numpy as np
import pandas as pd 
```


# Key Concepts

This section provides a comprehensive overview of key principles central to understanding the Truebit Protocol.

<table data-card-size="large" data-view="cards"><thead><tr><th align="center"></th><th></th></tr></thead><tbody><tr><td align="center"><a href="/pages/9QdmubpyGCMsA5O2eUHL"><strong>Determinism</strong></a></td><td>The crucial role determinism plays in Truebit's operations, ensuring consistent and predictable outcomes in the execution of tasks within the WASM runtime.</td></tr><tr><td align="center"><a href="/pages/9ZDsLLcanSyjIAaRjDxs"><strong>WebAssembly + WASI</strong></a></td><td>Understand how these technologies work in tandem to empower developers with versatile and secure execution environments.</td></tr><tr><td align="center"><a href="/pages/U7e9U4cLqjafj5LwD9Na">Task <strong>Instrumentation</strong></a></td><td>Understand the instrumentation process and its crucial role in task execution.</td></tr></tbody></table>


# Determinism

In Truebit tasks, determinism ensures that whenever someone takes part in the Truebit process, they'll always get the same result if they use the same starting information.

## What is Determinism?

**Determinism** **means that when you run a program or code multiple times with the same inputs and conditions, you will always get the same result.**&#x20;

### Challenges

* A program running in a Turing machine is non-deterministic by default. Given some input, it is only possible to tell if a program will end by running it firs&#x74;**.** That is known as [the halting problem](https://en.wikipedia.org/wiki/Halting_problem).&#x20;
* A program running an infinitely recursive function will consume the whole stack memory even before its infinite recursion gets noticed by the time it takes to execute.
* The way floating-point hardware is implemented can lead to inconsistencies in the task execution results.

### How Do We Manage Those Challenges?

To manage those challenges, Truebit [instruments](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/task-instrumentation) the [WebAssembly](/developing-truebit-tasks/how-to-create-function-tasks/key-concepts/webassembly) program to:&#x20;

* **Limit** the number of executed instructions (Gas metering).
* **Restrict** the available execution stack memory (Stack limit).
* **Constrain** the depth of nested calls assigned to the task execution (Call limit).

In addition to that, it also performs the following tasks:

* Replaces the the default WASI implementation with a customized WASI interface developed by Truebit.
* Replaces FPU instructions with deterministic functions created by Truebit.


# WebAssembly

Truebit uses WebAssembly as a foundational technology to ensure security, compatibility, and high-performance execution for its decentralized verification protocol.

### **What is WebAssembly?**

[WebAssembly](https://webassembly.org/) (**WASM) is a compilation target that allows to run high-performance code written in compiled languages like C, C++, and Rust to run in a platform-independent way through a sandboxed interpreter.**

The [WebAssembly System Interface ](https://wasi.dev/)(WASI) is the system interface for WebAssembly. It allows to call specific operating system-related services to be called from inside the execution sandbox. WebAssembly programs can **access filesystem data,** **environment variables**, and **program arguments** through this interface. Truebit is compatible with WASM programs that use the WASI version known as 'Snapshot 1'.

#### Limitations

* All ingress/egress networking is disabled – you won't be able to pull data/code/weights/etc from an external source. WASM jobs can access the data by reading from the filesystem.
* There is no multi-threading as WASI Snapshot 1 does not expose any interface for it.

#### Why Do We Use It?

Truebit uses WebAssembly as a foundational technology to ensure security, compatibility, and high-performance execution for its verification protocol.

1. **Portability**: WebAssembly code can run unmodified on various platforms, ensuring compatibility across different systems.
2. **Performance**: WebAssembly's speed is essential for the efficient execution of Truebit's complex verification tasks.
3. **Language Flexibility**: Developers contributing to Truebit can write code in [multiple languages](/developing-truebit-tasks/how-to-create-function-tasks/supported-languages), thanks to WebAssembly's language-agnostic nature.


# Task Instrumentation

In order to guarantee a deterministic execution and also to abort execution wherever it exceeds a set amount of resources, Truebit instruments the WebAssembly file to add capabilities.

### How Does The Instrumentation Process Work?

The instrumentation process injects WebAssembly code through the program to watch for resource usage. When the program exceeds a set amount of resources, it signals that error to the [wasm-runner](/architecture/introduction/truebit-verify-nodes#wasm-runner) and immediately aborts execution.

### Link Process&#x20;

The first step in the process is called '**Link**' and it handles the following tasks to guarantee deterministic execution.

### Replace WASI Interface

Replace the default WASI interface with the Truebit WASI implementation&#x20;

### Replace Bulk Memory Instruction

Replace WASM bulk memory extension instructions with basic ones.

### Replace FPU Instructions

Replace the hardware floating point number implementation with a deterministic one created by Truebit.

### Limit Process

The second step in the process is called '**Limit**' and it handles the following tasks to detect resource usage and abort execution wherever it exceeds a set amount.

#### Gas Limit

It limits program execution to a given number of WebAssembly instructions. It allows paying nodes for the execution of up to a maximum number of instructions (the gas). The program won't execute past a given instruction count, even when executing an infinite loop.

#### Stack Limit

It limits stack usage by restricting how much stack memory, in bytes, functions can be used at any given time, including their nested calls.

#### Call Limit

Sets a maximum amount of nested calls, which limits infinite recursion.


# How To Create API Tasks

API Tasks verify and provide a transcript for the execution of web services' API calls.

**With API Tasks, the Truebit Verify Hub proxies requests to an external API endpoint**. API Tasks are dispatched and executed only by the Truebit Verify Hub, which secures sensitive data such as API credentials and allows for execution of a single, audited API call. In a role reversal, Truebit Verify Nodes then audit the network transaction originated by the hub, providing full transparency for each call. &#x20;

API Tasks are accessed via a built-in web services interface provided by the Truebit Verify Hub, and can be called by any application using HTTP. **Each API Task execution is recorded in a transcript.**

#### Trusted Execution for API Tasks

All API Task executions are performed within a [Trusted Execution Environment (TEE)](/overview/how-does-truebit-work), ensuring that sensitive data and credentials remain private throughout the entire execution process. This adds an additional layer of trust and confidentiality to every API interaction.

By leveraging TEE-backed execution, Truebit provides:

* **Credential privacy:** Authentication keys remain encrypted and protected within a secure enclave, never exposed to external systems or verifiers.
* **Tamper-proof execution**: The API call and its outputs cannot be modified or inspected during runtime, preserving the integrity of the operation.
* **Verified transparency**: Even with private execution, each API Task still produces a verifiable transcript that confirms the request occurred exactly as intended.
* **End-to-end trust**: The combination of TEE execution and Truebit’s verification model ensures API Tasks are both private and provably correct — offering a secure, auditable bridge between systems that handle sensitive or regulated data.

This approach extends the security of hardware-backed trusted execution to the API layer, enabling developers to confidently automate API calls without compromising privacy or integrity.

## Prerequisites

There are several important considerations when defining an API Task:

* **OpenAPI Schemas:** Truebit Verify uses the [OpenAPI schema specification](https://spec.openapis.org/oas/v3.1.0#openapi-specification) as the basis for the API Manifest that defines the interaction with an external HTTP-based API. The OpenAPI schema describes the servers, data formats, validation rules, etc. for a given API endpoint. The Truebit Verify Hub will validate all API Task calls using the OpenAPI schema before executing a network request. Many APIs already provide an OpenAPI schema as part of their documentation — and this can serve as a good starting point for defining your API Manifest. Truebit supports OpenAPI Schema v3 and later.
* **Credentials:** Many APIs require authentication credentials to be provided as part of the network request. We currently support `basic auth, AWS key, and custom HTTP Header` credentials. The Truebit Verify CLI allows you to upload encrypted credentials to the Truebit Verify Hub, where they will be securely stored in their encrypted state. When possible, we recommend obtaining credentials specifically scoped to the authorization requirements of your API Task, and rotating credentials in accordance with your team's security practices.
* **No Determinsim Requirement**: Truebit Verify uses a different verification strategy for APIs which does not require deterministic outputs to be provided by the API.&#x20;

### Building An API Task

To interact with the Truebit protocol, developers can define **API Tasks** that encapsulate computation logic and interface with external systems. This section outlines the steps required to build, configure, and deploy an API Task within the Truebit ecosystem.

{% stepper %}
{% step %}

### Define The API Manifest

The [task developer](/#task-developers) provides an OpenAPI schema as an API Manifest for the relevant APIs that will be proxied by Truebit Verify.&#x20;

We recommend using a tool like [Swagger Editor](https://editor.swagger.io/) to help develop the OpenAPI schema used in your manifest. If using a pre-existing OpenAPI schema provided by an API publisher, we recommend reviewing the contents of the schema to remove any unneeded endpoints and/or add any additional validation rules as needed by your API Task.

**Using OpenAPI For The Manifest**

OpenAPI Specification (formerly Swagger Specification) is an API description format for REST APIs. An OpenAPI file allows you to describe an entire API, including:

* Available endpoints (/users) and operations on each endpoint (GET /users, POST /users).
* Operation parameters Input and output for each operation.
* Authentication methods.
* Contact information, license, terms of use and other information.

**Advantages**

* **Standardized Integration:** Leverages widely used industry standards to ensure compatibility across diverse environments.
* **OpenAPI Compatibility**: Most APIs come with ready-to-use OpenAPI specifications, streamlining the integration process within the Truebit ecosystem.
* **Native Validation Support:** Built-in mechanisms ensure that data integrity and task requirements are automatically verified.
* **Granular Customization**: Offers the flexibility to include or exclude specific fields, optimizing data transfer and processing efficiency.
* **Secure Extensibility:** Supports the inclusion of credentials and custom definitions through robust extensibility mechanisms.

**Example**

<details>

<summary>PET SHOP example manifest</summary>

{% code overflow="wrap" lineNumbers="true" fullWidth="false" %}

```json
{
  "openapi": "3.0.3",
  "info": {
    "title": "Swagger Petstore - OpenAPI 3.0",
    "description": "This is a sample Pet Store Server based on the OpenAPI 3.0 specification.",
    "contact": {
      "email": "apiteam@swagger.io"
    },
    "license": {
      "name": "Apache 2.0",
      "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
    },
    "version": "1.0.11"
  },
  "externalDocs": {
    "description": "Find out more about Swagger",
    "url": "http://swagger.io"
  },
  "servers": [
    {
      "url": "https://petstore3.swagger.io/api/v3"
    }
  ],
  "paths": {
    "/store/order": {
      "post": {
        "tags": [
          "store"
        ],
        "summary": "Place an order for a pet",
        "description": "Place a new order in the store",
        "operationId": "placeOrder",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Order"
              }
            },
            "application/xml": {
              "schema": {
                "$ref": "#/components/schemas/Order"
              }
            },
            "application/x-www-form-urlencoded": {
              "schema": {
                "$ref": "#/components/schemas/Order"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "successful operation",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Order"
                }
              }
            }
          },
          "405": {
            "description": "Invalid input"
          }
        }
      }
    },
    "/store/order/{orderId}": {
      "get": {
        "tags": [
          "store"
        ],
        "summary": "Find purchase order by ID",
        "description": "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.",
        "operationId": "getOrderById",
        "parameters": [
          {
            "name": "orderId",
            "in": "path",
            "description": "ID of order that needs to be fetched",
            "required": true,
            "schema": {
              "type": "integer",
              "format": "int64"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "successful operation",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Order"
                }
              },
              "application/xml": {
                "schema": {
                  "$ref": "#/components/schemas/Order"
                }
              }
            }
          },
          "400": {
            "description": "Invalid ID supplied"
          },
          "404": {
            "description": "Order not found"
          }
        }
      },
      "delete": {
        "tags": [
          "store"
        ],
        "summary": "Delete purchase order by ID",
        "description": "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
        "operationId": "deleteOrder",
        "parameters": [
          {
            "name": "orderId",
            "in": "path",
            "description": "ID of the order that needs to be deleted",
            "required": true,
            "schema": {
              "type": "integer",
              "format": "int64"
            }
          }
        ],
        "responses": {
          "400": {
            "description": "Invalid ID supplied"
          },
          "404": {
            "description": "Order not found"
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "Order": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int64",
            "example": 10
          },
          "petId": {
            "type": "integer",
            "format": "int64",
            "example": 198772
          },
          "quantity": {
            "type": "integer",
            "format": "int32",
            "example": 7
          },
          "shipDate": {
            "type": "string",
            "format": "date-time"
          },
          "status": {
            "type": "string",
            "description": "Order Status",
            "example": "approved",
            "enum": [
              "placed",
              "approved",
              "delivered"
            ]
          },
          "complete": {
            "type": "boolean"
          }
        },
        "xml": {
          "name": "order"
        }
      },
      "ApiResponse": {
        "type": "object",
        "properties": {
          "code": {
            "type": "integer",
            "format": "int32"
          },
          "type": {
            "type": "string"
          },
          "message": {
            "type": "string"
          }
        },
        "xml": {
          "name": "##default"
        }
      }
    }
  }
}
```

{% endcode %}

</details>
{% endstep %}

{% step %}

### Develop The API Task

The [Task Developer](/overview/how-do-you-intend-to-use-truebit) creates a new API task by calling the [create-api](/developing-truebit-tasks/truebit-cli-reference#create-api) command from the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) using the defined manifest as the input parameter.  As a result, a new [`taskId`](/community/glossary) will be returned.
{% endstep %}

{% step %}

### Test The API Task

The [Task Developer](/overview/how-do-you-intend-to-use-truebit) tests the API task using the [start-api](/developing-truebit-tasks/truebit-cli-reference#start-api) command from the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference).
{% endstep %}

{% step %}

### What If Authentication is Required?

{% hint style="warning" %}
An API Task must use a single authentication method across all endpoints and cannot include both public and private endpoints in the same manifest.
{% endhint %}

**If the API endpoint you want to call is authenticated, you'll need to provide the necessary credentials when running the start-api command.**

\
Currently, we support three authentication methods:

* `custom-header`
* `basic-auth`
* `aws-signature`

**How To Pass Credentials**

* **Custom Header:** Use this method when the API expects authentication via custom headers.

{% code overflow="wrap" %}

```bash
truebit start-api [options] <manifestPath> <input> custom-header "username:<username>,password:<password>"
```

{% endcode %}

* **Basic Auth:** For standard HTTP Basic Authentication, you will need to use the following:

{% code overflow="wrap" %}

```bash
truebit start-api [options] <manifestPath> <input> basic-auth "username:<username>,password:<password>"
```

{% endcode %}

* **AWS Signature:** For endpoints protected with AWS Signature Version 4, you will need to use the following:

{% code overflow="wrap" %}

```bash
truebit start-api [options] <manifestPath> <input> aws-signature "accessKey:<accesskey>,secretKey:<secretkey>"
```

{% endcode %}
{% endstep %}

{% step %}

### Deploy The API Task

When the API Task is ready, the [Task Developer](/#task-developers) deploys the task using the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command from the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference).

**Deploying Credentials For Authenticated Endpoints**

If the endpoints defined in your manifest require authentication (custom-header, basic-auth, or aws-signature), you must also deploy the corresponding credentials to ensure the [Task Requester](/overview/how-do-you-intend-to-use-truebit#task-requesters) can execute the task successfully.

To do this, use the [api-auth](/developing-truebit-tasks/truebit-cli-reference#api-auth) command along with the appropriate authentication method and credentials:

{% code overflow="wrap" %}

```bash
truebit api-auth <namespace> <taskname> <taskId> <authType> <authString>
```

{% endcode %}

**Authorize The Task execution**

The Task Authorization process is an optional step, but it becomes mandatory when the Task Requester has registered the task. This step allows the Task Developer to define who has permission to execute the deployed task.

{% hint style="info" %}
Click Here to see more information about the [**Task Authorization**](/developing-truebit-tasks/task-authorization) process.&#x20;
{% endhint %}
{% endstep %}

{% step %}

### Execute The API Task

The [Task Requester](/#task-requesters) executes the task using the [Task Execution Endpoint](/integrating-truebit-tasks/api-task-execution) from the Truebit API.
{% endstep %}
{% endstepper %}


# API Task Examples

<table><thead><tr><th align="center">Example</th><th align="center">Description</th><th data-hidden></th><th data-hidden></th></tr></thead><tbody><tr><td align="center"><a href="/pages/i67Jq7eOtA9vS7cRFpYd"><strong>Pet Store CRUD</strong></a></td><td align="center">A simple <a href="/pages/QBCfYKYQLimFxc788UMp">API Task </a>that retrieves information about a Pet Store conditions from an existing endpoint.</td><td>A simple API Task that retrieves information about a Pet Store conditions from an existing endpoint.</td><td></td></tr><tr><td align="center"><a href="/pages/eVv45tF274b2RQ43aXb4">API-Auth </a></td><td align="center">The main goal of these examples is to demonstrate how a <a href="/pages/0eIo1lFuEUfAIDJZyZ6t#task-developers">Task Developer </a>can create Truebit API Tasks that interact with authenticated endpoints.</td><td></td><td></td></tr></tbody></table>


# Pet Store CRUD

We will use the [Truebit CLI](/developing-truebit-tasks/truebit-cli-reference) to [compile](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-2-build-the-source-code) and [test](/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

### Step 1. Define The API Manifest

The manifest is already defined within the folder *examples/api-tasks/petstore-crud/manifest.json*.

### Step 2. Test The API Task

Execute the [`start-api`](/developing-truebit-tasks/truebit-cli-reference#start-api) command to test the manifest.

#### Add a New Record Using POST Verb

{% code overflow="wrap" %}

```bash
truebit start-api truebit-nextgen-examples/api-tasks/petstore-crud/manifest.json truebit-nextgen-examples/api-tasks/petstore-crud/post.add.input.json 
```

{% endcode %}

#### Output

```bash
Executing the API Task
API Task executed with status - OK 

Input request :
{
  "path": "/store/order",
  "method": "POST",
  "body": {
    "id": 2,
    "petId": 198772,
    "quantity": 7,
    "shipDate": "2077-08-24T14:15:22Z",
    "status": "approved",
    "complete": true
  },
  "headers": {}
}

Base URL = https://petstore.swagger.io/v2 
OpenAPI manifest check - OK 

API Task response
{
  "id": 2,
  "petId": 198772,
  "quantity": 7,
  "shipDate": "2077-08-24T14:15:22.000+0000",
  "status": "approved",
  "complete": true
}
```

#### Retrieve The Record Using GET Verb

{% code overflow="wrap" %}

```bash
truebit start-api truebit-nextgen-examples/api-tasks/petstore-crud/manifest.json truebit-nextgen-examples/api-tasks/petstore-crud/get.input.json 
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Executing the API Task
API Task executed with status - OK 

Input request :
{
  "path": "/store/order/{orderId}",
  "method": "GET",
  "params": {
    "orderId": 2
  },
  "headers": {}
}

Base URL = https://petstore.swagger.io/v2 
OpenAPI manifest check - OK 

API Task response
{
  "id": 2,
  "petId": 198772,
  "quantity": 7,
  "shipDate": "2077-08-24T14:15:22.000+0000",
  "status": "approved",
  "complete": true
}
```

{% endcode %}

#### Update The Record Using The POST Verb

{% code overflow="wrap" %}

```bash
truebit start-api truebit-nextgen-examples/api-tasks/petstore-crud/manifest.json truebit-nextgen-examples/api-tasks/petstore-crud/post.update.input.json
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Executing the API Task
API Task executed with status - OK 

Input request :
{
  "path": "/store/order",
  "method": "POST",
  "body": {
    "id": 2,
    "petId": 198772,
    "quantity": 18,
    "shipDate": "2077-08-24T14:15:22Z",
    "status": "approved",
    "complete": true
  },
  "headers": {}
}

Base URL = https://petstore.swagger.io/v2 
OpenAPI manifest check - OK 

API Task response
{
  "id": 2,
  "petId": 198772,
  "quantity": 18,
  "shipDate": "2077-08-24T14:15:22.000+0000",
  "status": "approved",
  "complete": true
}
```

{% endcode %}

#### Delete The Record Using The DELETE Verb

{% code overflow="wrap" %}

```bash
truebit start-api truebit-nextgen-examples/api-tasks/petstore-crud/manifest.json truebit-nextgen-examples/api-tasks/petstore-crud/delete.input.json
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Executing the API Task
API Task executed with status - OK 

Input request :
{
  "path": "/store/order/{orderId}",
  "method": "DELETE",
  "params": {
    "orderId": 2
  },
  "headers": {}
}

Base URL = https://petstore.swagger.io/v2 
OpenAPI manifest check - OK 

API Task response
{
  "code": 200,
  "type": "unknown",
  "message": "2"
}
```

{% endcode %}

### Step 3. Create The API Task

Execute the [`create-api`](/developing-truebit-tasks/truebit-cli-reference#create-api) command against the Truebit Verify Node to execute the endpoint.

{% code overflow="wrap" %}

```bash
truebit create-api truebit-nextgen-examples/api-tasks/petstore-crud/manifest.json
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```
Creating API task...
OpenAPI manifest is valid!
Your API task is ready!
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

### Step 4. Deploy The API Task

Last but not least, please go ahead and execute the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command to deploy the API task to the coordination hub, so that anyone with the `taskId` can use it.

{% code overflow="wrap" %}

```bash
truebit deploy <namespace> <taskname> --taskId <taskId>
```

{% endcode %}

* \[taskId]: Add the `taskId` generated in step 3

#### Output

{% code overflow="wrap" lineNumbers="true" %}

```bash
Deploying the API task
The function task has been deployed successfully.
```

{% endcode %}


# API-Auth Examples

**The main goal of these examples is to demonstrate how a** [**Task Developer**](/overview/how-do-you-intend-to-use-truebit#task-developers) **can create** [**Truebit API Tasks**](/developing-truebit-tasks/how-to-create-api-tasks) **that interact with authenticated endpoints.**

\
In this section, we’ll walk through how to handle each of the supported authentication methods: *custom-header, basic-auth*, and aws-signature.

### 1. Test Your Manifest

Use the  [`start-api`](/developing-truebit-tasks/truebit-cli-reference#start-api) command to execute the API task locally within the context of the Truebit Node. This allows you to verify that the authenticated endpoints behave as expected.

#### custom-header

{% code overflow="wrap" %}

```bash
truebit start-api api-auth/custom-header/custom-header.manifest.json api-auth/custom-header/custom-header.input.json custom-header 'username:foo, password:bar'
```

{% endcode %}

**basic-auth**

{% code overflow="wrap" %}

```bash
truebit start-api api-auth/basic-auth/basic-auth.manifest.json api-auth/basic-auth/basic-auth.input.json basic-auth 'username:<username>,password:<password>'
```

{% endcode %}

**aws-signature**

{% code overflow="wrap" %}

```bash
truebit start-api api-auth/aws-signature/aws-signature.manifest.json api-auth/aws-signature/aws-signature.input.json aws-signature "accessKey:AKIA2VXUSRQO3CTJ5UH5,secretKey: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"
```

{% endcode %}

### 2. Create The Truebit API Task

Once the authenticated endpoints have been successfully tested, create the Truebit API Task by running the [`create-api`](/developing-truebit-tasks/truebit-cli-reference#create-api) command.

#### custom-header

{% code overflow="wrap" %}

```bash
truebit create-api api-auth/custom-header/custom-header.manifest.json
```

{% endcode %}

**basic-auth**

{% code overflow="wrap" %}

```bash
truebit create-api api-auth/basic-auth/basic-auth.manifest.json
```

{% endcode %}

**aws-signature**

{% code overflow="wrap" %}

```bash
truebit create-api api-auth/aws-signature/aws-signature.manifest.json
```

{% endcode %}

### 3. Deploy the Truebit API Task

Deploy the created API Task using the [deploy](/developing-truebit-tasks/truebit-cli-reference#deploy) command. This makes it available for execution by [Task Requesters](/overview/how-do-you-intend-to-use-truebit#task-requesters).

{% code overflow="wrap" %}

```bash
truebit deploy <namespace> <taskname> --taskId <taskId>
```

{% endcode %}

* \[taskId]: Add the taskId generated in step 2

### 4. Deploy the Authentication Credentials

After deploying the API Task, upload the required authentication credentials using the `api-auth` command. This ensures the Task Requester can execute the task without encountering authentication issues.

#### custom-header

{% code overflow="wrap" %}

```bash
truebit api-auth <namespace> <taskname> <taskId> custom-header "username:<username>,password:<password>"
```

{% endcode %}

**basic-auth**

{% code overflow="wrap" %}

```bash
truebit api-auth <namespace> <taskname> <taskId> basic-auth 'username:<username>,password:<password>'
```

{% endcode %}

**aws-signature**

{% code overflow="wrap" %}

```bash
truebit api-auth <namespace> <taskname> <taskId> aws-signature "accessKey:AKIA2VXUSRQO3CTJ5UH5,secretKey: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"
```

{% endcode %}

### 5. Execute The Truebit API Task

Now, you're ready to execute the Truebit API Task using the [execute-by-name](/integrating-truebit-tasks/api-task-execution/execute-api-tasks) endpoint and retrieve the Truebit transcript.


# Dynamic Oracles

This guide explains how to implement a Solidity smart contract that utilizes Truebit to perform off-chain computation.

### What Is Dynamic Oracles?

With Truebit’s Dynamic Oracle, smart contracts can securely trigger external computations or data requests that are handled by Truebit’s off-chain execution and verification layer. The platform ensures that results are returned verifiably and without requiring trust in third parties.

This enables:

* **Off-chain Computation:** Running heavy or external tasks outside the main network while maintaining full on-chain trust.
* **Cryptographic Verification:** Providing mathematical proof of task correctness to ensure every execution is tamper-proof.
* **Seamless Integration:** Enabling fluid interaction with smart contract logic for a cohesive developer experience.

### **Available Execution Types**

* **Dynamic JS Function**: Execute a **single** JavaScript function directly from a smart contract without the need to deploy the function task previously. It will execute the code directly without the need to register in the platform.
* **Truebit API Task**: Run your deployed Truebit API tasks directly from a smart contract and retrieve the result without  encoding (bytes).
* **Truebit API Task with n8n Orchestration**: Trigger an n8n workflow via a Truebit API and receive the result ABI-encoded.

### System Components

1. **User Contract**\
   A custom smart contract developed by the [Task Developer](/overview/how-does-truebit-work). It inherits from `tbBaseContract`, calls the `_requestExecution` method, and handles the `callback` with the computed result.&#x20;
2. **WatchTower**\
   A Truebit-developed contract responsible for emitting events when new execution are requested and managing the response callbacks once computation is completed. This contract has all the needed logic required to interact with Truebit.

***

### Technical Prerequisites

Before starting, please clone the examples on the following repository to start working with Truebit:

```bash
git clone https://github.com/TruebitProtocol/truebit-nextgen-examples.git
```

* You will find the following files under the folder *Blockchain:*
  * `/BaseTBContract.sol`
  * `/interfaces/IBaseTBContract.sol`
  * `/interfaces/IWatchTower.sol`&#x20;
  * `/abstract/Types.sol`
  * `/examples/DemoContract.sol` : You can use this contract as a reference for implementing a Dynamic Oracle within your own smart contract.
* A Solidity development environment (`^0.8.0`)
* WatchTower Address: `0xEcd0EeD24Ed6a54d05a07125c4ccb809b3A09868`

### Create Your Contract

Please, review the implementation guides we’ve prepared to help you integrate with the **Dynamic Oracle** feature.

* [**Implement a Dynamic JS Function execution**](/developing-truebit-tasks/dynamic-oracles/dynamic-js-execution)
* [**Implement a Truebit API Task execution**](/developing-truebit-tasks/dynamic-oracles/api-task)
* [**Implement Truebit API Task with n8n Orchestration execution**](/developing-truebit-tasks/dynamic-oracles/api-task-with-n8n-orchestration)


# Dynamic Js Execution

This Dynamic Oracle implementation allows your smart contract to execute a predefined JavaScript function on the Truebit network, providing off-chain computation with on-chain guarantees.

###

{% stepper %}
{% step %}

### Inherit From BaseTBContract

Import `BaseTBContract.sol` contract and extend from it.
{% endstep %}

{% step %}

### Constructor

When deploying the contract, ensure you set the correct values for **watchTowerAddress,** **sourceCode** within your contract:

* **watchTowerAddress**: `0xEcd0EeD24Ed6a54d05a07125c4ccb809b3A09868`.
* **sourceCode**: "`Place your JS code here inside quotes`".
  {% endstep %}

{% step %}

### Submitting a Request

In your contract, to execute JS code on Truebit, call the `_requestExecution` function. This will trigger the task execution on the Truebit platform.

To call the  **`_requestExecution`** , you must:

1. Define the method signature string.
2. Encode all parameters using **`abi.encode`**.
3. Specify the execution type as: `DOTypes.ExecutionType.EMBEDDED_FUNCTION`.

**Method Signature:**

**The method signature must follow a strict format.** It begins with the method name (in this case, `"function"`), followed by parentheses containing the parameter definitions, separated by commas.

Example:

```solidity
function(uint256)
```

{% endstep %}

{% step %}

### **Filling The Payload:**

Once the method signature is defined, you must fill the payload with the values for the parameter defined on the signature, and encode it by using `abi.encode(...)`.
{% endstep %}

{% step %}

### **Call \_requestExecution:**

Finally, you call \_requestExecution() with:

* The method signature (string).
* The encoded payload (bytes).
* The execution type: `DOTypes.ExecutionType.EMBEDDED_FUNCTION` .

```solidity
// Prepare the payload for the function execution
bytes memory payload = abi.encode(
    input     // The input parameter for fibonacci calculation
);
// Submit the execution request to the Truebit network
uint256 wtExecutionId = _requestExecution(
    "function(uint256)",
    payload,
    DOTypes.ExecutionType.EMBEDDED_FUNCTION
)
```

{% endstep %}

{% step %}

### Handling The Callback

When the execution is finished, your will receive the result within the `callbackTask`.

```solidity
function callbackTask(
        bytes calldata resultData, 
        string[] memory transcripts, 
        uint256 wtExecutionId, 
        uint8 status,
        string memory callbackMessageDetails
    ) external override onlywatchTower {
```

* **resultData:** The encoded result data from the execution.
* **transcripts:** Array of execution transcripts for verification.
* **wtExecutionId:**  The execution identifier.
* **status:** Execution status (0 = success, >0 = error).
* **callbackMessageDetails:** Additional details about the execution.

**Status types**

<table><thead><tr><th width="194.9453125">Status</th><th width="95.2421875">Code</th><th>Description</th></tr></thead><tbody><tr><td><code>SUCCESS</code></td><td><code>0</code></td><td>The execution completed successfully.</td></tr><tr><td><code>FAILED</code></td><td><code>1</code></td><td>This execution is invalid. Check the <code>callbackMessageDetails</code> for more information.</td></tr><tr><td><code>ERROR</code></td><td><code>2</code></td><td>A verified error occurred during execution. The network <em>did</em> reach consensus, and the agreed-upon result is that the program failed.</td></tr><tr><td><code>EXCEEDED</code></td><td><code>3</code></td><td>Execution was halted for exceeding the computational resource limit. You Should optimize your program or reduce input size before retrying.</td></tr><tr><td><code>CODE_HASH_MISMATCH</code></td><td><code>4</code></td><td>The executed code's hash does not match the one committed in the original <code>ExecutionRequest</code> .</td></tr></tbody></table>

{% hint style="warning" %}
**Key considerations:**

* Always check `status` before decoding `resultData`&#x20;
* Treat all non-zero statuses as failures; the exact value is useful for logging but your control flow should not depend on it.
  {% endhint %}
  {% endstep %}
  {% endstepper %}


# API Task

This Dynamic Oracle implementation allows your smart contract to execute a pre deployed Truebit API Task, providing off-chain computation with on-chain guarantees.

{% hint style="info" %}
To execute a Truebit task, you must first deploy it using the Truebit CLI (run [truebit deploy](/developing-truebit-tasks/truebit-cli-reference#deploy)).\
Once deployed, you will need both the `namespace` and the `task name` of your API task.
{% endhint %}

{% stepper %}
{% step %}

### Inherit From BaseTBContract

Import `BaseTBContract.sol` contract and extend from it.
{% endstep %}

{% step %}

### Constructor

When deploying the contract, ensure you set the correct values for both **watchTowerAddress** and **sourceCode** within your contract:

* **watchTowerAddress**: `0xEcd0EeD24Ed6a54d05a07125c4ccb809b3A09868`.
* **sourceCode**: In the case of API task this value must be an empty string (`""`).
  {% endstep %}

{% step %}

### Submitting a Request

In your contract, call the `_requestExecution` function. This will trigger the task execution on the Truebit platform.

To Call the  **`_requestExecution`** You must:

1. Define the method signature string.
2. Encode all parameters using **`abi.encode`** .
3. Specify the execution type as: `DOTypes.ExecutionType.API` .

**Method Signature**

The method signature must follow a strict format. It begins with the method name (in this case, `"request"`), followed by parentheses containing the parameter definitions, separated by commas.

The following parameters are **required** and must appear **in this exact order** with the specified names:&#x20;

`namespace, taskname, method, path, executionTimeout, async`

**Depending on your API call, you may also include:**

* `params()` — if your endpoint uses path or query parameters.
* `body` — if your call includes a request body (e.g. for POST/PUT).<br>

**If params() is required, you must specify the key and type inside the parentheses, for example:**

```solidity
params(orderId:uint256)
```

**Multiple parameters can be separated by commas.**

If body is also needed, it should appear after `params()` or `async`, depending on whether parameters are present.

Examples:

**Only params:**

```solidity
request(namespace,taskname,method,path,executionTimeout,async,params(orderId:uint256))
```

**Only body:**

```solidity
request(namespace,taskname,method,path,executionTimeout,async,body)
```

**Both params and body:**

```solidity
request(namespace,taskname,method,path,executionTimeout,async,params(orderId:uint256),body)
```

{% endstep %}

{% step %}

### Filling The Payload

Once the method signature is defined, you must fill the payload with the values for the parameter defined on the signature, and encode it using `abi.encode(...)`.

**The payload values are the following:**

1. The namespace where the task was deployed.
2. The name of the task defined at deployment.
3. The HTTP method to call (GET, POST, PUT, DELETE, PATCH).
4. The endpoint path you want to call in your Truebit API task.
5. The executionTimeout (e.g. 100000).
6. The async flag:&#x20;
   1. `true` → returns an `executionId` immediately.
   2. `false` → waits until the task completes and returns the response.
7. (Optional) Any path/query parameters.
8. (Optional) The body content.
   {% endstep %}

{% step %}

### Call \_requestExecution

Finally, you call \_requestExecution() with:

* The method signature (string).
* The encoded payload (bytes).
* The execution type: `DOTypes.ExecutionType.API` .

```solidity
bytes memory payload = abi.encode(
    'Your Namespace', // namespace - identifies the API collection
    'Your Taskname',      // taskname - specific API task to execute
    'GET',      // HTTP method
    '/store/order/{orderId}', // API endpoint path
    100000,     // executionTimeout - max time for execution
    false,      // async - whether to run asynchronously
    orderId     // orderId - the parameter for the API call
);
// Submit the execution request to the Truebit network
uint256 wtExecutionId = _requestExecution(
    "request(namespace,taskname,method,path,executionTimeout,async,params(orderId:uint256))",
    payload,
    DOTypes.ExecutionType.API
);
```

{% endstep %}

{% step %}

### Handling The Callback

When the execution is finished, your will receive the result within the `callbackTask` .

```solidity
function callbackTask(
        bytes calldata resultData, 
        string[] memory transcripts, 
        uint256 wtExecutionId, 
        uint8 status,
        string memory callbackMessageDetails
    ) external override onlywatchTower {
```

* **resultData:** The encoded result data from the execution.
* **transcripts:** Array of execution transcripts for verification.
* **wtExecutionId:**  The execution identifier.
* **status:** Execution status (0 = success, >0 = error).
* **callbackMessageDetails:** Additional details about the execution.

**Status types**

<table><thead><tr><th width="194.9453125">Status</th><th width="95.2421875">Code</th><th>Description</th></tr></thead><tbody><tr><td><code>SUCCESS</code></td><td><code>0</code></td><td>The execution completed successfully.</td></tr><tr><td><code>FAILED</code></td><td><code>1</code></td><td>This execution is invalid. Check the <code>callbackMessageDetails</code> for more information.</td></tr><tr><td><code>ERROR</code></td><td><code>2</code></td><td>A verified error occurred during execution. The network <em>did</em> reach consensus, and the agreed-upon result is that the program failed.</td></tr><tr><td><code>EXCEEDED</code></td><td><code>3</code></td><td>Execution was halted for exceeding the computational resource limit. You Should optimize your program or reduce input size before retrying.</td></tr><tr><td><code>CODE_HASH_MISMATCH</code></td><td><code>4</code></td><td>The executed code's hash does not match the one committed in the original <code>ExecutionRequest</code> .</td></tr></tbody></table>

{% hint style="warning" %}
**Key considerations:**

* Always check `status` before decoding `resultData`&#x20;
* Treat all non-zero statuses as failures; the exact value is useful for logging but your control flow should not depend on it.
  {% endhint %}
  {% endstep %}
  {% endstepper %}

## Grant Permissions

### User Contract Permission

In order to authorize the user contract, the task developer must grant permissions to the user contract over the namespace called in the \_requestExecution. To do so, please use the following CLI command

```
truebit auth grant <namespace_to_grant> <address_grantee>
```

* `namespace_to_grant`: Namespace mentioned in \_requestExecution.
* `address_grantee`: Contract address.

### Truebit Verify Hub Access

Each user who wants to execute API or Function Tasks via Dynamic Oracle must grant permissions to the Truebit Verify address to complete the connection. For example:

```
truebit auth grant <namespace_to_grant> <truebit_hub_address>
```

* `namespace_to_grant`: Namespace mentioned in \_requestExecution.
* `truebit_hub_address`:  `0xd70C3454aaD1B7ec660a064d8b1FE5708d898d84`.


# API Task With n8n Orchestration

This Dynamic Oracle implementation allows your smart contract to execute a pre deployed Truebit API Task pointing to an n8n workflow, providing off-chain computation with on-chain guarantees.

## Description

You can implement a custom N8N workflow to act as an off-chain processing layer that:

* Receives an execution request from your deployed smart contract.
* Executes Truebit API or Function tasks.
* Then triggers a second function task that extracts and encodes only the desired fields using `abi.encode`.
* And finally responds with the encoded output and transcript IDs for the on-chain callbackTask.<br>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcR_XHOYWpIOZWA_xuvlqKCyT3_kGHwrmrqLU5LgNLKj59OgxbZzWYlOGVbxQ8NU8QCY2UdqJ7vdW8UKeK3zIOk8ycNXWkX-tr4jyq4meTYJaCf6r1VVPHtUQJ_vCCAbu1bIoKUeQ?key=yM4bTL3u4RXxd1TQyVE1EA" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
By using an **n8n workflow**, you can encode and return only the specific field you want as the response.\
In contrast, executing directly against the **Truebit API** returns the entire JSON object.
{% endhint %}

## Flow Architecture

Your N8N workflow consists of the following nodes:

{% stepper %}
{% step %}

### **Webhook**

This is the Workflow entry point. The path should be defined in the manifest of your Truebit API task and also, must match the one specified in your Solidity contract’s payload.
{% endstep %}

{% step %}

### **API/Task node**

Triggers a Truebit Function or API task using the Truebit Endpoints.

**Example of calling a Truebit API TASK:**

```
{
"namespace": "a67fa7c8",
"taskName": "direct",
"input": {
"url": "https://api.restful-api.dev/objects?id=3",
"method": "GET",
"headers": {
"Content-Type": "application/json"
}
},
"executionTimeout": 10000,
"async": false
}
```

{% endstep %}

{% step %}

### **Task node**

Executes a Truebit function task that takes the response of the API task, selects only the required fields, and encodes them using Solidity's `abi.encode(...)` format. This allows the WatchTower to send those encoded values directly back to your smart contract in resultData.

**Example of calling a Truebit task to encode the output values**

```
{
"namespace": "a67fa7c8",
"taskName": "n8nvalueencode",
"input": "",
"requiredSolutions": 2,
"totalSolutions": 3,
"executionTimeout": 60000,
"async": false
}
```

**How it works:**

* The input for this task is built from the output of APINODE.
* The task runs a custom JS function in a sandboxed environment.
* The JS function selects and ABI-encodes only the fields the user needs (e.g., \[uint256, string]).
  {% endstep %}

{% step %}

### Respond to Webhook

Sends a structured response back to WatchTower.

**JSON response example**

```
{
"namespace": "a67fa7c8",
"taskName": "n8n",
"input": "",
"requiredSolutions": 2,
"totalSolutions": 3,
"executionTimeout": 60000,
"async": false
}
```

{% endstep %}
{% endstepper %}

## Execution Flow Summary

1. The smart contract sends a request to WatchTower (e.g. \[using requestGet...]).
2. WatchTower triggers the N8N webhook via HTTP.
3. N8N:
   1. Executes the API task using APINODE.
   2. Runs a JS task (TASKNODE) to process the API response and encode the final result.
   3. Returns the ABI-encoded result and transcript IDs to WatchTower.
4. WatchTower uses the returned data to invoke callbackTask(...) on your contract.

{% hint style="info" %}

#### Important!

* The value returned as encodedOutput must be ABI-encoded using Solidity types, matching what your contract expects in the callback.
* Ensure your N8N workflow returns a response within the configured timeout on WatchTower.
  {% endhint %}

### Encoding

The encodedOutput in the webhook response must be a string encoded using Solidity's ABI rules, e.g., via abi.encode(...) in your N8N logic. If your smart contract expects a string, uint, or a tuple of both, the data returned must match the expected structure and be properly encoded ahead of time.

For example, if your contract expects:

```solidity
(string value, uint256 number)
```

Then, in N8N you must do ABI encoding of that pair and return it as a hex string.

Here the N8N workflow full example json.

### Best Practices

* If supporting multiple simultaneous tasks, use a mapping of id => data instead of a single id variable.
* Customize the callbackTask logic as needed (e.g. conditional branching, retries, etc).
* Use abi.encode / abi.decode correctly when dealing with complex types.

### How To Implement It?

{% hint style="danger" %}
Make sure you have developed and deployed the API manifest first.
{% endhint %}

1. You must create a Dynamic Oracle API Task filling the payload with the n8n Webhook URL.
2. You must [grant](/developing-truebit-tasks/truebit-cli-reference#auth-grant) permission to the Truebit Verify Hub. Please execute:

```bash
truebit auth grant [options] <namespace> <grantee>
```

* `namespace`: The namespace where the Truebit API task was deployed
* grantee:&#x20;
  * Truebit Verify Hub Address: `0xd70C3454aaD1B7ec660a064d8b1FE5708d898d84` .

3. Handle the callback with the output you have defined in your n8n workflow.&#x20;


# Namespace Management

The task registration process means giving the task a simple, easy-to-remember name to make it easier to identify and use.

**Each time a** [**Task Developer** ](/overview/how-do-you-intend-to-use-truebit#task-developers)**deploys a new Truebit task, a new version is registered with a unique name.** This allows task requesters to easily identify the task for execution.

### **Namespace**&#x20;

Since Task names must be unique across the Truebit Ecosystem, and multiple Task Developers might choose the same name, we introduced the concept of namespaces. A namespace is a unique identifier that groups all the tasks registered by a specific group of developers.&#x20;

Think of it as a company name, like "Truebit," that groups all the tasks developed by that company. The namespace is owned by its creator and can be accessed by the owner and any users who have been granted permission. This makes task development accessible to a group of developers.

{% hint style="success" %}
During onboarding, we generate a default 8-digit namespace for you to start deploying tasks. You can also create a custom namespace with a name that represents you.
{% endhint %}

#### Managing a Namespace

Sometimes, it’s necessary to transfer ownership from one user to another. To do this, you can use the [namespace transfer](/developing-truebit-tasks/truebit-cli-reference#transfer) command in the CLI.

Additionally, you can grant permissions over a namespace to allow new users to collaborate on task development. Simply use the [namespace grant](/developing-truebit-tasks/truebit-cli-reference#grant) command in the CLI to grant permission. If you need to revoke a user's permission, you can do so with the [namespace revoke](/developing-truebit-tasks/truebit-cli-reference#revoke) command in the CLI.

These commands make it easy to manage ownership and permissions for namespaces, facilitating smooth collaboration and control over tasks.

### **Versioning**

Task development is an ongoing process, so we provide the ability to identify different versions of a task. Each time a new task ID is associated with a task name, an automatic version number is generated. This helps track the evolution and updates of tasks over time. The Task Requester can execute any version of the task.

### **Labeling**

Sometimes, we want to assign a friendly name to a specific task version, such as "latest," "stable," or "marshmallow." This friendly label helps the [Task Requester](/overview/how-do-you-intend-to-use-truebit#task-requesters) execute a specific version of the task identified by the specific label.

### Enabling and Disabling Tasks

Imagine a scenario where a Task Developer has deployed and registered multiple versions of the same task, with the code evolving to include new features and functionality. One day, a new bug is discovered, and the developer needs to fix it while also preventing anyone from executing a specific task version due to the critical bug.

To address this, we provide the [task disable](/developing-truebit-tasks/truebit-cli-reference#disable) command in the CLI, which allows developers to disable a specific version or all versions of a task.&#x20;

{% hint style="danger" %}
It's important to note that Truebit reserves the right to disable any task or task version if it is deemed to be malicious or harmful.
{% endhint %}


# Task Authorization

The Task Authorization Process involves giving permission to one or multiple users to execute a deployed and registered task.

**This process enables the Namespace Owner to grant or deny permissions to one or more users for executing deployed and registered tasks within the namespace.** This permission determines who can execute the task and who will be responsible for the associated costs.

<figure><img src="/files/YERw5qYMzFEvzi4785Bl" alt=""><figcaption><p>Task Authorization Process</p></figcaption></figure>

### Task Authorization Process

1. **Granting Permission:** The [Namespace owner](/developing-truebit-tasks/namespace-management#namespace) grants permission to the [Task Requester](/verifying-truebit-tasks/introduction) by calling the [auth grant](/developing-truebit-tasks/truebit-cli-reference#auth-grant) command within the Truebit CLI.
2. **Creating an API Key:** The Task Requester creates a new API key by calling the [auth new-apikey](/developing-truebit-tasks/truebit-cli-reference#auth-new-apikey) command from the Truebit CLI.
3. **Registering the API Key:** The Task Requester registers the API key by calling the [auth register](/developing-truebit-tasks/truebit-cli-reference#auth-register) command from the CLI. The person who registers the API key **will be responsible for paying for the task execution**, regardless of who calls the task.
   * The Task Requester can pass the created API key to someone else to execute the task. However, the one who registered the key will still pay for the execution: Imagine a development team consisting of several developers who need to execute the task. Each developer can have his/her own unique API key or share the same API key.
4. **Executing the Task:** The Task Requester calls the execute endpoint using the API key.
5. **Validating and Executing:** The [Dispatcher](/architecture/introduction/truebit-verify-hub#dispatcher) service validates that the API key has permission to execute tasks within the task namespace. If verified, the dispatcher starts the task execution workflow.

{% hint style="success" %}
During the Public Beta, Truebit will cover the cost of the task execution. To qualify, please ensure you’re registered on our platform.
{% endhint %}

### **Truebit CLI Commands**

To interact with the Task Authorization smart contract, we created several commands within the Truebit CLI:

#### [Auth Commands](/developing-truebit-tasks/truebit-cli-reference#auth)

* [auth grant](/developing-truebit-tasks/truebit-cli-reference#auth-grant)
* [auth revoke](/developing-truebit-tasks/truebit-cli-reference#auth-revoke)
* [auth register](/developing-truebit-tasks/truebit-cli-reference#auth-register)
* [auth deregister](/developing-truebit-tasks/truebit-cli-reference#auth-deregister)
* [auth check-authorization](/developing-truebit-tasks/truebit-cli-reference#auth-check-authorization)
* [auth get-payer](/developing-truebit-tasks/truebit-cli-reference#auth-get-payer)
* [auth new-apikey](/developing-truebit-tasks/truebit-cli-reference#auth-new-apikey)

These commands help manage who can execute the deployed task and who will be responsible for paying for those executions.

### **Accessing a Namespace**

To allow an address to execute tasks stored in a namespace, the namespace owner must grant permission. This can be done by calling the [auth grant](/developing-truebit-tasks/truebit-cli-reference#auth-grant) command from the CLI. Only the namespace owner has the authority to grant this permission. If the namespace owner wants to revoke the previously granted permission, they should call the [auth revoke](/developing-truebit-tasks/truebit-cli-reference#auth-revoke) command from the CLI.

### API\_KEYS

Any user with granted permission to a namespace can generate their own API\_KEYS using the [auth new-apikey](/developing-truebit-tasks/truebit-cli-reference#auth-new-apikey) command from the CLI. The user who generates the API\_KEY must register it by calling the [auth register](/developing-truebit-tasks/truebit-cli-reference#auth-register) command. The user who registers the API\_KEY becomes the payer for any task execution made using that API\_KEY.&#x20;

The API\_KEY allows others to execute tasks stored in the namespace while ensuring that the API\_KEY registrant pays for the execution.&#x20;

If the registrant wants to deregister the API\_KEY so that no one else with the API key can execute tasks, they should call the [auth deregister](/developing-truebit-tasks/truebit-cli-reference#auth-deregister) command from the CLI.

{% hint style="info" %}
To use the API KEY to execute a task, please look at the [Task Execution](/integrating-truebit-tasks/introduction) endpoint.
{% endhint %}


# Introduction

In this section, Task Requesters will learn how to execute verifiable Function and API tasks, apart from getting the execution transcript.

**Task Requesters will access and utilize the deployed tasks via Truebit platform.** **An API key and  a designated namespace will be provided to facilitate seamless integration with your applications.** This enables you to leverage Truebit as a reliable verification layer for your computations.

Task Requesters will receive both the task results and their corresponding verifications, ensuring data integrity and trustworthiness.

By following these straightforward steps, you can effortlessly integrate Truebit into your solution to obtain verified and trustworthy computation outcomes.

* [Integrate and execute Truebit Function Tasks](/integrating-truebit-tasks/function-task-execution)
* [Integrate and execute Truebit API Tasks](/integrating-truebit-tasks/api-task-execution)


# Function Task Execution

## Integrating and Executing Truebit Function Tasks

The Function Task Execution exposes your Truebit Task as an HTTP-based web service.&#x20;

<table><thead><tr><th width="390.1484375">Description</th><th>Endpoint</th></tr></thead><tbody><tr><td>To run a Function Task</td><td><a href="/pages/EJdZb6gyvrCYqoWiZWDX">Function Task execution endpoint</a></td></tr><tr><td>To poll for outputs of asynchronous or long-running tasks</td><td><a href="/pages/eXsJfaHEIRd6fuXv9aiE#task-function-execution-status-executionid">Function Task status endpoint</a></td></tr><tr><td>To get the Execution Transcript</td><td><a href="/pages/UulBwEplOpxECIC8bLw1">Get Execution Transcript endpoint</a></td></tr><tr><td>To get the Execution invoice Transcript</td><td><a href="/pages/XpneYD7rELYS4r3vv25R">Get Execution Invoice Trans</a></td></tr></tbody></table>


# Execute Function Tasks

## API Doc

Interactive API docs can be found at: [https://run.truebit.network/http-gateway/api-docs/](https://run.truebit.network/dispatcher/api-docs/)

## Overview

You can configure the endpoint to return either a synchronous or asynchronous response. In synchronous mode, if the result is ready before the timeout, it will be returned immediately. Otherwise, you’ll receive an `executionId`, which can be used to check the result later through the status endpoint.

## Execute a task by name

> Execute a task using the provided task name. Supports both synchronous and asynchronous execution.

```json
{"openapi":"3.1.0","info":{"title":"Task Execution API","version":"1.120.0-beta.275"},"tags":[{"name":"Function task execution","description":"Function task execution by id and namespace"}],"servers":[{"description":"Public beta","url":"https://run.truebit.network"},{"description":"Current environment relative paths","url":"/"}],"paths":{"/task/function/execute-by-name":{"post":{"summary":"Execute a task by name","description":"Execute a task using the provided task name. Supports both synchronous and asynchronous execution.","operationId":"executeTaskByName","tags":["Function task execution"],"parameters":[{"in":"header","name":"x-api-key","required":true,"schema":{"type":"string"},"description":"API key for authentication."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"namespace":{"type":"string","description":"The namespace of the task."},"taskName":{"type":"string","description":"The name of the task to be executed."},"label":{"type":"string","description":"Label of the task."},"version":{"type":"integer","format":"uint32","description":"Version number of the task."},"async":{"type":"boolean","description":"If true, the endpoint will retrieve the executionId; otherwise, it will try to return the execution result only if it completes within 60 seconds."},"input":{"type":"string","description":"Input data required for task execution."},"totalSolutions":{"type":"integer","format":"uint32","description":"Total number of solutions required for the task."},"requiredSolutions":{"type":"integer","format":"uint32","description":"Number of solutions required to complete the task."},"taskRequesterTimestamp":{"type":"integer","format":"uint32","description":"Task Requester Timestamp. This value is used to calculate the random bits in the node selection Phase."},"gasLimit":{"type":"string","description":"Execution step limit."}},"required":["namespace","taskName","async","input","totalSolutions","requiredSolutions","taskRequesterTimestamp"]}}}},"responses":{"200":{"description":"Successful operation","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ExecuteTaskAsyncResponse"},{"$ref":"#/components/schemas/ExecuteTaskSyncResponse"}]}}}},"400":{"description":"Bad request, invalid input.","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/BadRequestResponse"},{"$ref":"#/components/schemas/BlockchainSignedError"}]}}}},"401":{"description":"Not authorized.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"402":{"description":"Payment required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Internal server error.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"components":{"schemas":{"ExecuteTaskAsyncResponse":{"type":"object","description":"Asynchronous response of task execution.","properties":{"executionId":{"type":"string","description":"The ID of the task execution."}}},"ExecuteTaskSyncResponse":{"type":"object","description":"Synchronous response of task execution.","properties":{"executionId":{"type":"string","description":"The ID of the task execution."},"clearTextSolution":{"type":"object","description":"The result of the task execution.","properties":{"output":{"type":"string","description":"The output of the task execution."},"executionStatus":{"type":"string","description":"The status of the task execution.","enum":["succeed","failed"]},"senderAddress":{"type":"string","description":"The address of the sender."},"signature":{"type":"object","description":"Signature details of the execution.","properties":{"v":{"type":"integer","format":"int64","description":"The recovery id of the signature."},"r":{"type":"string","description":"The 'r' value of the signature."},"s":{"type":"string","description":"The 's' value of the signature."}}}}},"verificationStatus":{"type":"string","description":"The status of the task verification.","enum":["Success","Running","Indeterminate","Error"]}}},"BadRequestResponse":{"type":"object","description":"Bad request","properties":{"message":{"type":"string","description":"Error message."}}},"BlockchainSignedError":{"type":"object","description":"Blockchain Signed Error","properties":{"status":{"type":"number","description":"Error code."},"message":{"type":"string","description":"Error message."},"taskRegistryContract":{"type":"string","description":"Task Registry Contract address."},"nodeRegistryContract":{"type":"string","description":"Node Registry Contract address."},"authorizationContract":{"type":"string","description":"Authorization Contract address."},"chainId":{"type":"string","description":"Chain identification."},"blockHash":{"type":"string","description":"Block hash."},"blockNumber":{"type":"number","description":"Block number."},"signedError":{"type":"string","description":"Error signed by hub."}}},"Error":{"type":"object","description":"Internal server error","properties":{"message":{"type":"string","description":"Internal server error"}}}}}}
```

### Authorization

#### API KEY

To get authorization to execute a task, include your registered `API key` in the request header. This allows Truebit to validate your access and identify the account responsible for covering the task execution cost (linked to the API key’s associated address).

**Example**

```
X-API-KEY: be0dc6ba-9a60-4777-b5b7-60ed2397e3ed
```


# Get Task Status Function

## API Doc

Interactive API docs can be found at: <https://run.truebit.network/http-gateway/api-docs/>

## Overview

By calling this endpoint, you’ll receive the Function Task execution status and, if available, the result associated with the specified `executionId` &#x20;

## Get execution status by execution ID of a FUNCTION TASK

> Retrieve the status of a task execution using the execution ID.

```json
{"openapi":"3.1.0","info":{"title":"Task Execution API","version":"1.120.0-beta.275"},"tags":[{"name":"Task execution status","description":"Check status of a task execution"}],"servers":[{"description":"Public beta","url":"https://run.truebit.network"},{"description":"Current environment relative paths","url":"/"}],"paths":{"/task/function/execution-status/{executionId}":{"get":{"summary":"Get execution status by execution ID of a FUNCTION TASK","description":"Retrieve the status of a task execution using the execution ID.","operationId":"getFunctionExecutionStatus","tags":["Task execution status"],"parameters":[{"in":"path","name":"executionId","required":true,"schema":{"type":"string"},"description":"The ID of the task execution."}],"responses":{"200":{"description":"Successful function task response with execution status.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecuteTaskSyncResponse"}}}},"404":{"description":"Execution ID not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BadRequestResponse"}}}},"500":{"description":"Internal server error.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"components":{"schemas":{"ExecuteTaskSyncResponse":{"type":"object","description":"Synchronous response of task execution.","properties":{"executionId":{"type":"string","description":"The ID of the task execution."},"clearTextSolution":{"type":"object","description":"The result of the task execution.","properties":{"output":{"type":"string","description":"The output of the task execution."},"executionStatus":{"type":"string","description":"The status of the task execution.","enum":["succeed","failed"]},"senderAddress":{"type":"string","description":"The address of the sender."},"signature":{"type":"object","description":"Signature details of the execution.","properties":{"v":{"type":"integer","format":"int64","description":"The recovery id of the signature."},"r":{"type":"string","description":"The 'r' value of the signature."},"s":{"type":"string","description":"The 's' value of the signature."}}}}},"verificationStatus":{"type":"string","description":"The status of the task verification.","enum":["Success","Running","Indeterminate","Error"]}}},"BadRequestResponse":{"type":"object","description":"Bad request","properties":{"message":{"type":"string","description":"Error message."}}},"Error":{"type":"object","description":"Internal server error","properties":{"message":{"type":"string","description":"Internal server error"}}}}}}
```

### **verificationStatus**

|                   |                                                                                                                                                                                                                                                                   |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Success**       | The Task execution was completed successfully. The result was received within the specified timeout, and all nodes provided the same response.                                                                                                                    |
| **Running**       | The Function task is still being executed.                                                                                                                                                                                                                        |
| **Indeterminate** | A consensus on the result couldn't be reached. This could be because the execution took too long, nodes gave different answers (requiring an adjudication process resolution), or we received fewer responses than the required solutions defined in the request. |
| **Error**         | There was an error during the task execution                                                                                                                                                                                                                      |


# API Task Execution

Use the Task Execution API to call Function and API Tasks from an HTTP client.

The API Task Execution exposes your Truebit Task as an HTTP-based web service.&#x20;

<table><thead><tr><th width="390.1484375">Description</th><th>Endpoint</th></tr></thead><tbody><tr><td>To run an API Task</td><td><a href="/pages/UNBNz0wJQM3NetTPr784">API Task execution endpoint</a></td></tr><tr><td>To poll for outputs of asynchronous or long-running tasks</td><td><a href="/pages/Obe1O4vOSbhgrOKTB0BJ">API Task status endpoint</a></td></tr><tr><td>To get the Execution Transcript</td><td><a href="/pages/UulBwEplOpxECIC8bLw1">Get Execution Transcript endpoint</a></td></tr><tr><td>To get the Execution invoice Transcript</td><td><a href="/pages/XpneYD7rELYS4r3vv25R">Get Execution Invoice Trans</a></td></tr></tbody></table>


# Execute API Tasks

## API Doc

Interactive API docs can be found at: <https://run.truebit.network/dispatcher/api-docs/>

## Overview

You can configure the endpoint for either a synchronous or asynchronous response. In sync mode, if the result is ready within 60 seconds, it will be returned immediately. If not, you'll receive an executionId, which you can use to check the result later by calling the status endpoint.

When executing an [API Task](/developing-truebit-tasks/how-to-create-api-tasks), your task `input` will need to specify the API endpoint path, HTTP method type, and API input parameters.  These parameters must match the schema defined in the API Task manifest.

## Execute an API Task by task name

> Execute an API Task using the provided task name. Supports both synchronous and asynchronous execution.

```json
{"openapi":"3.1.0","info":{"title":"Task Execution API","version":"1.120.0-beta.275"},"tags":[{"name":"API task execution","description":"Api task execution by id and namespace"}],"servers":[{"description":"Public beta","url":"https://run.truebit.network"},{"description":"Current environment relative paths","url":"/"}],"paths":{"/task/api/execute-by-name":{"post":{"summary":"Execute an API Task by task name","description":"Execute an API Task using the provided task name. Supports both synchronous and asynchronous execution.","operationId":"executeApiTaskByName","tags":["API task execution"],"parameters":[{"in":"header","name":"x-api-key","required":true,"schema":{"type":"string"},"description":"API key for authentication."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"namespace":{"type":"string","description":"The namespace of the task."},"taskName":{"type":"string","description":"The name of the task to be executed."},"label":{"type":"string","description":"Label of the task."},"version":{"type":"integer","format":"uint32","description":"Version number of the task."},"async":{"type":"boolean","description":"If true, the endpoint will retrieve the executionId; otherwise, it will try to return the execution result only if it completes within 60 seconds."},"input":{"type":"object","description":"Input data required for task execution."},"executionTimeout":{"type":"integer","format":"uint32","description":"Timeout for task execution in seconds."}},"required":["namespace","taskName","async","input","executionTimeout"]}}}},"responses":{"200":{"description":"Successful execution","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ExecuteApiSyncResponse"},{"$ref":"#/components/schemas/ExecuteTaskAsyncResponse"}]}}}},"400":{"description":"Bad request, invalid input.","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/BadRequestResponse"},{"$ref":"#/components/schemas/BlockchainSignedError"}]}}}},"401":{"description":"Not authorized.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"402":{"description":"Payment required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Internal server error.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"components":{"schemas":{"ExecuteApiSyncResponse":{"type":"object","description":"Successful execution of the API task.","properties":{"executionId":{"type":"string","description":"The ID of the executed task."},"clearTextSolution":{"type":"object","description":"The result of the API task execution.","properties":{"output":{"type":"object","description":"The output of the task execution, containing task-specific details."},"status":{"type":"string","description":"Status of the execution within the solution.","enum":["succeed","failed"]},"senderAddress":{"type":"string","description":"The address of the sender who executed the task."}}},"status":{"type":"string","description":"Status of the execution.","enum":["Success","Running","Error"]},"totalTransferredBytes":{"type":"object","description":"Total bytes transferred during the request and response.","properties":{"request":{"type":"integer","description":"Bytes transferred in the request."},"response":{"type":"integer","description":"Bytes transferred in the response."}}},"errorMsg":{"type":"string","description":"Error message if execution encountered issues but still returned a result."}}},"ExecuteTaskAsyncResponse":{"type":"object","description":"Asynchronous response of task execution.","properties":{"executionId":{"type":"string","description":"The ID of the task execution."}}},"BadRequestResponse":{"type":"object","description":"Bad request","properties":{"message":{"type":"string","description":"Error message."}}},"BlockchainSignedError":{"type":"object","description":"Blockchain Signed Error","properties":{"status":{"type":"number","description":"Error code."},"message":{"type":"string","description":"Error message."},"taskRegistryContract":{"type":"string","description":"Task Registry Contract address."},"nodeRegistryContract":{"type":"string","description":"Node Registry Contract address."},"authorizationContract":{"type":"string","description":"Authorization Contract address."},"chainId":{"type":"string","description":"Chain identification."},"blockHash":{"type":"string","description":"Block hash."},"blockNumber":{"type":"number","description":"Block number."},"signedError":{"type":"string","description":"Error signed by hub."}}},"Error":{"type":"object","description":"Internal server error","properties":{"message":{"type":"string","description":"Internal server error"}}}}}}
```

### Custom Headers

When executing API tasks, you may need to include custom HTTP headers in the request to the target API. This is common for authentication tokens, custom identifiers, or specifying content preferences.

#### Adding Headers to Your Request

You will need to include a `headers` object within the `input` field of your request body. Truebit will inject these headers into the final API call to the target endpoint.

> **Note:** This feature is separate from the Truebit API authentication header (`X-API-KEY`), which is used to authenticate your request to Truebit. Custom headers you define in the `input.headers` object will be forwarded to the target API you are calling.

#### Supported Header Types

You can include any standard HTTP header, such as:

* **Authorization** – Bearer tokens, Basic auth, API keys for the target service.
* **Accept** – Specify expected response format (e.g., `application/json`, `application/xml`).
* **Content-Type** – Define the request body format when using POST/PUT methods.
* **Custom Headers** – Any application-specific headers required by the target API (e.g., `X-Custom-Header`, `X-Request-ID`).

<details>

<summary>Example: Executing an API Task with Custom Headers</summary>

```bash
curl -s -X POST "https://run.truebit.network/task/api/execute-by-name" \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: YOUR_TRUEBIT_API_KEY" \
  -d '{
    "namespace": "3a2b5129",
    "taskName": "custom",
    "input": {
      "path": "/anything/{Id}",
      "method": "GET",
      "params": {
        "Id": 12345
      },
      "headers": {
        "Authorization": "Bearer YOUR_TARGET_API_TOKEN",
        "X-Custom-Header": "CustomValue123",
        "Accept": "application/json"
      }
    },
    "executionTimeout": 30000,
    "async": false
  }'
```

</details>

#### Request Structure

| Field           | Location       | Description                                            |
| --------------- | -------------- | ------------------------------------------------------ |
| `X-API-KEY`     | Request Header | Your Truebit API key for authentication with Truebit   |
| `input.headers` | Request Body   | Custom headers to be injected into the target API call |

#### Important Notes

1. **Header Injection**: Headers defined in `input.headers` are injected by Truebit into the outgoing request to the target API endpoint.
2. **Authentication Separation**: Keep in mind the distinction between:
   * `X-API-KEY` in the request header → Authenticates your request to Truebit.
   * `Authorization` (or other auth headers) in `input.headers` → Authenticates the request to your target API.
3. **CLI Authentication**: If you previously configured authentication headers using the Truebit CLI tool, you can now alternatively include them directly in the request body using `input.headers`. Both methods are supported.
4. **Header Overrides**: Headers specified in `input.headers` will be included in the final request to the target API. Ensure there are no conflicts with headers that may be automatically set by Truebit.

### Authorization

#### API KEY

To get authorization to execute a task, include your registered `API key` in the request header. This allows Truebit to validate your access and identify the account responsible for covering the task execution cost (linked to the API key’s associated address).

**Example**

```
X-API-KEY: be0dc6ba-9a60-4777-b5b7-60ed2397e3ed
```


# Get Task Status API

## API Doc

Interactive API docs can be found at: <https://run.truebit.network/dispatcher/api-docs/>

## Overview

By calling this endpoint, you’ll receive the API Task execution status and, if available, the result associated with the specified `executionId`

## Get execution status by execution ID of an API TASK

> Retrieve the status of an API task execution using the execution ID.

```json
{"openapi":"3.1.0","info":{"title":"Task Execution API","version":"1.120.0-beta.275"},"tags":[{"name":"Task execution status","description":"Check status of a task execution"}],"servers":[{"description":"Public beta","url":"https://run.truebit.network"},{"description":"Current environment relative paths","url":"/"}],"paths":{"/task/api/execution-status/{executionId}":{"get":{"summary":"Get execution status by execution ID of an API TASK","description":"Retrieve the status of an API task execution using the execution ID.","operationId":"getApiExecutionStatus","tags":["Task execution status"],"parameters":[{"in":"path","name":"executionId","required":true,"schema":{"type":"string"},"description":"The ID of the task execution."}],"responses":{"200":{"description":"Successful api task response with execution status.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecuteApiSyncResponse"}}}},"404":{"description":"Execution ID not found.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BadRequestResponse"}}}},"500":{"description":"Internal server error.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"components":{"schemas":{"ExecuteApiSyncResponse":{"type":"object","description":"Successful execution of the API task.","properties":{"executionId":{"type":"string","description":"The ID of the executed task."},"clearTextSolution":{"type":"object","description":"The result of the API task execution.","properties":{"output":{"type":"object","description":"The output of the task execution, containing task-specific details."},"status":{"type":"string","description":"Status of the execution within the solution.","enum":["succeed","failed"]},"senderAddress":{"type":"string","description":"The address of the sender who executed the task."}}},"status":{"type":"string","description":"Status of the execution.","enum":["Success","Running","Error"]},"totalTransferredBytes":{"type":"object","description":"Total bytes transferred during the request and response.","properties":{"request":{"type":"integer","description":"Bytes transferred in the request."},"response":{"type":"integer","description":"Bytes transferred in the response."}}},"errorMsg":{"type":"string","description":"Error message if execution encountered issues but still returned a result."}}},"BadRequestResponse":{"type":"object","description":"Bad request","properties":{"message":{"type":"string","description":"Error message."}}},"Error":{"type":"object","description":"Internal server error","properties":{"message":{"type":"string","description":"Internal server error"}}}}}}
```

### **status**

|             |                                                                                                      |
| ----------- | ---------------------------------------------------------------------------------------------------- |
| **Success** | The Task execution was completed successfully. The result was received within the specified timeout. |
| **Running** | The API task is still being executed.                                                                |
| **Error**   | There was an error during the task execution                                                         |


# Get Transcript

## API Doc

Interactive API docs can be found at: <https://run.truebit.network/transcript-query/api-docs/>

## Overview

By calling this endpoint, you’ll receive the Transcript associated with the given  `executionId`  or `transcriptHash`.

## Find transcript by executionId

> Returns the transcript associated with the given executionId parameter

```json
{"openapi":"3.1.0","info":{"title":"Transcript and Invoice","version":"1.149.0"},"tags":[{"name":"Transcript","description":"Transcript query endpoints"}],"servers":[{"description":"Production","url":"https://run.truebit.network"},{"description":"Current environment relative paths","url":"/"}],"paths":{"/task/{executionId}/transcript":{"get":{"tags":["Transcript"],"summary":"Find transcript by executionId","description":"Returns the transcript associated with the given executionId parameter","operationId":"getTranscriptByExecutionId","parameters":[{"name":"executionId","in":"path","description":"Task executionId","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful operation","content":{"application/json":{"schema":{"type":"object"}}}},"404":{"description":"Cannot find the transcript associated with the given executionId","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}}}}}}}}}}}
```

## Find transcript by transcriptHash

> Returns the transcript associated with the given transcriptHash parameter

```json
{"openapi":"3.1.0","info":{"title":"Transcript and Invoice","version":"1.149.0"},"tags":[{"name":"Transcript","description":"Transcript query endpoints"}],"servers":[{"description":"Production","url":"https://run.truebit.network"},{"description":"Current environment relative paths","url":"/"}],"paths":{"/task/hash/{transcriptHash}/transcript":{"get":{"tags":["Transcript"],"summary":"Find transcript by transcriptHash","description":"Returns the transcript associated with the given transcriptHash parameter","operationId":"getTranscriptByTranscriptHash","parameters":[{"name":"transcriptHash","in":"path","description":"Transcript hash","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful operation","content":{"application/json":{"schema":{"type":"object"}}}},"404":{"description":"Cannot find the transcript associated with the given transcriptHash","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}}}}}}}}}}}
```

### Response Data

It returns the Function Transcript associated with the given `executionId`  or `transcriptHash`.

Function Transcript examples

* [Verified Function Transcript example](/architecture/execution-transcripts/function-transcript)
* [Non-Concensus Function Transcript example ](/architecture/execution-transcripts/non-consensus-transcript)

API Transcript examples

* [API Transcript example](/architecture/execution-transcripts/api-transcript)


# Get Invoice

## API Doc

Interactive API docs can be found at: <https://run.truebit.network/transcript-query/api-docs/>

## Overview

By calling this endpoint, you’ll receive the Invoice Transcript associated with the given  `executionId`  or `transcriptHash`.

## Find transcript invoice by executionId

> Returns the transcript invoice associated with the given executionId parameter

```json
{"openapi":"3.1.0","info":{"title":"Transcript and Invoice","version":"1.149.0"},"tags":[{"name":"Invoice","description":"Invoice info of a task execution"}],"servers":[{"description":"Production","url":"https://run.truebit.network"},{"description":"Current environment relative paths","url":"/"}],"paths":{"/task/{executionId}/transcriptInvoice":{"get":{"operationId":"getTranscriptInvoiceByExecutionId","tags":["Invoice"],"summary":"Find transcript invoice by executionId","description":"Returns the transcript invoice associated with the given executionId parameter","parameters":[{"name":"executionId","in":"path","description":"Execution Id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful operation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Invoice"}}}},"404":{"description":"Cannot find any invoice for given executionId","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}}}}}}}}}},"components":{"schemas":{"Invoice":{"type":"object","properties":{"executionId":{"type":"string"},"taskId":{"type":"string"},"taskCreated_timeStamp":{"type":"integer"},"invoiceId":{"type":"string"},"stepGasPrice":{"type":"number"},"byteGasPrice":{"type":"number"},"accounting_signature":{"type":"string"},"lineItem":{"type":"array","items":{"$ref":"#/components/schemas/LineItem"}}}},"LineItem":{"type":"object","properties":{"operation":{"type":"string","enum":["Pay","Charge","Penalty"]},"account":{"type":"string"},"total_steps_computed":{"type":"integer"},"peak_memory_used":{"type":"integer"},"transferredBytes":{"type":"object","description":"Decoded request/response body sizes captured by the enclave for API executions. Excludes HTTP framing/headers and TLS overhead.","properties":{"requestBodyDecodedBytes":{"type":"integer"},"responseBodyDecodedBytes":{"type":"integer"}}},"reason":{"type":"string"}}}}}}
```

### Response Data

It returns the Invoice Transcript associated with the given `executionId`  or `transcriptHash`  &#x20;

* [Invoice Transcript example](/architecture/execution-transcripts/invoice-transcript)


# Introduction

In this section, Operators who want to contribute computing power will learn how to verify tasks.

**To became a Decentralized Node Operator, you will need to install a Truebit Node** by following the [Tuebit Node Installation Guide.](/verifying-truebit-tasks/truebit-node-installation-guide) This document will help you to set up your Truebit Decentralized Verification Node, empowering your system to contribute to the integrity and performance of the Truebit network.


# Node Status

Use the public dashboard to check whether a node is registered and whether it was recently slashed by following these three simple steps:

1. Visit: <https://nodes.truebit.io/>
2. Enter the node wallet address.
3. Click "**Fetch Status"**.

The page will show the node status details:

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

If the node is not registered, you’ll see a **“not registered”** result:

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

{% hint style="info" %}
The dashboard keeps the **last 5 days** **of data.**
{% endhint %}


# Truebit Node Installation Guide

This guide will walk you through the process of setting up a Truebit Decentralized Verification Node, enabling your system to participate in verifying Truebit tasks on the network.

### System Requirements for a Truebit Node

Truebit Node is designed to run on cloud infrastructure (such as AWS or Google Cloud) or can alternatively be installed locally on your computer.

For **optimal uptime and reliability, cloud deployment is strongly recommended**. This approach ensures your verification node remains online 24/7 without the stability risks of running it on a personal machine. For cost-effective deployment, a cloud provider's free tier is an acceptable option.

#### **Creating a FREE Tier Cloud instance**

If you're new to cloud deployment, these official guides will help you create a compatible VM:

* AWS: [Launch an EC2 t3.small instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html)
* Google Cloud: [Create an e2-micro VM](https://cloud.google.com/compute/docs/create-linux-vm-instance)

**Note**: Select Ubuntu 22.04 LTS or later as your OS, then install Docker using the [official installation guide](https://docs.docker.com/engine/install/ubuntu/).

## Prerequisites

* **Wallet Address — Ethereum-Compatible (EVM)**

{% hint style="danger" %}
Create a **new** wallet address — **don’t use an existing one**. You’ll need to share its **private key** with the node, so it must be used **only** for this server.
{% endhint %}

***Why:** this keeps your personal funds safe and ensures you stay in control if the server is lost or replaced.*

**Steps:**

1. Create a new wallet with [MetaMask](https://metamask.io) or [MyCrypto](https://www.mycrypto.com).
2. Export and securely store the **private key**.
3. Use this wallet **only** for running the node.

* **AVAX balance:** The node operator pays for the Avalanche Gas used in registration and de-registration transactions.
* **$TRU stake:** Running a Truebit node requires **2,000 TRU tokens** to be staked. This stake is essential for the **slashing and reward mechanism** that ensures honest participation and secure verification.

{% hint style="success" %}
We run a limited-capacity **Stake Sponsorship Program** to support selected node operators.\
If you’d like to be considered for an invitation, please submit your request via <http://forms.truebit.io/>
{% endhint %}

## Setup The Truebit Node

### Create Docker-compose.yml File

Create a new file named **`docker-compose.yml`** and paste the configuration below.

{% hint style="success" %}
You can use any plain-text editor — for example: `nano docker-compose.yml` or `vim docker-compose.yml`
{% endhint %}

```yaml
name: truebit_runner_node
services:
  runner-node:
    image: truebitprotocol/runner-node:prod
    platform: linux/amd64
    container_name: runner-node
    pull_policy: always
    stop_signal: SIGINT
    stop_grace_period: 30s
    environment:
      - RABBITMQ_URL=amqps://runneruser:X4uj1hbWc79vZ6@tcp.truebit.network:30010/truebit-nextgen
      - FILESYSTEM_URL=https://prod-minio.truebit.network
      - FILESYSTEM_ACCESS_KEY=eHSCx431M1khHMc
      - FILESYSTEM_SECRET_KEY=6DnIQrM2wIyY09rT
      - PRIVATE_KEY= (to be added by the user)

```

Replace the `PRIVATE_KEY` field with your own private key that has already been staked with $TRU.

{% hint style="success" %}
If your private key starts with `0x`, **remove the `0x` prefix** before pasting it.
{% endhint %}

### Start Truebit Node

```bash
docker compose -f docker-compose.yml up -d 
```

### Node status

Use these checks right after you start the node.

#### Check the container is running

```bash
docker compose -f docker-compose.yml ps
```

You should see `runner-node` in a `running` state.

#### Watch the node logs

```bash
docker logs runner-node -f
```

Use this to confirm the node connects to the network and stays online.

#### Confirm the node is registered on-chain

On startup and shutdown, the node registers and de-registers via the [Node Registry smart contract](/architecture/audit-layer#node-registry-smart-contract).

For a quick UI check (registration + recent slashing history), use: [Node Status](/verifying-truebit-tasks/node-status).

{% hint style="info" %}
The node address is the EVM address derived from the `PRIVATE_KEY` you configured.
{% endhint %}

If you need to stop your Truebit Verification Node, run the following command:

```bash
docker compose -f docker-compose.yml down -v
```

If you want, you can check the logging command by executing this:

```bash
docker logs <CONTAINER_NAME> 
```

```bash
docker logs <CONTAINER_NAME> -f
```

{% hint style="info" %}
**IMPORTANT!** For reliable node operation, **you must use** `docker compose down` when performing a shutdown. Any other shutdown method may cause **registration inconsistencies**. If the Node fails to properly de-register, and the Hub subsequently assigns it a task, the Node will be **forcibly de-registered** after failing to respond.
{% endhint %}


# Truebit Unchained Protocol

### Transparency to Off-chain Compute

Truebit Verify is underpinned by the latest research in verified compute. Our technical report lays out transparency as a new standard for certifying the integrity of decentralized compute tasks.

### **Key Concepts**

#### Decentralized & Centralized Services

We've introduced ‘transparency’ as a new standard for certifying the integrity of serverless operations by bridging the gap between decentralized and centralized services.

#### Transcripts Provide Proof

Platform-independent, certified transcripts detail execution soundness and make applications tamper-proof.

#### Smoking Guns and Red Balloons

Machines can resist censorship by reporting smoking guns via ledger transactions or through game-theory techniques inspired by DARPA’s ‘Red Balloon Challenge.’

### Download The Technical Report

Click [here](https://truebit.io/unchained-report/) to download the technical report.


# Support

Join our vibrant Truebit community on [Discord](https://discord.com/invite/j34Yt6MGck) for ongoing support, engaging discussions, and the latest updates—your dedicated resource for seamless collaboration and assistance.

For general inquiries, contact us at <Hello@truebit.io>.


