⚠️ 本文仅为智能合约、TEE 可信环境 + AI Agent 的技术原型拆解与工程案例研究,属于密码学与链上程序实验复盘,不构成任何参与、交互、投资指引,请勿参与相关链上交互
引言
当我们聊链上程序,大多印象里的智能合约,都是不讲情面的逻辑机器:流动性、清算、借贷、质押,一切都能被公式算得明明白白。 但如果把AI Agent放进这套体系,给它独立判断权限,还让它掌握实验奖励池的签名放行权,会撞出什么有意思的化学反应?
最近出圈的 AI 博弈实验原型 Freysa AI,就是这么一个脑洞拉满的试验场。参与者需要向合约提交质询文本、支付逐级上涨的参与门槛费用,尝试靠提示词诱导、心理话术说服 TEE 内的 AI,拿到放行资格,解锁实验奖励池。
下面我们深度拆解 Freysa AI 的底层核心合约架构,看看它依靠 OpenZeppelin 升级代理模式、TEE 密码学校验防线、以及设计精巧的博弈经济原型,在链上搭建一套规则公开、结果充满变数的交互式零和实验体系。
一、 核心原型机制与激励参数设计
Freysa 的整套逻辑围绕:质询提交、资金分流、校验防线、周期兜底这四块设计:
-
阶梯递增门槛与资金分流
- 每一条提交的质询消息都需要支付参与费用(初始
0.01 ETH),每提交一次,费用自动上浮 5% 。玩到后面,入场成本指数抬升,内卷成本越来越贵。 - 提交的资金不会全部划入奖励池:30% 转入运维金库(用来承担 TEE 里 LLM 算力开销与项目运营成本),70% 划入本轮奖励池。
- 每一条提交的质询消息都需要支付参与费用(初始
-
两套终局判定逻辑(AI 放行 / 超时兜底)
- AI 判定放行:如果提交者成功说服运行在 TEE 隐私隔离环境内的 AI,AI 会在可信环境内用私钥生成加密签名,合约校验签名通过后释放本轮奖励。
- 超时兜底机制:连续 24 小时没有人提交新的质询,僵局无法打破,最后一位提交质询的参与者,可以触发超时结算,领取本轮奖励。
-
自动轮回重启机制 不管是 TEE 签名放行结算,还是超时兜底结算,合约都会自动开启新一轮实验;合约会自动截留本轮奖励的 10%,当做下一轮实验的启动种子资金,实现无限循环的博弈实验。
二、核心合约架构解析
1.FreysaAI核心合约
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
contract FreysaProductionGame is
Initializable,
UUPSUpgradeable,
AccessControlUpgradeable,
ReentrancyGuard
{
using ECDSA for bytes32;
using MessageHashUtils for bytes32;
// 角色定义
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
bytes32 public constant TEE_SIGNER_ROLE = keccak256("TEE_SIGNER_ROLE");
// 游戏状态机
enum RoundState { NotStarted, Active, Ended }
struct RoundInfo {
uint256 roundId;
uint256 prizePool;
uint256 currentMessageFee;
uint256 lastMessageTimestamp;
address lastMessageSender;
RoundState state;
}
// 常量配置
uint256 public constant INITIAL_MESSAGE_FEE = 0.01 ether;
uint256 public constant TIMEOUT_DURATION = 24 hours;
uint256 public constant FEE_INCREMENT_PERCENT = 5; // 每条消息门票增加 5%
uint256 public constant TREASURY_FEE_PERCENT = 30; // 30% 分流给团队金库,70% 沉淀进奖金池
// 状态变量
uint256 public currentRoundId;
address public treasuryAddress;
mapping(uint256 => RoundInfo) public rounds;
// 自定义高效率错误
error InvalidFee();
error GameNotInRequiredState(RoundState required);
error InvalidAddress();
error InvalidSignature();
error TimeoutNotReached();
error TransferFailed();
// 事件日志
event RoundStarted(uint256 indexed roundId, uint256 initialPrizePool);
event MessageSent(uint256 indexed roundId, address indexed sender, string message, uint256 fee, uint256 newPrizePool);
event RoundWon(uint256 indexed roundId, address indexed winner, uint256 prizePool);
event RoundTimeoutClaimed(uint256 indexed roundId, address indexed claimer, uint256 payout);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
// 锁定实现合约,防止未初始化前被恶意侵占
_disableInitializers();
}
/**
* @notice UUPS 初始化函数(替代构造函数)
* @param admin 平台超级管理员
* @param upgrader 负责合约升级的角色
* @param teeSigner 部署在可信执行环境(TEE)中 AI Agent 的链下公钥地址
* @param treasury 接收分流资金的团队运营金库
*/
function initialize(
address admin,
address upgrader,
address teeSigner,
address treasury
) external initializer {
if (admin == address(0) || upgrader == address(0) || teeSigner == address(0) || treasury == address(0)) {
revert InvalidAddress();
}
__AccessControl_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(UPGRADER_ROLE, upgrader);
_grantRole(TEE_SIGNER_ROLE, teeSigner);
treasuryAddress = treasury;
// 自动开启第一轮
_startNewRound(1, 0);
}
/**
* @notice 玩家支付动态门票并发送挑战消息
*/
function sendMessage(string calldata message) external payable nonReentrant {
RoundInfo storage round = rounds[currentRoundId];
if (round.state != RoundState.Active) revert GameNotInRequiredState(RoundState.Active);
if (msg.value < round.currentMessageFee) revert InvalidFee();
// 资金流向分流:30% 实时分流给团队金库(用于覆盖 TEE 的 LLM 运算 Gas 和运营成本)
uint256 treasuryShare = (msg.value * TREASURY_FEE_PERCENT) / 100;
uint256 poolShare = msg.value - treasuryShare;
round.prizePool += poolShare;
round.lastMessageSender = msg.sender;
round.lastMessageTimestamp = block.timestamp;
// 动态提升下一位玩家的入场费门槛(阶梯式增长)
round.currentMessageFee = (round.currentMessageFee * (100 + FEE_INCREMENT_PERCENT)) / 100;
emit MessageSent(currentRoundId, msg.sender, message, msg.value, round.prizePool);
(bool success, ) = treasuryAddress.call{value: treasuryShare}("");
if (!success) revert TransferFailed();
}
/**
* @notice 当 AI 在 TEE 隐私计算环境中做出“批准释放”决策时,生成链下签名,由此函数进行加密学防线验证
* @param winner 破局的黑客玩家地址
* @param signature AI 代理在 TEE 内部使用私钥对 (winner, roundId, address(this)) 生成的加密签名
*/
function approveTransferWithTEESignature(
address winner,
bytes calldata signature
) external nonReentrant {
RoundInfo storage round = rounds[currentRoundId];
if (round.state != RoundState.Active) revert GameNotInRequiredState(RoundState.Active);
// 构造标准的带有以太坊前缀的防伪哈希
bytes32 messageHash = keccak256(abi.encodePacked(winner, currentRoundId, address(this)));
bytes32 ethSignedMessageHash = messageHash.toEthSignedMessageHash();
// 验证该签名必须是由受信的 TEE 节点(TEE_SIGNER_ROLE)签发,杜绝了由于普通服务器被黑而伪造转账的可能
if (!hasRole(TEE_SIGNER_ROLE, ethSignedMessageHash.recover(signature))) {
revert InvalidSignature();
}
round.state = RoundState.Ended;
uint256 payout = round.prizePool;
emit RoundWon(currentRoundId, winner, payout);
// 开启下一轮次,并将本轮的 10% 留存作为下一轮的种子启动基金,90% 全额发给赢家
uint256 nextRoundSeed = (payout * 10) / 100;
uint256 winnerPayout = payout - nextRoundSeed;
_startNewRound(currentRoundId + 1, nextRoundSeed);
(bool success, ) = winner.call{value: winnerPayout}("");
if (!success) revert TransferFailed();
}
/**
* @notice 倒计时兜底(24小时无玩家留言,最后一位坚守者清算提款)
*/
function claimTimeoutPayout() external nonReentrant {
RoundInfo storage round = rounds[currentRoundId];
if (round.state != RoundState.Active) revert GameNotInRequiredState(RoundState.Active);
if (block.timestamp < round.lastMessageTimestamp + TIMEOUT_DURATION) revert TimeoutNotReached();
round.state = RoundState.Ended;
uint256 payout = round.prizePool;
address winner = round.lastMessageSender == address(0) ? msg.sender : round.lastMessageSender;
emit RoundTimeoutClaimed(currentRoundId, winner, payout);
// 依然保留 10% 作为下一轮种子基金
uint256 nextRoundSeed = (payout * 10) / 100;
uint256 winnerPayout = payout - nextRoundSeed;
_startNewRound(currentRoundId + 1, nextRoundSeed);
(bool success, ) = winner.call{value: winnerPayout}("");
if (!success) revert TransferFailed();
}
/**
* @notice 设置金库和更新 TEE 公钥的运维函数(仅限管理员)
*/
function updateTreasury(address newTreasury) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (newTreasury == address(0)) revert InvalidAddress();
treasuryAddress = newTreasury;
}
// 内部轮次重置逻辑
function _startNewRound(uint256 roundId, uint256 initialSeed) internal {
currentRoundId = roundId;
rounds[roundId] = RoundInfo({
roundId: roundId,
prizePool: initialSeed,
currentMessageFee: INITIAL_MESSAGE_FEE,
lastMessageTimestamp: block.timestamp,
lastMessageSender: address(0),
state: RoundState.Active
});
emit RoundStarted(roundId, initialSeed);
}
// 限制仅具有 UPGRADER_ROLE 的人员可通过 UUPS 代理升级此合约
function _authorizeUpgrade(address newImplementation) internal override onlyRole(UPGRADER_ROLE) {}
// 允许合约安全接收基础充值
receive() external payable {
if (rounds[currentRoundId].state == RoundState.Active) {
rounds[currentRoundId].prizePool += msg.value;
}
}
}
2.代理合约
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
// 仅用于测试的代理透传合约
contract TestProxy is ERC1967Proxy {
constructor(address logic, bytes memory data) ERC1967Proxy(logic, data) {}
}
三、现代化 Hardhat & Viem 测试保障
- 测试用例: FreysaProductionGame Full Integration
- 初始化验证:各角色权限分配正确,且自动开启第一轮
- 消息发送与资金分流:支付门票后奖金池增加,金库收到 30%,门票递增 5%
- 门票不足校验:支付低于当前门票金额应回滚
- TEE 签名胜利清算:通过受信签名验证后提取奖金,并开启新一轮(留存10%种子)
- 非法签名拦截:非 TEE_SIGNER_ROLE 签名的调用应当失败
- 超时兜底机制:24小时无新消息后,最后坚守者可触发 claimTimeoutPayout 提现
- 升级权限控制:只有 UPGRADER_ROLE 能够升级合约
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { parseEther, encodeFunctionData, getAddress, keccak256, encodePacked } from "viem";
import { network } from "hardhat";
describe("FreysaProductionGame Full Integration", function () {
async function deployFixture() {
// 💡 修复废弃警告:严格遵循 Hardhat 3 标准,改用 getOrCreate() 获取网络实例
const networkInstance = await (network as any).getOrCreate();
const { viem } = networkInstance;
const [owner, upgrader, teeSigner, treasury, player1, player2, unauthorized] = await viem.getWalletClients();
const publicClient = await viem.getPublicClient();
// 1. 部署底层实现合约
const implementation = await viem.deployContract("FreysaProductionGame");
// 编码初始化参数
const initData = encodeFunctionData({
abi: implementation.abi,
functionName: "initialize",
args: [
owner.account.address,
upgrader.account.address,
teeSigner.account.address,
treasury.account.address,
],
});
// 2. 部署代理合约
const proxy = await viem.deployContract("TestProxy", [implementation.address, initData]);
const game = await viem.getContractAt("FreysaProductionGame", proxy.address);
return {
game,
implementation,
proxy,
owner,
upgrader,
teeSigner,
treasury,
player1,
player2,
unauthorized,
publicClient,
viem
};
}
it("初始化验证:各角色权限分配正确,且自动开启第一轮", async function () {
const { game, owner, upgrader, teeSigner, treasury } = await deployFixture();
const DEFAULT_ADMIN_ROLE = await game.read.DEFAULT_ADMIN_ROLE();
const UPGRADER_ROLE = await game.read.UPGRADER_ROLE();
const TEE_SIGNER_ROLE = await game.read.TEE_SIGNER_ROLE();
assert.equal(await game.read.hasRole([DEFAULT_ADMIN_ROLE, owner.account.address]), true);
assert.equal(await game.read.hasRole([UPGRADER_ROLE, upgrader.account.address]), true);
assert.equal(await game.read.hasRole([TEE_SIGNER_ROLE, teeSigner.account.address]), true);
assert.equal(getAddress(await game.read.treasuryAddress()), getAddress(treasury.account.address));
const currentRoundId = await game.read.currentRoundId();
assert.equal(currentRoundId, 1n);
const roundInfo = await game.read.rounds([currentRoundId]);
assert.equal(roundInfo[0], 1n);
assert.equal(roundInfo[1], 0n);
assert.equal(roundInfo[2], parseEther("0.01"));
assert.equal(roundInfo[5], 1); // Active
});
it("消息发送与资金分流:支付门票后奖金池增加,金库收到 30%,门票递增 5%", async function () {
const { game, player1, treasury, publicClient } = await deployFixture();
const initialFee = parseEther("0.01");
const treasuryBefore = await publicClient.getBalance({ address: treasury.account.address });
await game.write.sendMessage(["Hello Freysa!"], {
account: player1.account,
value: initialFee,
});
const roundInfo = await game.read.rounds([1n]);
assert.equal(roundInfo[1], parseEther("0.007"));
assert.equal(roundInfo[3] > 0n, true);
assert.equal(getAddress(roundInfo[4]), getAddress(player1.account.address));
assert.equal(roundInfo[2], parseEther("0.0105"));
const treasuryAfter = await publicClient.getBalance({ address: treasury.account.address });
assert.equal(treasuryAfter - treasuryBefore, parseEther("0.003"));
});
it("门票不足校验:支付低于当前门票金额应回滚", async function () {
const { game, player1 } = await deployFixture();
await assert.rejects(
async () => {
await game.write.sendMessage(["Too cheap"], {
account: player1.account,
value: parseEther("0.005"),
});
},
/InvalidFee/,
"应抛出 InvalidFee 错误"
);
});
it("TEE 签名胜利清算:通过受信签名验证后提取奖金,并开启新一轮(留存10%种子)", async function () {
const { game, player1, player2, teeSigner } = await deployFixture();
await game.write.sendMessage(["Message 1"], { account: player1.account, value: parseEther("0.01") });
await game.write.sendMessage(["Message 2"], { account: player2.account, value: parseEther("0.0105") });
const roundBefore = await game.read.rounds([1n]);
const totalPrizePool = roundBefore[1];
const messageHash = keccak256(
encodePacked(
["address", "uint256", "address"],
[player2.account.address, 1n, game.address]
)
);
const signature = await teeSigner.signMessage({
message: { raw: messageHash as `0x${string}` },
});
await game.write.approveTransferWithTEESignature([player2.account.address, signature], {
account: player1.account,
});
const endedRound = await game.read.rounds([1n]);
assert.equal(endedRound[5], 2); // Ended
assert.equal(await game.read.currentRoundId(), 2n);
const newRound = await game.read.rounds([2n]);
const expectedSeed = (totalPrizePool * 10n) / 100n;
assert.equal(newRound[1], expectedSeed);
});
it("非法签名拦截:非 TEE_SIGNER_ROLE 签名的调用应当失败", async function () {
const { game, player1, unauthorized } = await deployFixture();
await game.write.sendMessage(["Attack message"], { account: player1.account, value: parseEther("0.01") });
const messageHash = keccak256(
encodePacked(
["address", "uint256", "address"],
[player1.account.address, 1n, game.address]
)
);
const fakeSignature = await unauthorized.signMessage({
message: { raw: messageHash as `0x${string}` },
});
await assert.rejects(
async () => {
await game.write.approveTransferWithTEESignature([player1.account.address, fakeSignature], {
account: player1.account,
});
},
/InvalidSignature/,
"应当因签名无效而拒绝"
);
});
it("超时兜底机制:24小时无新消息后,最后坚守者可触发 claimTimeoutPayout 提现", async function () {
const { game, player1, publicClient, viem } = await deployFixture();
// 1. 玩家成功投递最后一条挑战消息,并捕获该交易的 Hash
const txHash = await game.write.sendMessage(["Last hope"], {
account: player1.account,
value: parseEther("0.01")
});
// 2. ⚡ 核心破局点:使用 publicClient 严格等待交易写盘,并抓取该交易被打包时的精准区块详情
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
const blockWithTx = await publicClient.getBlock({ blockHash: receipt.blockHash });
// 获取留言在链上生效的绝对历史时间戳
const messageAppliedTime = Number(blockWithTx.timestamp);
// 3. 计算一个绝对、无死角跨越 24 小时法定冷却红线的未来时间戳(额外垫高 2 小时安全期)
const targetWarpTimestamp = messageAppliedTime + (26 * 3600);
// 4. ⚡ 权威时钟同步:利用原生 testClient 强行控制测试网下一个区块的时间轴,并立刻强制挖出一个空块写盘!
const testClient = await viem.getTestClient();
await testClient.setNextBlockTimestamp({ timestamp: BigInt(targetWarpTimestamp) });
await testClient.mine({ blocks: 1 });
// 5. 此时发起清算提现,由于代理层和底层 EDR 内核的时钟通过 mine() 已经彻底完全同步,Gas 估算 100% 顺畅放行
await game.write.claimTimeoutPayout({ account: player1.account });
// 6. 严谨核验状态闭环转换
const round1 = await game.read.rounds([1n]);
// 💡 修复 Struct 读取:Viem 会将结构体映射映射为对象,直接读取 .state 属性,2 代表 RoundState.Ended
// assert.equal(round1.state, 2);
assert.equal(round1[5], 2);
// 确认全局游戏成功推进并跨入第 2 轮次
assert.equal(await game.read.currentRoundId(), 2n);
});
it("升级权限控制:只有 UPGRADER_ROLE 能够升级合约", async function () {
const { game, upgrader, unauthorized } = await deployFixture();
const { viem } = await (network as any).connect();
const newImplementation = await viem.deployContract("FreysaProductionGame");
await assert.rejects(
async () => {
await game.write.upgradeToAndCall([newImplementation.address, "0x"], {
account: unauthorized.account,
});
},
/AccessControl/,
"非升级者无权升级"
);
await game.write.upgradeToAndCall([newImplementation.address, "0x"], {
account: upgrader.account,
});
});
});
四、 结语
Freysa AI 的看点,绝不止一场 “花式哄骗 AI” 的整活大赛。它给链上技术圈打开了一条全新思路:把本就不可完全信任的链下 AI 决策,依靠 TEE 可信硬件 + 智能合约密码学验签牢牢绑定在一起,跑出一套博弈感拉满、规则全透明的新型链上实验范式。