Somnia Agents / Invoking agents
Custom consensus
Advanced: Threshold consensus for agents whose validators are expected to return different values.
Advanced. Most agents work with the default Majority consensus. Read this page if each validator is expected to return a different value.
By default, Somnia Agents uses Majority consensus — the request finalizes when a threshold of validators return byte-identical results. This works well for deterministic agents (math, API lookups with exact values, etc.) but breaks down when each validator is expected to return a different value.
Threshold consensus solves this. Instead of requiring matching results, it waits for every elected validator to respond (or for the deadline to pass) and succeeds if at least threshold of them responded successfully, whether or not their results agree. FirstQuorum works the same way but finalizes as soon as threshold validators have responded successfully. Your callback receives all individual results, and you aggregate them however you like.
Consensus types
| Type | Finalization condition | responses[] in callback |
|---|---|---|
Majority (0) |
threshold successful responses return the same result |
All responses received so far; at least threshold match on the same .result value |
Threshold (1) |
Every elected validator has responded, or the deadline has passed and upkeepRequests() runs. Success if at least threshold responded successfully |
All responses (check .status to filter successful ones); values may differ |
FirstQuorum (2) |
threshold validators have responded successfully |
All responses received so far, at least threshold of them successful; values may differ |
Every mode can also fail early. Once so many validators have failed that threshold successful responses are out of reach, the request finalizes as Failed without waiting for the others or the deadline. Majority also fails as soon as no result can still reach threshold matching responses, or when every response is in without a match.
Using Threshold consensus
Call createAdvancedRequest instead of createRequest:
platform.createAdvancedRequest{value: deposit}(
agentId,
address(this),
this.handleResponse.selector,
payload,
4, // subcommitteeSize
3, // threshold: succeed if at least 3 of 4 respond
ConsensusType.Threshold, // don't require matching results
1 minutes // timeout
);
The threshold parameter controls how many successful responses the request needs. A typical choice is 3 of 4: it tolerates one validator failure while still collecting enough data points for meaningful aggregation.
subcommitteeSize can be at most 10 and can't exceed the active committee, or the request reverts with NotEnoughActiveMembers. The active committee is 8 on Global mainnet and 4 on Global testnet, Tokyo mainnet and Tokyo testnet today. Read committee().getActiveMembers() on the SomniaAgents contract before choosing a size above 4.
// Get the required deposit for a custom subcommittee size
uint256 deposit = platform.getAdvancedRequestDeposit(subcommitteeSize);
Example: price oracle (median)
Each validator fetches a price independently. Results may differ slightly. Your contract takes the median to filter outliers.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
enum ConsensusType { Majority, Threshold, FirstQuorum }
enum ResponseStatus {
None, // 0 - Default zero value (uninitialized storage)
Pending, // 1 - Awaiting responses
Success, // 2 - Consensus reached normally
Failed, // 3 - Validators reported failure
TimedOut // 4 - Request timed out
}
struct Response {
address validator;
bytes result;
ResponseStatus status;
uint256 receipt;
uint256 timestamp;
uint256 executionCost;
}
struct Request {
uint256 id;
address requester;
address callbackAddress;
bytes4 callbackSelector;
address[] subcommittee;
Response[] responses;
uint256 responseCount;
uint256 failureCount;
uint256 threshold;
uint256 createdAt;
uint256 deadline;
ResponseStatus status;
ConsensusType consensusType;
uint256 remainingBudget;
uint256 perAgentBudget;
}
interface IAgentRequester {
function createAdvancedRequest(
uint256 agentId,
address callbackAddress,
bytes4 callbackSelector,
bytes calldata payload,
uint256 subcommitteeSize,
uint256 threshold,
ConsensusType consensusType,
uint256 timeout
) external payable returns (uint256 requestId);
function getAdvancedRequestDeposit(uint256 subcommitteeSize) external view returns (uint256);
}
interface IPriceOracleAgent {
function getPrices(string[] calldata symbols, uint8 decimals)
external returns (uint256[] memory prices, uint8[] memory numSources, uint64[] memory lastUpdated);
}
contract MedianPriceOracle {
IAgentRequester public platform;
uint256 public constant PRICE_AGENT_ID = 9911223344556677889; // Price Oracle, the same on every chain
uint256 public constant SUBCOMMITTEE_SIZE = 4;
uint256 public constant COST_PER_AGENT = 0.0003 ether; // Price Oracle (see Gas Fees)
uint256 public latestPrice;
constructor(address _platform) {
platform = IAgentRequester(_platform);
}
function requestPrice(string calldata pair) external payable returns (uint256) {
string[] memory symbols = new string[](1);
symbols[0] = pair; // a Price Oracle symbol, e.g. "BTC/USDC"
bytes memory payload = abi.encodeWithSelector(
IPriceOracleAgent.getPrices.selector,
symbols,
uint8(8)
);
// Safe deposit: contract floor + per-agent execution reward.
uint256 reserve = platform.getAdvancedRequestDeposit(SUBCOMMITTEE_SIZE);
uint256 reward = COST_PER_AGENT * SUBCOMMITTEE_SIZE;
uint256 deposit = reserve + reward;
return platform.createAdvancedRequest{value: deposit}(
PRICE_AGENT_ID,
address(this),
this.handlePrice.selector,
payload,
SUBCOMMITTEE_SIZE,
3, // Succeed if at least 3 of 4 respond
ConsensusType.Threshold,
1 minutes // Timeout
);
}
function handlePrice(
uint256 requestId,
Response[] memory responses,
ResponseStatus status,
Request memory details
) external {
require(msg.sender == address(platform), "Only platform");
if (status != ResponseStatus.Success || responses.length == 0) return;
// Decode all prices from successful responses and take the median
uint256 count;
uint256[] memory prices = new uint256[](responses.length);
for (uint256 i = 0; i < responses.length; i++) {
if (responses[i].status != ResponseStatus.Success) continue;
// Decode in an external call, so one malformed result is skipped instead of reverting the callback
try this.firstPrice(responses[i].result) returns (bool ok, uint256 price) {
if (!ok) continue; // no price for this symbol
prices[count] = price;
count++;
} catch {}
}
// Resize array to actual count
assembly { mstore(prices, count) }
// A response without a price doesn't count: update only with `threshold` usable prices
if (count >= details.threshold) latestPrice = _median(prices);
}
function firstPrice(bytes calldata result) external pure returns (bool ok, uint256 price) {
(uint256[] memory p, uint8[] memory n, ) = abi.decode(result, (uint256[], uint8[], uint64[]));
if (p.length == 0 || n.length == 0 || n[0] == 0) return (false, 0);
return (true, p[0]);
}
function _median(uint256[] memory values) internal pure returns (uint256) {
// Insertion sort (fine for small arrays)
for (uint256 i = 1; i < values.length; i++) {
uint256 key = values[i];
uint256 j = i;
while (j > 0 && values[j - 1] > key) {
values[j] = values[j - 1];
j--;
}
values[j] = key;
}
return values[values.length / 2];
}
receive() external payable {}
}
Taking the median of independent price observations naturally filters outliers and manipulation. With 3 or 4 results, the median remains accurate even if one validator returns a garbage value.
Example: random oracle (XOR)
Each validator returns a random uint256. Your contract XORs all values together to produce a combined random number. This is secure as long as at least one responding validator provides a truly random value — even if the others are compromised or predictable, the XOR output remains unpredictable.
// Hypothetical: no random agent is registered today.
interface IRandomAgent {
function random() external returns (uint256);
}
contract RandomOracle {
IAgentRequester public platform;
uint256 public constant RANDOM_AGENT_ID = 67890; // Replace with actual agent ID from the explorer
uint256 public constant SUBCOMMITTEE_SIZE = 4;
uint256 public constant COST_PER_AGENT = 0.0003 ether; // adjust to match the agent type (see Gas Fees)
mapping(uint256 => address) public requesters;
event RandomGenerated(uint256 indexed requestId, uint256 value);
constructor(address _platform) {
platform = IAgentRequester(_platform);
}
function requestRandom() external payable returns (uint256 requestId) {
bytes memory payload = abi.encodeWithSelector(
IRandomAgent.random.selector
);
// Safe deposit: contract floor + per-agent execution reward.
uint256 reserve = platform.getAdvancedRequestDeposit(SUBCOMMITTEE_SIZE);
uint256 reward = COST_PER_AGENT * SUBCOMMITTEE_SIZE;
uint256 deposit = reserve + reward;
requestId = platform.createAdvancedRequest{value: deposit}(
RANDOM_AGENT_ID,
address(this),
this.handleRandom.selector,
payload,
SUBCOMMITTEE_SIZE,
3, // Succeed if at least 3 of 4 respond
ConsensusType.Threshold,
1 minutes // Timeout
);
requesters[requestId] = msg.sender;
}
function handleRandom(
uint256 requestId,
Response[] memory responses,
ResponseStatus status,
Request memory details
) external {
require(msg.sender == address(platform), "Only platform");
if (status != ResponseStatus.Success || responses.length == 0) return;
// XOR all successful values — secure if at least one provider is honest
uint256 combined = 0;
for (uint256 i = 0; i < responses.length; i++) {
if (responses[i].status == ResponseStatus.Success) {
combined ^= abi.decode(responses[i].result, (uint256));
}
}
emit RandomGenerated(requestId, combined);
}
receive() external payable {}
}
When to use which
| Use case | Consensus | Why |
|---|---|---|
| Deterministic computation (math, hashing) | Majority | All validators should return the exact same result |
| API lookups with exact values | Majority | Same endpoint, same response |
| Deterministic LLM inference | Majority | Fixed seed + temperature 0 produces identical outputs across validators |
| Price feeds / continuous values | Threshold | Slight differences expected; median filters outliers |
| Random number generation | Threshold | Values must differ; XOR combines them securely |
| Weather data / sensor readings | Threshold | Approximate values; average or median for accuracy |
| Non-deterministic LLM inference | Threshold | Natural variance in outputs; application decides how to reconcile |
Threshold tips
- A threshold of 3 out of 4 is a good default: it works on every chain and tolerates one failure while still collecting enough data for aggregation.
- A higher threshold guarantees more successful results to aggregate, but the request is more likely to fail or time out when a validator fails.
- Avoid setting
threshold = subcommitteeSize— a single validator failure would prevent finalization entirely. - For
Majority,thresholdmust be more than half ofsubcommitteeSize, or the request reverts withInvalidThreshold. - The
responses[]array in your callback contains all validator responses — check eachresponses[i].statusto filter for successful ones. getAdvancedRequestDeposit(subSize)returns the operations-reserve floor (minPerAgentDeposit × subSize). That's the minimummsg.valuethe contract will accept, and it only covers gas/callback/upkeep — the agent pot ismsg.value − floor. Deposit more than the floor to actually pay runners for execution work. See Gas fees for the full fund-flow model.- Unused funds are rebated to the requester after finalisation.
Next steps
- Invoking from Solidity: the basic request and callback pattern.
- Gas fees: understand costs and deposits.