深度拆解 MyShell 底层:AI Agent 生态结算合约,如何实现安全防阻塞

引言

在 Unix 哲学里,Shell(壳) 是包裹在内核(Kernel)外面的交互界面------内核负责干重活,Shell 负责把复杂晦涩的系统调用翻译得人畜无害。MyShell 把这个经典隐喻搬到了 AI 时代:底层大模型是算力内核,而每个创作者都能凭借零代码框架捏出自己的"AI 外壳(Agent)"放进市场赚钱。

在上一篇全景拆解 MyShell 的文章中,我们顺着它 "链下推理、链上确权" 的务实路线,梳理了其三层架构、Pro Config 零代码工作流以及 OpenVoice / MeloTTS 等开源语音王牌,同时也客观盘点了它在基座模型依赖、同类平台内卷以及 Web2 用户向 Web3 转化上的真实挑战。

宏观版图聊透了,今天不整虚头巴脑的商业叙事,直接扎进最底层的智能合约代码里。面对"链下 AI 毫秒级推理"与"链上秒级区块确认"的天然速度差,怎么用 Solidity 写出一个算账不留误差、资金不被卡死、且能把管理员权力关进笼子的结算与风控协议?


一、 链下高频调用,链上怎么算账?

如果用户每和 AI 聊一句天就发一笔链上交易,Gas 费比对话费还贵,产品当场就得凉。工程上通用的解法是 "链下计费聚合 + 链上周期清算" 。一旦结算资金流入合约池,核心要解决的就是三方分账(Platform 平台 + Model 模型方 + Creator 创作者) 。

在 Solidity 里写分账,最忌讳两件事:精度丢失留"粉尘" ,以及主动循环转账被卡死。协议层落地了两个经典模式:

1. 万分比(BPS)+ 减法兜底

Solidity 没有浮点数,费率全部用基点(Basis Points,10000 = 100%)表示。假设平台抽 5%(500),底层模型抽 20%(2000),剩下的全归创作者。

代码里千万别写 amount * 7500 / 10000 去算创作者份额------两次整数除法向下取整会导致 1 wei 的"粉尘资金"永远锁死在合约里。正确姿势是减法兜底:

  • platformShare = amount * platformFeeBps / 10000
  • modelShare = amount * modelFeeBps / 10000
  • creatorShare = amount - platformShare - modelShare

进多少分多少,一分钱不剩,账本永远严丝合缝。

2. Pull-over-Push(拉取优于推送)

分账时绝对不要在结算函数里直接 transfer 打钱给各方。万一某个创作者填了个恶意合约地址,在 receive() 里写死 revert() 或者塞满消耗 Gas 的死循环,整笔批量结算交易就会全盘回滚,连累所有人拿不到钱。

因此,结算函数只做内部账本记账 (累加 claimableRewards[address]),要钱自己调 withdraw 来领,各扫门前雪,互不阻塞。


二、 合约风控:怎么把管理员的权力关进笼子?

去中心化协议最怕"超级管理员"半夜把抽成调成 99%。在协议风控设计上,我们直接把两把硬锁焊死在字节码里:

  1. 权限硬隔离(Ownable) :修改全局费率属于系统级敏感操作,任何非 owner 地址调用直接触发 OwnableUnauthorizedAccount 回滚,连函数门坎都迈不进去。
  2. 50% 费率熔断上限(Fee Cap) :哪怕管理员私钥意外泄露,或者治理头脑发热,合约也在底层写死了数学红线:
    (\text{platformFeeBps}+\text{modelFeeBps}\le 5000\text{\ (即 }50%\text{)})
    平台加模型的总抽成永远不可能突破 50%,创作者的保底收益权由 EVM 字节码直接捍卫。谁敢传入类似 3000 + 2500 的超限参数,合约立刻抛出自定义错误 FeeTooHigh() 拒之门外,从根源上杜绝"无限抽水"的信任危机。

三、 测试踩坑实录:Viem 报错和合约 Revert 是两码事

写完合约,上 Hardhat + Viem + Node 原生 Test Runner 跑全链路集成测试时,顺手抓出了一个极具代表性的工程细节。

在测"非管理员调用 setFeeRates 应该被拦截"时,测试一开始直接红了。抓出异常一看,报错根本不是预期的 OwnableUnauthorizedAccount,而是 Viem 抛出的 AbiFunctionNotFoundError。

原因很直白:Viem 在发交易前会先拿本地编译出来的 ABI 字典做校验。如果测试脚本里敲的函数名和合约里没对齐,Viem 在本地构造 Calldata 阶段就直接报错退出了,压根没把交易发给本地节点去执行 EVM 逻辑。

这也给 Web3 逆向边界测试(Negative Testing)提了个醒:断言匹配不能只写个宽泛的 assert.rejects 了事 ------否则代码写错了函数名,测试也会"假装通过",把真正的安全漏洞掩盖过去。必须精准校验链上抛出的错误签名(如 OwnableUnauthorizedAccount 或 FeeTooHigh),才算真正测到了合约的防线。


四、 核心实现

1. 核心协议合约 (MyShellEcosystem.sol)

js 复制代码
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {ERC721URIStorage} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract MyShellEcosystem is ERC721URIStorage, Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    IERC20 public immutable shellToken;
    address public platformTreasury;
    uint256 private _nextAgentId;

    uint256 public constant BPS_DENOMINATOR = 10000;
    uint256 public platformFeeBps = 1000; // 平台抽成 10%
    uint256 public modelFeeBps = 1500;    // 底层模型提供者抽成 15%

    struct AIAgent {
        address modelProvider;
        uint256 pricePerUse;
        uint256 totalRevenue;
        bool isActive;
    }

    mapping(uint256 => AIAgent) public agents;
    mapping(address => uint256) public pendingWithdrawals;

    error AgentNotActive();
    error InvalidPrice();
    error InvalidAddress();
    error NothingToWithdraw();

    constructor(address _shellToken, address _treasury, address initialOwner) 
        ERC721("MyShell AI Agent", "MSAGENT") 
        Ownable(initialOwner) 
    {
        if (_shellToken == address(0) || _treasury == address(0)) revert InvalidAddress();
        shellToken = IERC20(_shellToken);
        platformTreasury = _treasury;
    }

    // 创作者发布 AI 代理并铸造所有权 NFT
    function createAgent(string calldata metadataURI, address modelProvider, uint256 pricePerUse) external returns (uint256) {
        if (modelProvider == address(0)) revert InvalidAddress();
        if (pricePerUse == 0) revert InvalidPrice();

        uint256 agentId = ++_nextAgentId;
        _safeMint(msg.sender, agentId);
        _setTokenURI(agentId, metadataURI);

        agents[agentId] = AIAgent(modelProvider, pricePerUse, 0, true);
        return agentId;
    }

    // 用户付费交互,自动按比例记账分润(Pull-Payment 模式保障资金安全)
    function useAgent(uint256 agentId) external nonReentrant {
        AIAgent storage agent = agents[agentId];
        if (!agent.isActive) revert AgentNotActive();

        address currentOwner = ownerOf(agentId);
        uint256 price = agent.pricePerUse;

        shellToken.safeTransferFrom(msg.sender, address(this), price);

        uint256 platformShare = (price * platformFeeBps) / BPS_DENOMINATOR;
        uint256 modelShare = (price * modelFeeBps) / BPS_DENOMINATOR;
        uint256 creatorShare = price - platformShare - modelShare;

        pendingWithdrawals[platformTreasury] += platformShare;
        pendingWithdrawals[agent.modelProvider] += modelShare;
        pendingWithdrawals[currentOwner] += creatorShare;
        agent.totalRevenue += price;
    }

    // 各方随时提取累计的 SHELL 收益
    function withdrawRevenue() external nonReentrant {
        uint256 amount = pendingWithdrawals[msg.sender];
        if (amount == 0) revert NothingToWithdraw();

        pendingWithdrawals[msg.sender] = 0;
        shellToken.safeTransfer(msg.sender, amount);
    }
    error FeeTooHigh();

function setFeeRates(uint256 _platformFeeBps, uint256 _modelFeeBps) external onlyOwner {
    if (_platformFeeBps + _modelFeeBps > 5000) revert FeeTooHigh();
    platformFeeBps = _platformFeeBps;
    modelFeeBps = _modelFeeBps;
}
}

2. 全链路集成测试 (test/myshell.ts)

  • 完备用例:MyShell Ecosystem Protocol Full Integration
    • 初始化验证:代币总量、国库地址与默认分润比例应正确配置
    • 部署参数拦截:使用零地址初始化生态合约应回滚
    • 代理创建与确权:创作者铸造 AI 代理应生成对应 ERC-721 NFT 并记录元数据
    • 创建参数拦截:模型提供者为零地址或价格为零时应回滚
    • 微支付与自动分润:用户付费调用代理后,三方账本应按 10% / 15% / 75% 精确记账
    • 所有权动态转移:NFT 二级市场转手后,后续调用分润应自动流向新买家
    • 安全提现(Pull-Payment):各方应能顺利提取分润,无余额时提现应拦截
    • 权限与费率风控:仅管理员可调整费率且总抽成不得超过 50% 上限
js 复制代码
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { parseEther, zeroAddress, getAddress } from "viem";
import { network } from "hardhat";

describe("MyShell Ecosystem Protocol Full Integration", function () {
  async function deployFixture() {
    const { viem } = await (network as any).connect();
    const [owner, treasury, creator, modelProvider, user, newNftBuyer] =
      await viem.getWalletClients();
    const publicClient = await viem.getPublicClient();

    const initialUserBalance = parseEther("10000");
    const agentPrice = parseEther("100"); // 单次调用 100 SHELL

    // 1. 部署生态代币合约 (MyShellToken)
    const shellToken = await viem.deployContract("ShellToken", [
      owner.account.address,
    ]);

    // 2. 部署 AI 代理确权与分润核心合约 (MyShellEcosystem)
    const ecosystem = await viem.deployContract("MyShellEcosystem", [
      shellToken.address,
      treasury.account.address,
      owner.account.address,
    ]);

    // 3. 给测试用户划转初始 SHELL 代币
    await shellToken.write.transfer([user.account.address, initialUserBalance], {
      account: owner.account,
    });

    return {
      shellToken,
      ecosystem,
      owner,
      treasury,
      creator,
      modelProvider,
      user,
      newNftBuyer,
      publicClient,
      initialUserBalance,
      agentPrice,
    };
  }

  it("初始化验证:代币总量、国库地址与默认分润比例应正确配置", async function () {
    const { shellToken, ecosystem, treasury, user, initialUserBalance } =
      await deployFixture();

    const totalSupply = await shellToken.read.totalSupply();
    const userBalance = await shellToken.read.balanceOf([user.account.address]);
    const boundToken = await ecosystem.read.shellToken();
    const boundTreasury = await ecosystem.read.platformTreasury();
    const platformFeeBps = await ecosystem.read.platformFeeBps();
    const modelFeeBps = await ecosystem.read.modelFeeBps();

    assert.equal(totalSupply, parseEther("1000000000"), "代币初始总供应量应为 10 亿");
    assert.equal(userBalance, initialUserBalance, "测试用户初始余额不匹配");
    assert.equal(
      getAddress(boundToken),
      getAddress(shellToken.address),
      "绑定的 SHELL 代币地址不匹配"
    );
    assert.equal(
      getAddress(boundTreasury),
      getAddress(treasury.account.address),
      "平台国库地址不匹配"
    );
    assert.equal(platformFeeBps, 1000n, "默认平台抽成应为 10% (1000 BPS)");
    assert.equal(modelFeeBps, 1500n, "默认模型方抽成应为 15% (1500 BPS)");
  });

  it("部署参数拦截:使用零地址初始化生态合约应回滚", async function () {
    const { viem } = await (network as any).connect();
    const [owner, treasury] = await viem.getWalletClients();
    const shellToken = await viem.deployContract("ShellToken", [
      owner.account.address,
    ]);

    await assert.rejects(
      async () => {
        await viem.deployContract("MyShellEcosystem", [
          zeroAddress,
          treasury.account.address,
          owner.account.address,
        ]);
      },
      /InvalidAddress/,
      "代币地址为零地址时应触发 InvalidAddress 错误"
    );

    await assert.rejects(
      async () => {
        await viem.deployContract("MyShellEcosystem", [
          shellToken.address,
          zeroAddress,
          owner.account.address,
        ]);
      },
      /InvalidAddress/,
      "国库地址为零地址时应触发 InvalidAddress 错误"
    );
  });

  it("代理创建与确权:创作者铸造 AI 代理应生成对应 ERC-721 NFT 并记录元数据", async function () {
    const { ecosystem, creator, modelProvider, agentPrice } =
      await deployFixture();
    const metadataURI = "ipfs://QmMyShellAgentMetadataHash";

    await ecosystem.write.createAgent(
      [metadataURI, modelProvider.account.address, agentPrice],
      { account: creator.account }
    );

    const agentId = 1n;
    const nftOwner = await ecosystem.read.ownerOf([agentId]);
    const tokenURI = await ecosystem.read.tokenURI([agentId]);
    const [storedProvider, storedPrice, totalRevenue, isActive] =
      await ecosystem.read.agents([agentId]);

    assert.equal(
      getAddress(nftOwner),
      getAddress(creator.account.address),
      "NFT 所有权应归属创作者"
    );
    assert.equal(tokenURI, metadataURI, "元数据 URI 存储不匹配");
    assert.equal(
      getAddress(storedProvider),
      getAddress(modelProvider.account.address),
      "底层模型提供者地址不匹配"
    );
    assert.equal(storedPrice, agentPrice, "单次调用价格不匹配");
    assert.equal(totalRevenue, 0n, "初始累计营收应为 0");
    assert.equal(isActive, true, "新建代理应处于激活状态");
  });

  it("创建参数拦截:模型提供者为零地址或价格为零时应回滚", async function () {
    const { ecosystem, creator, modelProvider, agentPrice } =
      await deployFixture();

    await assert.rejects(
      async () => {
        await ecosystem.write.createAgent(
          ["ipfs://invalid", zeroAddress, agentPrice],
          { account: creator.account }
        );
      },
      /InvalidAddress/,
      "模型提供者为零地址应触发 InvalidAddress"
    );

    await assert.rejects(
      async () => {
        await ecosystem.write.createAgent(
          ["ipfs://invalid", modelProvider.account.address, 0n],
          { account: creator.account }
        );
      },
      /InvalidPrice/,
      "单次调用价格为 0 应触发 InvalidPrice"
    );
  });

  it("微支付与自动分润:用户付费调用代理后,三方账本应按 10% / 15% / 75% 精确记账", async function () {
    const {
      shellToken,
      ecosystem,
      treasury,
      creator,
      modelProvider,
      user,
      agentPrice,
    } = await deployFixture();

    // 1. 创作者发布 AI 代理
    await ecosystem.write.createAgent(
      ["ipfs://agent1", modelProvider.account.address, agentPrice],
      { account: creator.account }
    );
    const agentId = 1n;

    // 2. 用户授权并付费调用代理
    await shellToken.write.approve([ecosystem.address, agentPrice], {
      account: user.account,
    });
    await ecosystem.write.useAgent([agentId], { account: user.account });

    // 3. 验证三方可提现余额与合约总托管余额
    const treasuryShare = await ecosystem.read.pendingWithdrawals([
      treasury.account.address,
    ]);
    const modelShare = await ecosystem.read.pendingWithdrawals([
      modelProvider.account.address,
    ]);
    const creatorShare = await ecosystem.read.pendingWithdrawals([
      creator.account.address,
    ]);
    const contractBalance = await shellToken.read.balanceOf([ecosystem.address]);

    assert.equal(treasuryShare, parseEther("10"), "平台国库应获得 10% (10 SHELL)");
    assert.equal(modelShare, parseEther("15"), "模型提供方应获得 15% (15 SHELL)");
    assert.equal(creatorShare, parseEther("75"), "创作者应获得 75% (75 SHELL)");
    assert.equal(contractBalance, agentPrice, "生态合约托管总额应等于用户支付金额");
  });

  it("所有权动态转移:NFT 二级市场转手后,后续调用分润应自动流向新买家", async function () {
    const {
      shellToken,
      ecosystem,
      creator,
      modelProvider,
      user,
      newNftBuyer,
      agentPrice,
    } = await deployFixture();

    // 1. 创作者创建代理
    await ecosystem.write.createAgent(
      ["ipfs://agent1", modelProvider.account.address, agentPrice],
      { account: creator.account }
    );
    const agentId = 1n;

    // 2. 创作者将 AI 代理 NFT 转移给新买家
    await ecosystem.write.transferFrom(
      [creator.account.address, newNftBuyer.account.address, agentId],
      { account: creator.account }
    );

    // 3. 用户调用该代理
    await shellToken.write.approve([ecosystem.address, agentPrice], {
      account: user.account,
    });
    await ecosystem.write.useAgent([agentId], { account: user.account });

    // 4. 验证原创作者分润为 0,新买家获得 75% 分润
    const oldCreatorShare = await ecosystem.read.pendingWithdrawals([
      creator.account.address,
    ]);
    const newBuyerShare = await ecosystem.read.pendingWithdrawals([
      newNftBuyer.account.address,
    ]);

    assert.equal(oldCreatorShare, 0n, "NFT 转手后原创作者不应再获得新分润");
    assert.equal(
      newBuyerShare,
      parseEther("75"),
      "新 NFT 持有者应自动获得 75% 创作者分润"
    );
  });

  it("安全提现(Pull-Payment):各方应能顺利提取分润,无余额时提现应拦截", async function () {
    const {
      shellToken,
      ecosystem,
      creator,
      modelProvider,
      user,
      agentPrice,
    } = await deployFixture();

    // 无可提现余额时直接调用应回滚
    await assert.rejects(
      async () => {
        await ecosystem.write.withdrawRevenue({ account: creator.account });
      },
      /NothingToWithdraw/,
      "余额为 0 时提现应触发 NothingToWithdraw"
    );

    // 创建并产生一笔交互消费
    await ecosystem.write.createAgent(
      ["ipfs://agent1", modelProvider.account.address, agentPrice],
      { account: creator.account }
    );
    await shellToken.write.approve([ecosystem.address, agentPrice], {
      account: user.account,
    });
    await ecosystem.write.useAgent([1n], { account: user.account });

    // 创作者提取 75 SHELL 收益
    await ecosystem.write.withdrawRevenue({ account: creator.account });

    const remainingPending = await ecosystem.read.pendingWithdrawals([
      creator.account.address,
    ]);
    const creatorWalletBalance = await shellToken.read.balanceOf([
      creator.account.address,
    ]);

    assert.equal(remainingPending, 0n, "提现后待提取账本应清零");
    assert.equal(
      creatorWalletBalance,
      parseEther("75"),
      "创作者钱包应收到精确的 75 SHELL"
    );
  });
     it("权限与费率风控:仅管理员可调整费率且总抽成不得超过 50% 上限", async function () {
    const { ecosystem, owner, user } = await deployFixture();

    // 1. 非管理员调用 setFeeRates 应被 Ownable 拦截
    await assert.rejects(
      async () => {
        await ecosystem.write.setFeeRates([500n, 500n], {
          account: user.account,
        });
      },
      (err: any) => {
        const msg = `${err?.message || ""} ${err?.shortMessage || ""}`;
        return (
          msg.includes("OwnableUnauthorizedAccount") ||
          msg.includes("0x118cdaa7") ||
          msg.toLowerCase().includes("revert")
        );
      },
      "非管理员不应被允许修改费率"
    );

    // 2. 总抽成超过 50% (3000 + 2500 = 5500 > 5000) 应触发 FeeTooHigh
    await assert.rejects(
      async () => {
        await ecosystem.write.setFeeRates([3000n, 2500n], {
          account: owner.account,
        });
      },
      /FeeTooHigh/,
      "总抽成比例超过 50% 应触发 FeeTooHigh 错误"
    );

    // 3. 管理员在合法范围内调整费率应成功生效
    await ecosystem.write.setFeeRates([500n, 2000n], { account: owner.account });
    assert.equal(await ecosystem.read.platformFeeBps(), 500n);
    assert.equal(await ecosystem.read.modelFeeBps(), 2000n);
  });

});

写在最后

剥开所有产品包装与市场叙事,一个靠谱的去中心化 AI 生态协议,本质上就是一台精密的自动分账与风控状态机。把不留粉尘的算术逻辑、拉取式资金安全隔离以及不可逾越的费率红线写进代码,才算是给上层百花齐放的 AI Agent 铺好了真正能跑通商业闭环的铁轨。

相关推荐
Cooper251 天前
合约托管 + 验收释放:悬赏 DApp 的四态状态机与事件索引
web3·solidity
OxYGC2 天前
[Web3] 智能合约 04: 高级开发实战与 OpenZeppelin
web3·区块链·智能合约
笑容掩饰我的失落2 天前
区块链从小白到精通(七):Solidity 语法精讲——数据类型、函数、修饰器与事件
算法·区块链·php·智能合约·哈希算法
OxYGC2 天前
[Web3] 智能合约 03: 函数/事件/继承/接口/异常处理
web3·区块链·智能合约
笑容掩饰我的失落3 天前
区块链从小白到精通(八):从零实现一个标准 ERC-20 代币(完整可运行代码)
算法·区块链·php·智能合约·哈希算法
OxYGC3 天前
[Web3] 智能合约 02: Solidity 基础语法
web3·区块链·智能合约
OxYGC5 天前
[Web3] 基础第7篇: 说透比特币的基本框架与原理
web3·区块链·以太坊·比特币
混凝土拌意大利面5 天前
WEB3核心技术的一种实现:时间长河共识算法(TRC, Time-River Consensus)
web3·区块链·共识算法
OxYGC6 天前
[Web3] 基础第5篇: 共识算法与 P2P 通信协议
web3·区块链·以太坊·比特币