AI Integration
Integrate Tensora's AI subnets into your dApp for decentralized inference. This guide covers on-chain and off-chain patterns.
Integration Patterns
Off-Chain Query (Fastest)
Your backend queries miners directly via HTTP.
examples/translate.tsCopy
import axios from "axios";
async function translate(text: string, sourceLang: string, targetLang: string): Promise<string> {
// Get top miners from subnet registry
const miners = await getTopMiners(LINGUISTA_SUBNET_ID, count: 3);
for (const miner of miners) {
try {
const response = await axios.post(miner.endpoint, {
task_id: generateUUID(),
task_type: "translation",
input: { text, source_lang: sourceLang, target_lang: targetLang },
timestamp: Date.now(),
validator_signature: "0x..." // Optional
}, { timeout: 5000 });
return response.data.result.text;
} catch (error) {
console.warn(`Miner ${miner.id} failed, trying next...`);
continue;
}
}
throw new Error("All miners unavailable");
}On-Chain Request (Trustless)
Submit requests and receive results on-chain (higher latency, higher cost).
contracts/MyDApp.solCopy
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface ISubnetOracle {
function requestInference(
uint256 subnetId,
bytes calldata task,
uint256 fee
) external returns (bytes32 requestId);
function getResult(bytes32 requestId) external view returns (bytes memory result, bool ready);
}
contract MyDApp {
ISubnetOracle public oracle;
mapping(bytes32 => address) public requesters;
function requestTranslation(string calldata text) external payable {
bytes memory task = abi.encode("translation", text, "en", "es");
bytes32 requestId = oracle.requestInference{value: msg.value}(
LINGUISTA_SUBNET_ID,
task,
0.1 ether // Fee to subnet
);
requesters[requestId] = msg.sender;
}
function fulfillTranslation(bytes32 requestId) external {
(bytes memory result, bool ready) = oracle.getResult(requestId);
require(ready, "Result not ready");
string memory translation = abi.decode(result, (string));
// Use translation...
}
}Hybrid (Recommended)
Off-chain for speed, on-chain for disputes.
Copy
// Off-chain
const result = await queryMiners(task);
// Store hash on-chain for verification
await contract.storeResultHash(taskId, keccak256(result));
// If dispute, submit full result on-chain for verificationExample: DeFi Risk Scoring
Use Predictia subnet for price predictions.
contracts/RiskManager.solCopy
pragma solidity ^0.8.20;
contract RiskManager {
ISubnetOracle public oracle;
struct PriceRequest {
address asset;
uint256 horizon;
uint256 timestamp;
bool fulfilled;
int256 prediction;
}
mapping(bytes32 => PriceRequest) public requests;
function requestPriceForecast(address asset, uint256 horizonSeconds) external returns (bytes32) {
bytes memory task = abi.encode("price_prediction", asset, horizonSeconds);
bytes32 requestId = oracle.requestInference(PREDICTIA_SUBNET_ID, task, 0);
requests[requestId] = PriceRequest({
asset: asset,
horizon: horizonSeconds,
timestamp: block.timestamp,
fulfilled: false,
prediction: 0
});
return requestId;
}
function fulfillForecast(bytes32 requestId) external {
(bytes memory result, bool ready) = oracle.getResult(requestId);
require(ready, "Not ready");
int256 prediction = abi.decode(result, (int256));
requests[requestId].prediction = prediction;
requests[requestId].fulfilled = true;
}
function shouldLiquidate(address user, bytes32 forecastId) external view returns (bool) {
PriceRequest memory req = requests[forecastId];
require(req.fulfilled, "Forecast not ready");
// If predicted price drop >10%, liquidate
return req.prediction < -10;
}
}SDK Examples
JavaScript/TypeScript
examples/sdk.tsCopy
import { TensoraClient } from "@tensora/sdk";
const client = new TensoraClient({
rpcUrl: "https://rpc.tensora.org",
privateKey: process.env.PRIVATE_KEY
});
// Query Linguista subnet
const translation = await client.subnets.linguista.translate({
text: "Hello world",
sourceLang: "en",
targetLang: "es"
});
console.log(translation); // "Hola mundo"Python
examples/sdk.pyCopy
from tensora import TensoraClient
client = TensoraClient(
rpc_url="https://rpc.tensora.org",
private_key=os.getenv("PRIVATE_KEY")
)
# Query Visiona subnet
image_url = client.subnets.visiona.generate_image(
prompt="A futuristic city at sunset",
resolution="512x512"
)
print(image_url)Error Handling
Last updated