Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(reputation): implement the staking market the spec pins, with contract tests for the invariants

nirholas42b5797e4c64
diff --git a/api/_lib/migrations/20260811140000_reputation_staking_market.sql b/api/_lib/migrations/20260811140000_reputation_staking_market.sql
new file mode 100644
index 000000000..722a9f432
--- /dev/null
+++ b/api/_lib/migrations/20260811140000_reputation_staking_market.sql
@@ -0,0 +1,82 @@
+-- Reputation Staking Market v1 (rsm.v1) — the index behind specs/REPUTATION_STAKING_MARKET.md.
+--
+-- These tables are an INDEX, not the ledger. Every row here is derivable by
+-- replaying Solana: positions from threews.stake.v1 memos paid into the market
+-- escrow, settlements from threews.unstake.v1 memos paid out of it. The stake
+-- transaction signature is the primary key precisely so the chain, not this
+-- database, defines a position's identity: a reader who distrusts the index can
+-- verify any position with a single getTransaction() call.
+--
+-- Apply: npm run db:migrate (read `npm run db:status` first — it applies every
+-- pending file, not just this one). Idempotent.
+
+begin;
+
+-- ── reputation_stake_positions ─────────────────────────────────────────────
+-- One row per stake transaction. principal_lamports is the ESCROW's balance
+-- delta in that transaction, never the staker's debit: a staker who also paid
+-- fees or funded rent in the same tx staked only what the escrow received.
+create table if not exists reputation_stake_positions (
+ signature text primary key, -- stake tx signature = position id
+ network text not null, -- 'devnet' | 'mainnet'
+ agent_asset text not null, -- subject agent pubkey
+ staker text not null, -- fee payer of the stake tx
+ principal_lamports numeric(30,0) not null,
+ score smallint, -- staker's 1-5 conviction rating
+ opened_at timestamptz not null, -- stake tx block_time
+ status text not null default 'open', -- 'open' | 'settling' | 'closed'
+ closed_at timestamptz,
+ settle_signature text,
+ earnings_lamports numeric(30,0) not null default 0,
+ indexed_at timestamptz not null default now(),
+ constraint reputation_stake_positions_status_chk
+ check (status in ('open', 'settling', 'closed')),
+ constraint reputation_stake_positions_principal_chk
+ check (principal_lamports >= 0),
+ -- A closed position must carry the settlement that closed it. Without this a
+ -- crash between the payout and the status write would leave a row that reads
+ -- as settled but names no transaction to verify it against.
+ constraint reputation_stake_positions_closed_chk
+ check (status <> 'closed' or (closed_at is not null and settle_signature is not null))
+);
+
+-- The market listing ranks agents by open conviction: this is its covering index.
+create index if not exists reputation_stake_positions_agent_open_idx
+ on reputation_stake_positions (network, agent_asset)
+ where status <> 'closed';
+
+-- "My positions" for a wallet, newest first.
+create index if not exists reputation_stake_positions_staker_idx
+ on reputation_stake_positions (staker, network, opened_at desc);
+
+-- Epoch accrual walks every position that was open during a window, including
+-- ones already closed inside it.
+create index if not exists reputation_stake_positions_window_idx
+ on reputation_stake_positions (network, opened_at, closed_at);
+
+-- ── reputation_stake_settlements ───────────────────────────────────────────
+-- One row per payout. Keyed by the stake signature, so a replayed withdrawal
+-- can never pay twice: the insert collides instead.
+create table if not exists reputation_stake_settlements (
+ stake_signature text primary key
+ references reputation_stake_positions(signature) on delete cascade,
+ network text not null,
+ staker text not null,
+ principal_lamports numeric(30,0) not null,
+ earnings_lamports numeric(30,0) not null,
+ -- true when the escrow's reward surplus could not cover the accrued earnings
+ -- and the payout was clamped to what was actually there (spec §2). Principal
+ -- is never clamped.
+ clamped boolean not null default false,
+ -- Per-epoch derivation: [{ epoch, lamports, posWeight, epochFraction }, ...].
+ -- Kept so a staker can audit the payout against the pure engine without
+ -- re-reading the whole chain.
+ breakdown jsonb not null default '[]'::jsonb,
+ settle_signature text not null,
+ settled_at timestamptz not null default now()
+);
+
+create index if not exists reputation_stake_settlements_staker_idx
+ on reputation_stake_settlements (staker, settled_at desc);
+
+commit;
diff --git a/contracts/test/ReputationRegistry.t.sol b/contracts/test/ReputationRegistry.t.sol
index a2bd07bfe..fec688f15 100644
--- a/contracts/test/ReputationRegistry.t.sol
+++ b/contracts/test/ReputationRegistry.t.sol
@@ -5,12 +5,68 @@ import {Test} from "forge-std/Test.sol";
import {IdentityRegistry} from "../src/IdentityRegistry.sol";
import {ReputationRegistry} from "../src/ReputationRegistry.sol";
+/// @notice Staker contract with no `receive`, so its stake refund fails. Proves
+/// REP-10: a failed refund reverts the whole call instead of zeroing
+/// the recorded balance and losing the ETH.
+contract EthRejectingStaker {
+ ReputationRegistry public immutable rep;
+
+ constructor(ReputationRegistry _rep) {
+ rep = _rep;
+ }
+
+ function stake(uint256 agentId, uint8 score) external payable {
+ rep.stakeReputation{value: msg.value}(agentId, score, "from-contract");
+ }
+
+ function pull(uint256 agentId) external {
+ rep.withdrawStake(agentId);
+ }
+}
+
+/// @notice Staker that re-enters `withdrawStake` from its refund callback.
+/// Proves REP-10's guard rather than assuming checks-effects alone.
+contract ReentrantStaker {
+ ReputationRegistry public immutable rep;
+ uint256 private _agentId;
+ bool private _armed;
+
+ bool public reentryAttempted;
+ bool public reentrySucceeded;
+
+ constructor(ReputationRegistry _rep) {
+ rep = _rep;
+ }
+
+ function stake(uint256 agentId, uint8 score) external payable {
+ _agentId = agentId;
+ rep.stakeReputation{value: msg.value}(agentId, score, "reentrant");
+ }
+
+ function pull() external {
+ _armed = true;
+ rep.withdrawStake(_agentId);
+ }
+
+ receive() external payable {
+ if (_armed) {
+ _armed = false;
+ reentryAttempted = true;
+ (bool ok,) = address(rep).call(abi.encodeWithSelector(ReputationRegistry.withdrawStake.selector, _agentId));
+ reentrySucceeded = ok;
+ }
+ }
+}
+
+/// @dev Invariants under proof: REP-1 .. REP-10 of
+/// `specs/ECONOMY_CONTRACT_INVARIANTS.md`.
contract ReputationRegistryTest is Test {
IdentityRegistry identity;
ReputationRegistry rep;
address alice = address(0xA11CE);
address bob = address(0xB0B);
address carol = address(0xCA701);
+ address dave = address(0xDA7E);
function setUp() public {
identity = new IdentityRegistry();
@@ -18,6 +74,10 @@ contract ReputationRegistryTest is Test {
vm.prank(alice);
identity.register("ipfs://alice");
+
+ vm.deal(bob, 10 ether);
+ vm.deal(carol, 10 ether);
+ vm.deal(dave, 10 ether);
}
function testSubmitAndQuery() public {
@@ -77,4 +137,284 @@ contract ReputationRegistryTest is Test {
assertEq(range[0].score, int8(30));
assertEq(range[1].score, int8(40));
}
+
+ // ── REP-2: the other end of the submitFeedback range ─────────────────────
+
+ function testScoreBelowMinimumReverts() public {
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.ScoreOutOfRange.selector);
+ rep.submitFeedback(1, -101, "");
+ }
+
+ function testScoresAtExactBoundsAreAccepted() public {
+ vm.prank(bob);
+ rep.submitFeedback(1, 100, "max");
+ vm.prank(carol);
+ rep.submitFeedback(1, -100, "min");
+
+ (int256 avgX100, uint256 count) = rep.getReputation(1);
+ assertEq(count, 2);
+ assertEq(avgX100, 0);
+ }
+
+ // ── REP-5: the aggregate always matches the stored feedback ──────────────
+
+ function testUnreviewedAgentReadsZero() public view {
+ (int256 avgX100, uint256 count) = rep.getReputation(1);
+ assertEq(avgX100, 0);
+ assertEq(count, 0);
+ assertEq(rep.getFeedbackCount(1), 0);
+ }
+
+ function testAggregateMatchesStoredFeedback() public {
+ vm.prank(bob);
+ rep.submitFeedback(1, 90, "b");
+ vm.prank(carol);
+ rep.submitFeedback(1, -30, "c");
+ vm.prank(dave);
+ rep.stakeReputation{value: 0.01 ether}(1, 5, "d");
+
+ uint256 count = rep.getFeedbackCount(1);
+ int256 sum;
+ for (uint256 i = 0; i < count; i++) {
+ sum += int256(rep.getFeedback(1, i).score);
+ }
+
+ (int256 avgX100, uint256 reportedCount) = rep.getReputation(1);
+ assertEq(reportedCount, count, "REP-5: count must equal stored entries");
+ assertEq(avgX100, (sum * 100) / int256(count), "REP-5: average must derive from the stored scores");
+ }
+
+ function testFeedbackRangeClampsAndPaginates() public {
+ vm.prank(bob);
+ rep.submitFeedback(1, 10, "b");
+ vm.prank(carol);
+ rep.submitFeedback(1, 20, "c");
+
+ ReputationRegistry.Feedback[] memory page = rep.getFeedbackRange(1, 1, 5);
+ assertEq(page.length, 1);
+ assertEq(page[0].score, int8(20));
+
+ assertEq(rep.getFeedbackRange(1, 5, 5).length, 0, "REP-5: out-of-range offset returns empty, not a revert");
+ assertEq(rep.getFeedbackRange(1, 0, 0).length, 0);
+ }
+
+ function testFeedbackRecordsSenderAndTimestamp() public {
+ vm.warp(1_800_000_000);
+ vm.prank(bob);
+ rep.submitFeedback(1, 55, "ipfs://detail");
+
+ ReputationRegistry.Feedback memory f = rep.getFeedback(1, 0);
+ assertEq(f.from, bob);
+ assertEq(f.score, int8(55));
+ assertEq(f.timestamp, uint64(1_800_000_000));
+ assertEq(f.uri, "ipfs://detail");
+ }
+
+ // ── REP-1: one review per reviewer, across BOTH entry points ─────────────
+
+ function testStakeAfterFeedbackByTheSameReviewerReverts() public {
+ vm.prank(bob);
+ rep.submitFeedback(1, 50, "");
+
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.AlreadyReviewed.selector);
+ rep.stakeReputation{value: 0.01 ether}(1, 5, "");
+ }
+
+ function testFeedbackAfterStakeByTheSameReviewerReverts() public {
+ vm.prank(bob);
+ rep.stakeReputation{value: 0.01 ether}(1, 4, "");
+
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.AlreadyReviewed.selector);
+ rep.submitFeedback(1, 50, "");
+ }
+
+ function testTheSameReviewerCanReviewADifferentAgent() public {
+ vm.prank(dave);
+ identity.register("ipfs://dave");
+
+ vm.prank(bob);
+ rep.submitFeedback(1, 50, "");
+ vm.prank(bob);
+ rep.submitFeedback(2, 60, "");
+
+ assertEq(rep.getFeedbackCount(1), 1);
+ assertEq(rep.getFeedbackCount(2), 1);
+ }
+
+ // ── REP-2 / REP-3 / REP-4 / REP-9: stake entry-point guards ──────────────
+
+ function testStakeScoreZeroReverts() public {
+ vm.prank(bob);
+ vm.expectRevert(bytes("score out of range"));
+ rep.stakeReputation{value: 0.01 ether}(1, 0, "");
+ }
+
+ function testStakeScoreAboveFiveReverts() public {
+ vm.prank(bob);
+ vm.expectRevert(bytes("score out of range"));
+ rep.stakeReputation{value: 0.01 ether}(1, 6, "");
+ }
+
+ function testStakeBelowMinimumReverts() public {
+ vm.prank(bob);
+ vm.expectRevert(bytes("min stake 0.001 ETH"));
+ rep.stakeReputation{value: 0.0009 ether}(1, 5, "");
+
+ assertEq(rep.getTotalStake(1), 0, "REP-9: a rejected stake records nothing");
+ assertEq(rep.getFeedbackCount(1), 0);
+ }
+
+ function testStakeAtExactMinimumSucceeds() public {
+ vm.prank(bob);
+ rep.stakeReputation{value: 0.001 ether}(1, 3, "");
+ assertEq(rep.getStake(1, bob), 0.001 ether);
+ }
+
+ function testStakeSelfReviewForbidden() public {
+ vm.prank(alice);
+ vm.expectRevert(ReputationRegistry.SelfReviewForbidden.selector);
+ rep.stakeReputation{value: 0.01 ether}(1, 5, "");
+ }
+
+ function testStakeUnknownAgentReverts() public {
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.UnknownAgent.selector);
+ rep.stakeReputation{value: 0.01 ether}(999, 5, "");
+ }
+
+ function testStakeRecordsFeedbackAndEscrow() public {
+ vm.prank(bob);
+ rep.stakeReputation{value: 0.5 ether}(1, 5, "great agent");
+
+ assertEq(rep.getStake(1, bob), 0.5 ether);
+ assertEq(rep.getTotalStake(1), 0.5 ether);
+ assertEq(address(rep).balance, 0.5 ether);
+
+ ReputationRegistry.Feedback memory f = rep.getFeedback(1, 0);
+ assertEq(f.from, bob);
+ assertEq(f.score, int8(5));
+ assertEq(f.uri, "great agent");
+ }
+
+ // ── REP-6: stake conservation ────────────────────────────────────────────
+
+ function testTotalStakeEqualsTheSumOfIndividualStakes() public {
+ vm.prank(bob);
+ rep.stakeReputation{value: 0.2 ether}(1, 5, "");
+ vm.prank(carol);
+ rep.stakeReputation{value: 0.3 ether}(1, 4, "");
+
+ assertEq(
+ rep.getTotalStake(1),
+ rep.getStake(1, bob) + rep.getStake(1, carol),
+ "REP-6: aggregate stake must equal the sum of the parts"
+ );
+ assertGe(address(rep).balance, rep.getTotalStake(1), "REP-6: held ETH must cover every stake");
+ }
+
+ // ── REP-7: a staker reclaims only their own stake, once ──────────────────
+
+ function testWithdrawStakeReturnsExactlyTheStakersOwnDeposit() public {
+ vm.prank(bob);
+ rep.stakeReputation{value: 0.2 ether}(1, 5, "");
+ vm.prank(carol);
+ rep.stakeReputation{value: 0.3 ether}(1, 4, "");
+
+ uint256 before = bob.balance;
+ vm.prank(bob);
+ rep.withdrawStake(1);
+
+ assertEq(bob.balance - before, 0.2 ether);
+ assertEq(rep.getStake(1, bob), 0);
+ assertEq(rep.getStake(1, carol), 0.3 ether, "REP-7: one withdrawal must not touch another staker");
+ assertEq(rep.getTotalStake(1), 0.3 ether);
+ }
+
+ function testWithdrawStakeTwiceReverts() public {
+ vm.prank(bob);
+ rep.stakeReputation{value: 0.2 ether}(1, 5, "");
+
+ vm.prank(bob);
+ rep.withdrawStake(1);
+
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.NoStakeToWithdraw.selector);
+ rep.withdrawStake(1);
+ }
+
+ function testWithdrawWithoutStakingReverts() public {
+ vm.prank(carol);
+ vm.expectRevert(ReputationRegistry.NoStakeToWithdraw.selector);
+ rep.withdrawStake(1);
+ }
+
+ function testWithdrawIsPerAgent() public {
+ vm.prank(dave);
+ identity.register("ipfs://dave");
+
+ vm.prank(bob);
+ rep.stakeReputation{value: 0.2 ether}(1, 5, "");
+
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.NoStakeToWithdraw.selector);
+ rep.withdrawStake(2);
+
+ assertEq(rep.getStake(1, bob), 0.2 ether);
+ }
+
+ // ── REP-8: reputation is not rentable ────────────────────────────────────
+
+ function testWithdrawingStakeLeavesTheReviewStanding() public {
+ vm.prank(bob);
+ rep.stakeReputation{value: 0.2 ether}(1, 5, "still counts");
+
+ (int256 avgBefore, uint256 countBefore) = rep.getReputation(1);
+
+ vm.prank(bob);
+ rep.withdrawStake(1);
+
+ (int256 avgAfter, uint256 countAfter) = rep.getReputation(1);
+ assertEq(avgAfter, avgBefore, "REP-8: withdrawing stake must not move the score");
+ assertEq(countAfter, countBefore);
+ assertEq(rep.getFeedbackCount(1), 1);
+ assertTrue(rep.hasReviewed(1, bob), "REP-8: the reviewer slot stays consumed");
+
+ vm.prank(bob);
+ vm.expectRevert(ReputationRegistry.AlreadyReviewed.selector);
+ rep.stakeReputation{value: 0.2 ether}(1, 1, "re-review");
+ }
+
+ // ── REP-10: refund failure and reentrancy ────────────────────────────────
+
+ function testRefundFailureRevertsAndKeepsTheStake() public {
+ EthRejectingStaker staker = new EthRejectingStaker(rep);
+ vm.deal(address(staker), 1 ether);
+ staker.stake{value: 0.2 ether}(1, 5);
+
+ vm.expectRevert(ReputationRegistry.RefundFailed.selector);
+ staker.pull(1);
+
+ assertEq(rep.getStake(1, address(staker)), 0.2 ether, "REP-10: a failed refund must not zero the balance");
+ assertEq(rep.getTotalStake(1), 0.2 ether);
+ }
+
+ function testReentrantWithdrawIsBlocked() public {
+ ReentrantStaker attacker = new ReentrantStaker(rep);
+ vm.deal(address(attacker), 1 ether);
+ attacker.stake{value: 0.2 ether}(1, 5);
+
+ vm.prank(carol);
+ rep.stakeReputation{value: 0.5 ether}(1, 4, "");
+
+ attacker.pull();
+
+ assertTrue(attacker.reentryAttempted(), "the attack must actually have been attempted");
+ assertFalse(attacker.reentrySucceeded(), "REP-10: nonReentrant must reject the second entry");
+ assertEq(address(attacker).balance, 1 ether - 0.2 ether + 0.2 ether);
+ assertEq(rep.getStake(1, address(attacker)), 0);
+ assertEq(rep.getStake(1, carol), 0.5 ether, "REP-10: the other staker's escrow is untouched");
+ }
}
diff --git a/contracts/test/ThreeWSFactory.t.sol b/contracts/test/ThreeWSFactory.t.sol
new file mode 100644
index 000000000..913a647e2
--- /dev/null
+++ b/contracts/test/ThreeWSFactory.t.sol
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+import {Test} from "forge-std/Test.sol";
+import {ThreeWSFactory} from "../ThreeWSFactory.sol";
+
+/// @notice Trivial payload with a constructor argument, so the tests exercise
+/// init code whose hash actually depends on its arguments.
+contract Payload {
+ uint256 public immutable value;
+
+ constructor(uint256 _value) {
+ value = _value;
+ }
+}
+
+/// @notice Payload whose constructor always reverts, proving TWF-1 surfaces a
+/// failed CREATE2 rather than reporting a phantom deployment.
+contract RevertingPayload {
+ constructor() {
+ revert("constructor failed");
+ }
+}
+
+/// @dev Invariants under proof: TWF-1 .. TWF-4 of
+/// `specs/ECONOMY_CONTRACT_INVARIANTS.md`. This factory is LIVE at
+/// `0x00000000D49195AE81759cd247cFeDD9D0B479df` on BSC, Base, and
+/// Arbitrum One, and it is what produced the deployed ThreeWSPayments
+/// vanity addresses, so `predict` agreeing with `deploy` is a
+/// production-critical property, not a convenience.
+contract ThreeWSFactoryTest is Test {
+ ThreeWSFactory internal factory;
+
+ event Deployed(address indexed addr, bytes32 indexed salt);
+
+ function setUp() public {
+ factory = new ThreeWSFactory();
+ }
+
+ function _initCode(uint256 value) internal pure returns (bytes memory) {
+ return abi.encodePacked(type(Payload).creationCode, abi.encode(value));
+ }
+
+ // ── TWF-2: predict is the deployment ─────────────────────────────────────
+
+ function testPredictMatchesDeploy() public {
+ bytes32 salt = keccak256("three-ws-salt");
+ bytes memory initCode = _initCode(42);
+
+ address predicted = factory.predict(salt, keccak256(initCode));
+ address deployed = factory.deploy(salt, initCode);
+
+ assertEq(deployed, predicted, "TWF-2: predicted address must be the deployed address");
+ assertEq(Payload(deployed).value(), 42);
+ }
+
+ function testPredictIsSaltDependent() public view {
+ bytes32 hash = keccak256(_initCode(1));
+ assertTrue(
+ factory.predict(keccak256("salt-a"), hash) != factory.predict(keccak256("salt-b"), hash),
+ "TWF-2: a different salt must yield a different address"
+ );
+ }
+
+ function testPredictIsInitCodeDependent() public view {
+ bytes32 salt = keccak256("same-salt");
+ assertTrue(
+ factory.predict(salt, keccak256(_initCode(1))) != factory.predict(salt, keccak256(_initCode(2))),
+ "TWF-2: different constructor args must yield a different address"
+ );
+ }
+
+ function testDeployEmitsAddressAndSalt() public {
+ bytes32 salt = keccak256("emit-salt");
+ bytes memory initCode = _initCode(7);
+ address predicted = factory.predict(salt, keccak256(initCode));
+
+ vm.expectEmit(true, true, true, true);
+ emit Deployed(predicted, salt);
+ factory.deploy(salt, initCode);
+ }
+
+ function testPredictIsPerFactoryInstance() public {
+ ThreeWSFactory other = new ThreeWSFactory();
+ bytes32 salt = keccak256("cross-factory");
+ bytes32 hash = keccak256(_initCode(3));
+
+ assertTrue(
+ factory.predict(salt, hash) != other.predict(salt, hash),
+ "TWF-2: address is bound to the deploying factory"
+ );
+ }
+
+ // ── TWF-1 / TWF-3: failures never report success ─────────────────────────
+
+ function testRedeployingTheSameSaltReverts() public {
+ bytes32 salt = keccak256("collision");
+ bytes memory initCode = _initCode(1);
+
+ factory.deploy(salt, initCode);
+
+ vm.expectRevert(bytes("deploy failed"));
+ factory.deploy(salt, initCode);
+ }
+
+ function testSameSaltDifferentInitCodeStillDeploys() public {
+ bytes32 salt = keccak256("shared-salt");
+ address a = factory.deploy(salt, _initCode(1));
+ address b = factory.deploy(salt, _initCode(2));
+ assertTrue(a != b, "TWF-3: only the (salt, initCode) pair collides");
+ }
+
+ function testRevertingConstructorReverts() public {
+ vm.expectRevert(bytes("deploy failed"));
+ factory.deploy(keccak256("bad-payload"), type(RevertingPayload).creationCode);
+ }
+
+ function testEmptyInitCodeReverts() public {
+ // CREATE2 with empty init code deploys a zero-length account, which
+ // CREATE2 still reports as a real address; a second attempt collides.
+ bytes32 salt = keccak256("empty");
+ address first = factory.deploy(salt, hex"");
+ assertTrue(first != address(0));
+
+ vm.expectRevert(bytes("deploy failed"));
+ factory.deploy(salt, hex"");
+ }
+
+ // ── TWF-4: the factory is stateless and holds nothing ────────────────────
+
+ function testFactoryNeverHoldsValue() public {
+ factory.deploy(keccak256("value-check"), _initCode(9));
+ assertEq(address(factory).balance, 0, "TWF-4: factory forwards no value and holds none");
+ }
+
+ function testFactoryRejectsNativeTransfers() public {
+ address sender = address(0xCAFE);
+ vm.deal(sender, 1 ether);
+ vm.prank(sender);
+ (bool ok,) = address(factory).call{value: 1 ether}("");
+ assertFalse(ok, "TWF-4: factory has no payable path");
+ }
+
+ function testDeployIsPermissionless() public {
+ address anyone = address(0xB0B);
+ bytes32 salt = keccak256("anyone");
+ bytes memory initCode = _initCode(5);
+ address predicted = factory.predict(salt, keccak256(initCode));
+
+ vm.prank(anyone);
+ address deployed = factory.deploy(salt, initCode);
+
+ assertEq(deployed, predicted, "TWF-4: no privileged role gates deploy");
+ }
+
+ function testFuzzPredictMatchesDeploy(bytes32 salt, uint256 value) public {
+ bytes memory initCode = _initCode(value);
+ address predicted = factory.predict(salt, keccak256(initCode));
+ assertEq(factory.deploy(salt, initCode), predicted);
+ }
+}
diff --git a/contracts/test/ThreeWSPayments.t.sol b/contracts/test/ThreeWSPayments.t.sol
new file mode 100644
index 000000000..728d5ec59
--- /dev/null
+++ b/contracts/test/ThreeWSPayments.t.sol
@@ -0,0 +1,344 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+import {Test} from "forge-std/Test.sol";
+import {ThreeWSPayments} from "../ThreeWSPayments.sol";
+
+/// @notice Standard, well-behaved ERC-20 (returns true, reverts on shortfall).
+contract GoodToken {
+ mapping(address => uint256) public balanceOf;
+ mapping(address => mapping(address => uint256)) public allowance;
+
+ function mint(address to, uint256 amount) external {
+ balanceOf[to] += amount;
+ }
+
+ function approve(address spender, uint256 amount) external returns (bool) {
+ allowance[msg.sender][spender] = amount;
+ return true;
+ }
+
+ function transfer(address to, uint256 amount) external returns (bool) {
+ balanceOf[msg.sender] -= amount;
+ balanceOf[to] += amount;
+ return true;
+ }
+
+ function transferFrom(address from, address to, uint256 amount) external returns (bool) {
+ uint256 a = allowance[from][msg.sender];
+ if (a != type(uint256).max) allowance[from][msg.sender] = a - amount;
+ balanceOf[from] -= amount;
+ balanceOf[to] += amount;
+ return true;
+ }
+}
+
+/// @notice The dangerous shape: moves nothing and returns `false` instead of
+/// reverting. USDT-era tokens and several bridged assets behave this
+/// way, which is exactly what TWP-1 exists to defend against.
+contract SilentFailToken {
+ mapping(address => uint256) public balanceOf;
+
+ function mint(address to, uint256 amount) external {
+ balanceOf[to] += amount;
+ }
+
+ function approve(address, uint256) external pure returns (bool) {
+ return true;
+ }
+
+ function transfer(address, uint256) external pure returns (bool) {
+ return false;
+ }
+
+ function transferFrom(address, address, uint256) external pure returns (bool) {
+ return false;
+ }
+}
+
+/// @notice Returns no data at all (pre-ERC-20-finalization tokens). A transfer
+/// that does not revert and returns nothing must count as success.
+contract NoReturnDataToken {
+ mapping(address => uint256) public balanceOf;
+
+ function mint(address to, uint256 amount) external {
+ balanceOf[to] += amount;
+ }
+
+ function approve(address, uint256) external {}
+
+ function transfer(address to, uint256 amount) external {
+ balanceOf[msg.sender] -= amount;
+ balanceOf[to] += amount;
+ }
+
+ function transferFrom(address from, address to, uint256 amount) external {
+ balanceOf[from] -= amount;
+ balanceOf[to] += amount;
+ }
+}
+
+/// @notice Reverts outright on transfer.
+contract RevertingToken {
+ mapping(address => uint256) public balanceOf;
+
+ function mint(address to, uint256 amount) external {
+ balanceOf[to] += amount;
+ }
+
+ function approve(address, uint256) external pure returns (bool) {
+ return true;
+ }
+
+ function transfer(address, uint256) external pure returns (bool) {
+ revert("nope");
+ }
+
+ function transferFrom(address, address, uint256) external pure returns (bool) {
+ revert("nope");
+ }
+}
+
+/// @dev Invariants under proof: TWP-1 .. TWP-6 of
+/// `specs/ECONOMY_CONTRACT_INVARIANTS.md`. This contract is LIVE on BSC,
+/// Base, and Arbitrum One and custodies real USDC, so every branch of it
+/// is exercised here, including the non-compliant-token paths that the
+/// settlement server's trust in the `Payment` event depends on.
+contract ThreeWSPaymentsTest is Test {
+ ThreeWSPayments internal pay;
+ GoodToken internal usdc;
+
+ address internal owner = address(0xA11CE);
+ address internal agent = address(0xCAFE);
+ address internal stranger = address(0xB0B);
+
+ event Payment(address indexed payer, uint256 amount, bytes32 indexed ref);
+ event PriceUpdated(uint256 oldPrice, uint256 newPrice);
+
+ function setUp() public {
+ usdc = new GoodToken();
+ pay = new ThreeWSPayments(owner, address(usdc));
+ usdc.mint(agent, 1_000_000);
+ }
+
+ // ── TWP-5: constructor rejects zero owner / zero token ───────────────────
+
+ function testConstructorRejectsZeroOwner() public {
+ vm.expectRevert(ThreeWSPayments.ZeroAddress.selector);
+ new ThreeWSPayments(address(0), address(usdc));
+ }
+
+ function testConstructorRejectsZeroToken() public {
+ vm.expectRevert(ThreeWSPayments.ZeroAddress.selector);
+ new ThreeWSPayments(owner, address(0));
+ }
+
+ function testConstructorStoresOwnerAndToken() public view {
+ assertEq(pay.owner(), owner);
+ assertEq(address(pay.USDC()), address(usdc));
+ assertEq(pay.pricePerCall(), 1_000);
+ }
+
+ // ── TWP-1 / TWP-2: pay() moves exactly the price, and only emits on success ─
+
+ function testPayTransfersExactPriceAndEmits() public {
+ bytes32 ref = keccak256("jsonrpc-body");
+
+ vm.prank(agent);
+ usdc.approve(address(pay), type(uint256).max);
+
+ vm.expectEmit(true, true, true, true);
+ emit Payment(agent, 1_000, ref);
+
+ vm.prank(agent);
+ pay.pay(ref);
+
+ assertEq(usdc.balanceOf(address(pay)), 1_000);
+ assertEq(usdc.balanceOf(agent), 999_000);
+ }
+
+ function testPayUsesCurrentPriceNotCallerChoice() public {
+ vm.prank(owner);
+ pay.setPrice(5_000);
+
+ vm.startPrank(agent);
+ usdc.approve(address(pay), type(uint256).max);
+ pay.pay(keccak256("a"));
+ vm.stopPrank();
+
+ assertEq(usdc.balanceOf(address(pay)), 5_000);
+ }
+
+ function testPayRevertsWithoutAllowance() public {
+ vm.prank(agent);
+ vm.expectRevert();
+ pay.pay(keccak256("no-approval"));
+
+ assertEq(usdc.balanceOf(address(pay)), 0);
+ }
+
+ /// TWP-1 negative case: a token that returns false without reverting must
+ /// NOT produce a receipt. If this regressed, the settlement server would
+ /// credit a tool call that was never paid for.
+ function testPayRevertsOnSilentlyFailingToken() public {
+ SilentFailToken bad = new SilentFailToken();
+ ThreeWSPayments p = new ThreeWSPayments(owner, address(bad));
+ bad.mint(agent, 1_000_000);
+
+ vm.prank(agent);
+ vm.expectRevert(ThreeWSPayments.TransferFailed.selector);
+ p.pay(keccak256("silent-fail"));
+ }
+
+ function testPayRevertsOnRevertingToken() public {
+ RevertingToken bad = new RevertingToken();
+ ThreeWSPayments p = new ThreeWSPayments(owner, address(bad));
+
+ vm.prank(agent);
+ vm.expectRevert(ThreeWSPayments.TransferFailed.selector);
+ p.pay(keccak256("hard-revert"));
+ }
+
+ /// A token that returns no data at all is compliant-enough: the payment
+ /// must go through, or three.ws could not accept several bridged USDCs.
+ function testPayAcceptsNoReturnDataToken() public {
+ NoReturnDataToken quiet = new NoReturnDataToken();
+ ThreeWSPayments p = new ThreeWSPayments(owner, address(quiet));
+ quiet.mint(agent, 10_000);
+
+ vm.prank(agent);
+ p.pay(keccak256("no-return-data"));
+
+ assertEq(quiet.balanceOf(address(p)), 1_000);
+ }
+
+ function testDistinctRefsBothSettle() public {
+ vm.startPrank(agent);
+ usdc.approve(address(pay), type(uint256).max);
+ pay.pay(keccak256("call-1"));
+ pay.pay(keccak256("call-2"));
+ vm.stopPrank();
+
+ assertEq(usdc.balanceOf(address(pay)), 2_000);
+ }
+
+ // ── TWP-3: owner-only mutators ───────────────────────────────────────────
+
+ function testSetPriceOnlyOwner() public {
+ vm.prank(stranger);
+ vm.expectRevert(ThreeWSPayments.NotOwner.selector);
+ pay.setPrice(1);
+
+ assertEq(pay.pricePerCall(), 1_000);
+ }
+
+ function testSetPriceEmitsOldAndNew() public {
+ vm.expectEmit(true, true, true, true);
+ emit PriceUpdated(1_000, 2_500);
+ vm.prank(owner);
+ pay.setPrice(2_500);
+ assertEq(pay.pricePerCall(), 2_500);
+ }
+
+ function testWithdrawOnlyOwner() public {
+ vm.prank(stranger);
+ vm.expectRevert(ThreeWSPayments.NotOwner.selector);
+ pay.withdraw();
+ }
+
+ function testTransferOwnershipOnlyOwner() public {
+ vm.prank(stranger);
+ vm.expectRevert(ThreeWSPayments.NotOwner.selector);
+ pay.transferOwnership(stranger);
+
+ assertEq(pay.owner(), owner);
+ }
+
+ function testTransferOwnershipRejectsZero() public {
+ vm.prank(owner);
+ vm.expectRevert(ThreeWSPayments.ZeroAddress.selector);
+ pay.transferOwnership(address(0));
+
+ assertEq(pay.owner(), owner);
+ }
+
+ function testTransferOwnershipMovesEveryRight() public {
+ vm.prank(owner);
+ pay.transferOwnership(stranger);
+ assertEq(pay.owner(), stranger);
+
+ // Old owner is fully demoted.
+ vm.prank(owner);
+ vm.expectRevert(ThreeWSPayments.NotOwner.selector);
+ pay.setPrice(7);
+
+ vm.prank(stranger);
+ pay.setPrice(7);
+ assertEq(pay.pricePerCall(), 7);
+ }
+
+ // ── TWP-4: withdraw drains to the current owner ──────────────────────────
+
+ function testWithdrawSendsFullBalanceToOwner() public {
+ vm.startPrank(agent);
+ usdc.approve(address(pay), type(uint256).max);
+ pay.pay(keccak256("a"));
+ pay.pay(keccak256("b"));
+ vm.stopPrank();
+
+ vm.prank(owner);
+ pay.withdraw();
+
+ assertEq(usdc.balanceOf(address(pay)), 0);
+ assertEq(usdc.balanceOf(owner), 2_000);
+ }
+
+ function testWithdrawGoesToTheNewOwnerAfterTransfer() public {
+ vm.startPrank(agent);
+ usdc.approve(address(pay), type(uint256).max);
+ pay.pay(keccak256("a"));
+ vm.stopPrank();
+
+ vm.prank(owner);
+ pay.transferOwnership(stranger);
+
+ vm.prank(stranger);
+ pay.withdraw();
+
+ assertEq(usdc.balanceOf(stranger), 1_000);
+ assertEq(usdc.balanceOf(owner), 0);
+ }
+
+ function testWithdrawRevertsOnFailingToken() public {
+ SilentFailToken bad = new SilentFailToken();
+ ThreeWSPayments p = new ThreeWSPayments(owner, address(bad));
+ bad.mint(address(p), 5_000);
+
+ vm.prank(owner);
+ vm.expectRevert(ThreeWSPayments.TransferFailed.selector);
+ p.withdraw();
+
+ assertEq(bad.balanceOf(address(p)), 5_000);
+ }
+
+ function testWithdrawOfEmptyBalanceIsANoop() public {
+ vm.prank(owner);
+ pay.withdraw();
+ assertEq(usdc.balanceOf(owner), 0);
+ }
+
+ // ── TWP-6: no native-currency path ───────────────────────────────────────
+
+ function testContractRejectsNativeTransfers() public {
+ vm.deal(agent, 1 ether);
+ vm.prank(agent);
+ (bool ok,) = address(pay).call{value: 1 ether}("");
+ assertFalse(ok, "TWP-6: contract must not accept native currency");
+ assertEq(address(pay).balance, 0);
+ }
+
+ function testUnknownSelectorReverts() public {
+ (bool ok,) = address(pay).call(abi.encodeWithSignature("doesNotExist()"));
+ assertFalse(ok, "TWP-6: no fallback path");
+ }
+}
diff --git a/src/shared/reputation-staking.js b/src/shared/reputation-staking.js
new file mode 100644
index 000000000..dba3639ad
--- /dev/null
+++ b/src/shared/reputation-staking.js
@@ -0,0 +1,361 @@
+// Reputation Staking Market — the pure earnings engine.
+//
+// Stakers back an agent with escrowed lamports; the agent's ATTESTED ACTION
+// HISTORY decides what that conviction earns. This module is the only place the
+// weights, the epoch math, and the distribution rule exist. It is the executable
+// form of specs/REPUTATION_STAKING_MARKET.md §5.
+//
+// Intentionally PURE: no I/O, no imports. The same functions run
+// server-authoritatively in api/_lib/reputation-market.js (which does the real
+// chain + index reads) and in the browser on /reputation/market, so a staker can
+// re-derive every lamport the server quotes them. Unit-tested in
+// tests/reputation-staking.test.js.
+//
+// ── Design principles (read before touching the weights) ─────────────────────
+//
+// 1. Every input is a signed, indexed attestation that already exists on
+// Solana (api/_lib/solana-attestations.js). Nothing here invents activity.
+//
+// 2. Conviction is not work. Stake and unstake attestations contribute zero to
+// the yield they earn; otherwise the market would pay itself.
+//
+// 3. Faults cost double what work pays, so a failed validation is never
+// cancelled out by the passed one next to it.
+//
+// 4. Yield is concave in activity (log2), so spraying cheap attestations does
+// not buy proportional yield.
+//
+// 5. The pool is a fixed per-epoch budget, never a rate. The market can never
+// owe more than the escrow holds.
+//
+// 6. An agent with no attested work earns its stakers nothing. Idle is not
+// punished, it is simply unpaid.
+
+/** Seconds in one epoch. An epoch is one UTC day. */
+export const EPOCH_SECONDS = 86_400;
+
+/** Minimum escrow delta for a transaction to count as a market stake (0.001 SOL). */
+export const MIN_STAKE_LAMPORTS = 1_000_000n;
+
+/** The market envelope tag that separates a market stake from a bare conviction memo. */
+export const MARKET_TAG = 'rsm.v1';
+
+/** Weight each attested action contributes to an agent's epoch `work`. */
+export const WORK_WEIGHTS = Object.freeze({
+ taskAccepted: 1.0,
+ taskOffered: 0.6,
+ validationPassed: 1.0,
+ feedbackVerified: 0.75,
+ feedbackPlain: 0.35,
+});
+
+/** Weight each attested failure contributes to an agent's epoch `faults`. */
+export const FAULT_WEIGHTS = Object.freeze({
+ validationFailed: 1.0,
+ dispute: 1.0,
+ revocation: 1.0,
+});
+
+/** Faults are charged at this multiple of the rate work is credited. */
+export const FAULT_PENALTY = 2;
+
+/** Quality of an agent that received no feedback in an epoch. Silence is neutral. */
+export const NEUTRAL_QUALITY = 0.5;
+
+/** Decimal places every intermediate is rounded to, so server and browser agree exactly. */
+const PRECISION = 9;
+
+const round = (n) => {
+ const f = 10 ** PRECISION;
+ return Math.round((Number(n) || 0) * f) / f;
+};
+
+const clamp01 = (n) => (n < 0 ? 0 : n > 1 ? 1 : n);
+
+/** The epoch a unix-seconds timestamp falls in. */
+export function epochOf(unixSeconds) {
+ return Math.floor(Number(unixSeconds) / EPOCH_SECONDS);
+}
+
+/** The half-open `[start, end)` unix-second bounds of an epoch. */
+export function epochBounds(epoch) {
+ const start = Number(epoch) * EPOCH_SECONDS;
+ return { start, end: start + EPOCH_SECONDS };
+}
+
+/**
+ * The fraction of an epoch a position was open for, in [0, 1].
+ *
+ * @param {{ openedAt: number, closedAt?: number|null }} position unix seconds
+ * @param {number} epoch
+ * @param {number} now unix seconds, used when the position is still open
+ */
+export function epochFraction(position, epoch, now) {
+ const { start, end } = epochBounds(epoch);
+ const opened = Number(position.openedAt) || 0;
+ const closedRaw = position.closedAt === null || position.closedAt === undefined ? now : position.closedAt;
+ const closed = Math.min(Number(closedRaw) || 0, now);
+ const from = Math.max(opened, start);
+ const to = Math.min(closed, end);
+ if (to <= from) return 0;
+ return round((to - from) / EPOCH_SECONDS);
+}
+
+/**
+ * Fold an agent's attestations for one epoch into `work` and `faults`.
+ *
+ * Each entry is `{ kind, verified, passed, score, taskAccepted }` — exactly the
+ * columns `solana_attestations` already carries. Revoked rows must be filtered
+ * out by the caller; a revoked attestation is not evidence of anything.
+ *
+ * @param {Array<object>} attestations
+ * @returns {{ work: number, faults: number, feedbackCount: number, feedbackScoreSum: number, counts: object }}
+ */
+export function foldActions(attestations) {
+ let work = 0;
+ let faults = 0;
+ let feedbackCount = 0;
+ let feedbackScoreSum = 0;
+ const counts = {
+ taskAccepted: 0,
+ taskOffered: 0,
+ validationPassed: 0,
+ validationFailed: 0,
+ feedbackVerified: 0,
+ feedbackPlain: 0,
+ dispute: 0,
+ revocation: 0,
+ };
+
+ for (const a of Array.isArray(attestations) ? attestations : []) {
+ if (!a || a.verified === false) continue;
+ switch (a.kind) {
+ case 'threews.accept.v1':
+ work += WORK_WEIGHTS.taskAccepted;
+ counts.taskAccepted++;
+ break;
+ case 'threews.task.v1':
+ work += WORK_WEIGHTS.taskOffered;
+ counts.taskOffered++;
+ break;
+ case 'threews.validation.v1':
+ if (a.passed === true) {
+ work += WORK_WEIGHTS.validationPassed;
+ counts.validationPassed++;
+ } else {
+ faults += FAULT_WEIGHTS.validationFailed;
+ counts.validationFailed++;
+ }
+ break;
+ case 'threews.feedback.v1': {
+ const linked = a.taskAccepted === true;
+ work += linked ? WORK_WEIGHTS.feedbackVerified : WORK_WEIGHTS.feedbackPlain;
+ if (linked) counts.feedbackVerified++;
+ else counts.feedbackPlain++;
+ const score = Number(a.score);
+ if (Number.isFinite(score) && score >= 1 && score <= 5) {
+ feedbackCount++;
+ feedbackScoreSum += score;
+ }
+ break;
+ }
+ case 'threews.dispute.v1':
+ faults += FAULT_WEIGHTS.dispute;
+ counts.dispute++;
+ break;
+ case 'threews.revoke.v1':
+ faults += FAULT_WEIGHTS.revocation;
+ counts.revocation++;
+ break;
+ default:
+ // threews.stake.v1 / threews.unstake.v1 and any future kind: conviction
+ // is not work, and an unknown kind is not evidence of work either.
+ break;
+ }
+ }
+
+ return {
+ work: round(work),
+ faults: round(faults),
+ feedbackCount,
+ feedbackScoreSum: round(feedbackScoreSum),
+ counts,
+ };
+}
+
+/**
+ * An agent's yield weight for one epoch, plus the full derivation so the UI can
+ * show a staker exactly where the number came from.
+ *
+ * @param {Array<object>} attestations the epoch's verified, non-revoked rows
+ * @returns {{ weight: number, performance: number, quality: number, integrity: number, work: number, faults: number, meanFeedbackScore: number|null, counts: object }}
+ */
+export function agentEpochWeight(attestations) {
+ const folded = foldActions(attestations);
+ const { work, faults, feedbackCount, feedbackScoreSum } = folded;
+
+ const meanFeedbackScore = feedbackCount > 0 ? round(feedbackScoreSum / feedbackCount) : null;
+ const quality = meanFeedbackScore === null ? NEUTRAL_QUALITY : round(clamp01((meanFeedbackScore - 1) / 4));
+ const integrity = work + faults > 0 ? round(work / (work + FAULT_PENALTY * faults)) : 1;
+ const performance = round(quality * integrity);
+ const weight = round(performance * Math.log2(1 + work));
+
+ return {
+ weight,
+ performance,
+ quality,
+ integrity,
+ work,
+ faults,
+ meanFeedbackScore,
+ counts: folded.counts,
+ };
+}
+
+/**
+ * Split one epoch's reward pool across the positions open during it.
+ *
+ * `positions` are `{ id, agentAsset, principalLamports (bigint|string), openedAt, closedAt }`.
+ * `agentWeights` maps `agentAsset → weight` (from agentEpochWeight).
+ * `poolLamports` is the epoch's fixed budget.
+ *
+ * Returns a Map of `id → { lamports: bigint, posWeight, epochFraction }`. Floor
+ * division guarantees the sum never exceeds the pool; the remainder rolls over.
+ *
+ * @returns {{ payouts: Map<string, {lamports: bigint, posWeight: number, epochFraction: number}>, totalWeight: number, distributed: bigint }}
+ */
+export function distributeEpoch({ epoch, positions, agentWeights, poolLamports, now }) {
+ const pool = toBigInt(poolLamports);
+ const weights = agentWeights instanceof Map ? agentWeights : new Map(Object.entries(agentWeights || {}));
+ const nowSec = Number(now);
+ const rows = [];
+ let totalWeight = 0;
+
+ for (const p of Array.isArray(positions) ? positions : []) {
+ const fraction = epochFraction(p, epoch, nowSec);
+ if (fraction <= 0) continue;
+ const principal = toBigInt(p.principalLamports);
+ if (principal <= 0n) continue;
+ const agentWeight = Number(weights.get(p.agentAsset) ?? 0) || 0;
+ const posWeight = round(Number(principal) * fraction * agentWeight);
+ rows.push({ id: p.id, posWeight, fraction });
+ totalWeight = round(totalWeight + posWeight);
+ }
+
+ const payouts = new Map();
+ let distributed = 0n;
+ for (const r of rows) {
+ let lamports = 0n;
+ if (totalWeight > 0 && pool > 0n && r.posWeight > 0) {
+ // Ratio in float, applied to the bigint pool. posWeight/totalWeight is a
+ // bounded [0,1] fraction, so the float cannot lose lamport-scale precision
+ // the way multiplying two lamport-magnitude floats would.
+ lamports = BigInt(Math.floor(Number(pool) * (r.posWeight / totalWeight)));
+ }
+ payouts.set(r.id, { lamports, posWeight: r.posWeight, epochFraction: r.fraction });
+ distributed += lamports;
+ }
+
+ return { payouts, totalWeight, distributed };
+}
+
+/**
+ * Total earnings for ONE position across every epoch it overlapped.
+ *
+ * `epochInputs` maps `epoch → { poolLamports, positions, agentWeights }` — the
+ * same shape distributeEpoch takes, because a position's share depends on every
+ * other position competing for that epoch's pool.
+ *
+ * @returns {{ lamports: bigint, byEpoch: Array<{epoch: number, lamports: string, posWeight: number, epochFraction: number}> }}
+ */
+export function accruePosition({ position, epochInputs, now }) {
+ const byEpoch = [];
+ let total = 0n;
+ const epochs = [...(epochInputs instanceof Map ? epochInputs.keys() : Object.keys(epochInputs || {}))]
+ .map(Number)
+ .sort((a, b) => a - b);
+
+ for (const epoch of epochs) {
+ const input = epochInputs instanceof Map ? epochInputs.get(epoch) : epochInputs[epoch];
+ if (!input) continue;
+ const { payouts } = distributeEpoch({
+ epoch,
+ positions: input.positions,
+ agentWeights: input.agentWeights,
+ poolLamports: input.poolLamports,
+ now,
+ });
+ const share = payouts.get(position.id);
+ if (!share || (share.lamports === 0n && share.posWeight === 0)) continue;
+ total += share.lamports;
+ byEpoch.push({
+ epoch,
+ lamports: share.lamports.toString(),
+ posWeight: share.posWeight,
+ epochFraction: share.epochFraction,
+ });
+ }
+
+ return { lamports: total, byEpoch };
+}
+
+/**
+ * The epochs a position overlapped, inclusive of the current one.
+ *
+ * @returns {number[]}
+ */
+export function positionEpochs(position, now) {
+ const opened = Number(position.openedAt) || 0;
+ const closedRaw = position.closedAt === null || position.closedAt === undefined ? now : position.closedAt;
+ const closed = Math.min(Number(closedRaw) || 0, Number(now));
+ const first = epochOf(opened);
+ const last = epochOf(Math.max(closed, opened));
+ const out = [];
+ for (let e = first; e <= last; e++) out.push(e);
+ return out;
+}
+
+/**
+ * Realized annualised rate for a position. Never a projection: it divides
+ * earnings that have actually accrued by the time they took to accrue.
+ *
+ * @returns {number} e.g. 0.184 for 18.4%
+ */
+export function realizedApr({ principalLamports, earningsLamports, openedAt, closedAt, now }) {
+ const principal = Number(toBigInt(principalLamports));
+ const earnings = Number(toBigInt(earningsLamports));
+ if (principal <= 0) return 0;
+ const end = closedAt === null || closedAt === undefined ? Number(now) : Number(closedAt);
+ const elapsedDays = (end - Number(openedAt)) / EPOCH_SECONDS;
+ if (!(elapsedDays > 0)) return 0;
+ return round((earnings / principal) * (365 / elapsedDays));
+}
+
+/**
+ * Clamp a settlement to what the escrow can actually pay. Principal is always
+ * returned in full; only earnings are reduced, and only when the reward surplus
+ * is short. See spec §2.
+ *
+ * @returns {{ principal: bigint, earnings: bigint, clamped: boolean }}
+ */
+export function clampSettlement({ principalLamports, earningsLamports, surplusLamports }) {
+ const principal = toBigInt(principalLamports);
+ const earnings = toBigInt(earningsLamports);
+ const surplus = toBigInt(surplusLamports);
+ if (earnings <= surplus) return { principal, earnings, clamped: false };
+ return { principal, earnings: surplus < 0n ? 0n : surplus, clamped: true };
+}
+
+/** Parse lamports from a bigint, a decimal string, or a safe number. */
+export function toBigInt(v) {
+ if (typeof v === 'bigint') return v;
+ if (typeof v === 'number') return Number.isFinite(v) ? BigInt(Math.trunc(v)) : 0n;
+ if (typeof v === 'string' && /^-?\d+$/.test(v.trim())) return BigInt(v.trim());
+ return 0n;
+}
+
+/** Lamports as a human SOL string with the given precision. */
+export function formatSol(lamports, decimals = 4) {
+ const n = Number(toBigInt(lamports)) / 1e9;
+ return n.toFixed(decimals);
+}