# Web3 SDK Reference

> **Status**: WIP — Early Draft

This document provides a comprehensive reference for interacting with Cortensor smart contracts using the `ethers.js` library. It covers session and task management, along with contract event listening for dApp integrations.

***

### Setup

#### Required Dependencies

```bash
npm install ethers
```

#### Configuration

```javascript
const SESSION_V2_ADDRESS = "0x...";        // SessionV2 contract address
const SESSION_QUEUE_V2_ADDRESS = "0x...";  // SessionQueueV2 contract address
const PUBLIC_RPC_URL = "https://...";      // RPC URL for the network
```

#### Required ABIs

* `SessionV2.json` - ABI for the Session V2 contract
* `SessionQueueV2.json` - ABI for the Session Queue V2 contract

***

### Session Management

#### `create`

<pre class="language-solidity"><code class="lang-solidity">function create(
  string memory name,
  string memory metadata,
  address variableAddress,
  uint256 minNumOfNodes,
  uint256 maxNumOfNodes,
  uint256 redundant,
  uint256 numOfValidatorNodes,
  uint256 mode,
  bool reserveEphemeralNodes,
<strong>  uint256 sla,
</strong>  uint256 modelIdentifier,
  uint256 reservePeriod,
  uint256 maxTaskExecutionCount
) external;
</code></pre>

Creates a new session.

```js
const tx = await sessionContract.create(
  "My Session",
  "Metadata",
  await signer.getAddress(),
  1, 3, 1, 0, 0,
  false,
  0,
  0,
  300,
  5
);
await tx.wait();
```

***

#### `getSessions`

```solidity
function getSessionsByAddress(address userAddr) external view returns (Session[] memory);
```

Returns all sessions owned by a user address.

```js
const sessions = await sessionContract.getSessionsByAddress("0xYourAddress");
```

***

#### `getSession`

```solidity
function getSession(uint256 sessionId) external view returns (Session memory);
```

Returns details for a session by ID.

```js
const session = await sessionContract.getSession(0);
```

***

#### `getSessionMiners`

```solidity
function getEphemeralNodes(uint256 sessionId) external view returns (address[] memory);
```

Returns ephemeral miners assigned to a session.

```js
const miners = await sessionContract.getEphemeralNodes(0);
```

***

#### `updateSession`

```solidity
function update(
  string memory name,
  string memory metadata,
  uint256 sessionId,
  uint256 minNumOfNodes,
  uint256 maxNumOfNodes,
  uint256 redundant,
  uint256 numOfValidatorNodes,
  uint256 mode
) public;
```

Updates session configuration.

```js
await sessionContract.update(
  "Updated Name",
  "Updated Metadata",
  0, 2, 4, 2, 0, 0
);
```

***

### Task Management

#### `submit`

```solidity
function submit(
  uint256 sessionId,
  uint256 nodeType,
  string calldata taskData,
  uint256 promptType,
  string calldata promptTemplate,
  uint256[] calldata llmParams,
  string calldata clientReference
) external;
```

Submits a task to the session.

```js
await sessionContract.submit(
  0,
  0,
  JSON.stringify({ type: "chat", message: "Hello" }),
  0,
  "",
  [1024, 1, 1, 1, 0, 0],
  "my-client-side-reference"
);
```

***

#### `getTasksBySessionId`

```solidity
function getTasksBySessionId(uint256 sessionId) public view returns (Task[] memory);
```

Returns all tasks for a session.

```js
const tasks = await queueContract.getTasksBySessionId(0);
```

***

#### `getTaskResults`

```solidity
function getTaskResults(uint256 sessionId, uint256 taskId) public view returns (address[] memory, string[] memory);
```

Returns the results submitted by miners for a specific task.

```js
const [miners, results] = await queueContract.getTaskResults(0, 0);
```

***

### Events

#### SessionV2 Contract Events

* `SessionCreated(uint256 sessionId, bytes32 sid, address owner, address[] miners)`
* `SessionUpdated(uint256 indexed sessionId, address indexed updater, uint256 minNumOfNodes, uint256 maxNumOfNodes, uint256 redundant)`
* `SessionDeactivated(uint256 indexed sessionId, address indexed deactivator)`

***

#### SessionQueueV2 Contract Events

* `TaskQueued(uint256 sessionId, uint256 taskId, uint256 globalId, string taskData)`
* `TaskAssigned(uint256 sessionId, uint256 taskId, address[] miners)`
* `TaskEnded(uint256 sessionId, uint256 taskId, address[] miners)`

***

### Listening to Events

```js
const provider = new ethers.WebSocketProvider(PUBLIC_RPC_URL.replace('https', 'wss'));
const queueContract = new ethers.Contract(SESSION_QUEUE_V2_ADDRESS, SessionQueueV2ABI, provider);

queueContract.on("TaskEnded", (sessionId, taskId, miners, event) => {
  console.log(`Task ${taskId} in session ${sessionId} completed`);
});
```

***

### Notes

* Use a secure provider (e.g. Alchemy, Infura)
* Wrap contract calls in try/catch
* Monitor for transaction failures
* For production, use hardware wallets for signing

***

### Error Handling

```js
try {
  const tx = await contract.fn();
  await tx.wait();
} catch (error) {
  console.error("Contract call failed:", error);
}
```

***

### Session Modes

* `0`: Ephemeral — shared miner pool
* `1`: Hybrid — dedicated + ephemeral
* `2`: Dedicated — exclusively dedicated miners


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.cortensor.network/getting-started/web3-sdk-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
