# API Task

{% hint style="info" %}
To execute a Truebit task, you must first deploy it using the Truebit CLI (run [truebit deploy](https://devs.truebit.io/truebit-cli-reference#deploy)).\
Once deployed, you will need both the `namespace` and the `task name` of your API task.
{% endhint %}

### 1. Inherit From BaseTBContract

Import `BaseTBContract.sol` contract and extend from it.

### 2. Constructor

When deploying the contract, ensure you set the correct values for both **watchTowerAddress** and **sourceCode** within your contract:

* **watchTowerAddress**: `0xEcd0EeD24Ed6a54d05a07125c4ccb809b3A09868`.
* **sourceCode**: Leave it as an empty string (`""`).

### 3. 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.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 arameters 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)
```

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

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

### 4. 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.

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