# Advanced Usage

This section covers advanced features for optimizing performance, ensuring data integrity, and debugging Oracle Program executions. These topics are particularly useful when integrating SEDA FAST into production applications or troubleshooting execution issues.

## **Reducing Latency with Cached Results**

For applications requiring the absolute lowest latency, SEDA FAST supports the `returnLastResult` parameter. This optimization can significantly reduce response times by returning cached results while still executing the Oracle Program in the background.

**How It Works**

1. When `returnLastResult=true,` SEDA FAST immediately returns the last cached result for the same Oracle Program and inputs
2. The Oracle Program executes in the background to update the cache
3. Subsequent requests get the newly updated result

**Example:**

```bash
curl "<https://fast-api.seda.xyz/execute?execProgramId=...&returnLastResult=true>" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

**When to Use**

This feature is ideal for:

* **High-frequency applications** where requests happen more often than data changes
* **Data feeds** that update every few seconds but are queried many times per second
* **Gaming or real-time data environments** where latency is critical
* **Updates** that can tolerate slightly stale data

**Trade-offs**

* **First request**: If no cache exists, the request executes normally (no latency benefit)
* **Stale data**: The returned result may be a few seconds old
* **Credit consumption**: Credits are still consumed for the background execution

## **Result Encoding**

SEDA FAST returns results as hex-encoded strings by default, but you can specify alternative encodings using the encoding parameter:

```bash
# Hex encoding (default)
curl "<https://fast-api.seda.xyz/execute?execProgramId=...&encoding=hex>"

# Base64 encoding
curl "<https://fast-api.seda.xyz/execute?execProgramId=...&encoding=base64>"

# UTF-8 encoding (for human-readable text results)
curl "<https://fast-api.seda.xyz/execute?execProgramId=...&encoding=utf8>"
```

The encoding parameter only affects the result field in the response. All other fields maintain their standard format.

## **Verifying Response Signatures**

SEDA FAST responses are cryptographically signed to ensure authenticity and enable on-chain verification. The response structure follows **SEDA Core data structures** for compatibility with the broader SEDA ecosystem, allowing the same verification logic to work across different SEDA services.

### **Understanding the Result Structure**

Each response contains two important identifiers:

**Data Request ID**: A unique identifier for the Oracle Program execution request, derived from the program IDs, inputs, gas limits, and other execution parameters. This ID is deterministic, the same request parameters will always produce the same `drId`.

The Data Request ID is computed by hashing the execution parameters:

```tsx
drId = keccak256(
  keccak256(version) ||
  execProgramId ||
  keccak256(execInputs) ||
  execGasLimit ||
  tallyProgramId ||
  keccak256(tallyInputs) ||
  tallyGasLimit ||
  replicationFactor ||
  keccak256(consensusFilter) ||
  gasPrice ||
  keccak256(memo)
)
```

**Data Result ID**: A unique identifier for the execution result, derived from the `drId` along with the execution outcome (result data, exit code, gas used, timestamp, etc.). The signature is computed over this Data Result ID.

The Data Result ID is calculated by hashing the execution outcome:

```tsx
dataResultId = keccak256(
  keccak256(version) ||
  drId ||
  consensus ||
  exitCode ||
  keccak256(result) ||
  blockHeight ||
  blockTimestamp ||
  gasUsed ||
  keccak256(paybackAddress) ||
  keccak256(sedaPayload)
)
```

**Note:** For SEDA FAST, `blockHeight` is always 0 since execution happens off-chain. The blockTimestamp field represents the execution timestamp in milliseconds.

### **Signature Verification**

The signature field contains a s**ecp256k1 ECDSA signature** of the Data Result ID, signed with SEDA FAST's private key. To verify:

1. Retrieve SEDA FAST's public key from the /info endpoint
2. Derive the Data Result ID from the response fields
3. Verify the signature against the Data Result ID using the public key

**Example Verification (JavaScript):**

```tsx
import { secp256k1 } from '@noble/curves/secp256k1';

// Helper function to convert BigInt to Buffer with specific byte length
function bigIntToBuffer(value, bytes) {
  return Buffer.from(value.toString(16).padStart(bytes * 2, '0'), 'hex');
}

// Get SEDA FAST public key
const infoResponse = await fetch('<https://fast-api.seda.xyz/info>');
const { publicKey } = await infoResponse.json();

// Execute Oracle Program
const execResponse = await fetch('<https://fast-api.seda.xyz/execute?execProgramId=>...', {
  headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
});
const { data } = await execResponse.json();

// Derive Data Result ID (returns Buffer)
function deriveDataResultId(dataResult) {
  const fields = [
    keccak256(Buffer.from(dataResult.version, 'utf-8')),         // 32 bytes
		Buffer.from(dataResult.drId, 'hex'),                         // 32 bytes
		Buffer.from([dataResult.consensus ? 1 : 0]),                 // 1 byte
		Buffer.from([dataResult.exitCode]),                          // 1 byte
		keccak256(Buffer.from(dataResult.result, 'hex')),            // 32 bytes
		bigIntToBuffer(dataResult.blockHeight, 8),                   // 8 bytes
		bigIntToBuffer(dataResult.blockTimestamp, 8),                // 8 bytes
		bigIntToBuffer(dataResult.gasUsed, 16),                      // 16 bytes
		keccak256(Buffer.from(dataResult.paybackAddress, 'hex')),    // 32 bytes
		keccak256(Buffer.from(dataResult.sedaPayload, 'hex'))        // 32 bytes
  ];
  
  return Buffer.from(keccak256(Buffer.concat(fields)));
}

// Verify secp256k1 signature
const resultId = deriveDataResultId(data.dataResult);
const publicKeyBytes = Buffer.from(publicKey.replace('0x', ''), 'hex');
const signatureBytes = Buffer.from(data.signature.replace('0x', ''), 'hex');

const isValid = secp256k1.verify(signatureBytes, resultId, publicKeyBytes);

console.log('Signature valid:', isValid);
```

This verification process guarantees that the data originates from the SEDA FAST service, making it cryptographically provable and suitable for on-chain verification in smart contracts or other applications requiring authenticated data sources.

## **Debugging Failed Executions**

Oracle Program execution can fail for various reasons—from exceeding resource limits to encountering errors in external data sources. When failures occur, SEDA FAST provides several tools to help you diagnose and resolve issues quickly. Understanding exit codes, gas limits, and leveraging debug output are essential for developing robust Oracle Programs.

### **Exit Codes**

Oracle Program execution can fail for various reasons. Always check the exitCode field in the response:

* **Exit Code 0**: Successful execution
* **Non-zero Exit Code**: Oracle Program Execution failed or encountered an error

When the exit code is non-zero, the HTTP response status will be 599 (Failed Execution) rather than 200. The response still contains all execution details, including any partial results or error information.

### **Gas Limits**

Each project has configured gas limits for both execution and tally phases (visible in the `/project` endpoint). These limits follow the same gas metering model used in SEDA Core, preventing runaway computations and ensuring predictable resource usage. If your Oracle Program exceeds these limits, execution will fail.

Gas limits are set during onboarding based on your use case. If you consistently hit gas limits, contact the SEDA team to discuss your requirements, but note that higher limits may increase per-execution costs.

### **Debug Output (stdout/stderr)**

A powerful debugging tool is the Oracle Program's output. By default, SEDA FAST doesn't include "stdout" and "stderr" in responses to keep them lightweight, but you can enable them:

```bash
curl "<https://fast-api.seda.xyz/execute?execProgramId=...&includeDebugInfo=true>" \\
-H "Authorization: Bearer YOUR_API_KEY"
```

With `includeDebugInfo=true` query parameter, the response includes additional fields in both the execution and tally results:

```json
{
  "data": {
    "execute": {
      "stdout": "Processing price data for BTC-USDT...\\nFetched from 3 sources\\n",
      "stderr": "Warning: Source timeout after 2s\\n",
      "exitCode": 0
    },
    "tally": {
      "stdout": "Computed median: 98765\\n",
      "stderr": "",
      "exitCode": 0
    }
  }
}
```

These logs come directly from your Oracle Program's execution and could be essential for debugging. Many Oracle Programs use structured logging to output trace information, making it easy to identify where failures occur.

{% hint style="info" %}
During development, it is always recommended to use `includeDebugInfo=true` to see what's happening inside your Oracle Program execution.
{% endhint %}
