普通视图

发现新文章,点击刷新页面。
昨天 — 2026年3月17日首页

Energy-Fi:基于 DePIN 的能源资产化协议设计与实现

作者 木西
2026年3月17日 13:30

前言

在 2026 年的 Web3 版图中,纯粹的"小圆盘"博彩模式已逐渐式微,取而代之的是拥有真实物理底座的 Energy-Fi。该协议将 GambleFi 的"赔率博弈"与现实世界的"电网负荷"相结合,创造了一种全新的能源资产化交易模式。

本文将完整复盘一套 Energy-Fi 协议 从合约架构到算法治理,再到集成测试的全流程实现。该协议基于 Solidity 0.8.24,采用 OpenZeppelin V5 标准,核心聚焦于硬件授权算法定价资产联动三大支柱。

一、核心架构:从物理电表到链上结算

Energy-Fi 的核心挑战在于数据真实性验证。我们采用 DePIN(去中心化物理基础设施) 模式,通过硬件认证确保每一度电、每一次负荷波动均为真实数据上链。

三层架构设计

层级 组件 技术实现 核心职责
资产层 ENT 代币 + GCC NFT OpenZeppelin V5 ERC20/ERC721 能源结算与碳信用资产化
数据层 Chainlink Functions 去中心化预言机网络 实时抽取物理电网负荷数据
逻辑层 Algorithmic Pricing DAO 治理的智能合约 将定价权从中心化机构移交至算法

二、 硬核代码实现:算法定价与安全断路器

2.1 动态调价算法

采用超额累进定价模型。当电网负荷(Lcurrent )超过额定值(Ltarget )时,价格随系数动态漂移:

Price=Pbase×(1+Ltarget×100Multiplier×(Lcurrent−Ltarget))

参数说明:

  • Pbase :基础电价(100 单位)
  • Multiplier :负荷敏感系数(50)
  • Ltarget :额定负荷(1000 MW)

2.2 安全断路器(Circuit Breaker)

为防止预言机遭受攻击(如物理 API 劫持),合约内置价格偏离检测机制。当新旧价格波动超过设定阈值(如 30%),系统自动触发 _pause() 进入熔断状态。

2.3 核心合约代码

A.能源代币合约(ENT)
// SPDX-License-Identifier: MIT
// Compatible with OpenZeppelin Contracts ^5.5.0
pragma solidity ^0.8.24;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract BoykaYuriToken is ERC20, ERC20Burnable, Ownable, ERC20Permit {
    constructor(address recipient, address initialOwner)
        ERC20("MyToken", "MTK")
        Ownable(initialOwner)
        ERC20Permit("MyToken")
    {
        _mint(recipient, 1000000 * 10 ** decimals());
    }
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }
}
B. 碳信用 NFT 合约(GCC)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract GreenCarbonNFT is ERC721, Ownable {
    error AlreadyOffset(uint256 tokenId);

    struct CarbonData { uint256 amountKG; bool isOffset; }
    mapping(uint256 => CarbonData) public carbonRegistry;
    uint256 private _nextTokenId;

    constructor(address initialOwner) ERC721("GreenCarbon", "GCC") Ownable(initialOwner) {}

    function mintCarbonCredit(address to, uint256, uint256 kgAmount) external onlyOwner {
        uint256 tokenId = _nextTokenId++;
        _safeMint(to, tokenId);
        carbonRegistry[tokenId] = CarbonData(kgAmount, false);
    }
}
C. 算法定价合约
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract AlgorithmicEnergyPricing is Ownable {
    uint256 public basePrice = 100;      // 基础价
    uint256 public loadMultiplier = 50;  // 影响系数
    uint256 public targetLoad = 1000;    // 额定负荷 (MW)
    uint256 public lastReportedLoad;

    constructor(address initialOwner) Ownable(initialOwner) {}

    function updateLoadFromOracle(uint256 _load) external onlyOwner {
        lastReportedLoad = _load;
    }

    function getCurrentPrice() public view returns (uint256) {
        if (lastReportedLoad <= targetLoad) return basePrice;
        // 公式:Price = base * (1 + (M * (L - T) / T) / 100)
        uint256 excessLoad = lastReportedLoad - targetLoad;
        uint256 dynamicPart = (loadMultiplier * excessLoad) / targetLoad;
        return basePrice + (basePrice * dynamicPart / 100);
    }
}
D. 能源市场合约
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract GreenEnergyMarket is Pausable, Ownable {
    error UnauthorizedDevice(address device);
    error PriceAnomalyDetected(uint256 price);

    IERC20 public energyToken;
    mapping(address => bool) public authorizedDevices;
    
    struct Offer { address provider; uint256 amountKWh; uint256 price; bool active; }
    mapping(uint256 => Offer) public offers;
    uint256 public nextOfferId;

    constructor(address _token, address initialOwner) Ownable(initialOwner) {
        energyToken = IERC20(_token);
    }

    // 硬件授权:仅限通过认证的智能电表
    function authorizeDevice(address _device) external onlyOwner {
        authorizedDevices[_device] = true;
    }

    // 上链发电数据 (由 IOT 设备调用)
    function recordProduction(address _provider, uint256 _amount) external {
        if (!authorizedDevices[msg.sender]) revert UnauthorizedDevice(msg.sender);
        // 此处可触发 NFT 铸造逻辑
    }

    // 发布卖单
    function createOffer(uint256 _amount, uint256 _price, uint256) external whenNotPaused {
        offers[nextOfferId++] = Offer(msg.sender, _amount, _price, true);
    }

    // 购买能源
    function buyEnergy(uint256 _offerId) external whenNotPaused {
        Offer storage offer = offers[_offerId];
        uint256 totalCost = offer.amountKWh * offer.price;
        offer.active = false;
        energyToken.transferFrom(msg.sender, offer.provider, totalCost);
    }

    // 安全断路器:模拟价格异常检测
    function updatePriceSafe(uint256 _newPrice) external onlyOwner {
        if (_newPrice > 500) { // 模拟极端波动阈值
            _pause();
            revert PriceAnomalyDetected(_newPrice);
        }
    }
}

三、 集成测试:Viem + Node:test 实战复盘

测试用例:Energy-Fi Protocol Full Integration

  • 算法定价:电价应随电网负荷动态调整
  • 产出上链:授权 IOT 设备应能记录发电量并触发 NFT 铸造逻辑
  • 能源交易:用户应能利用代币购买发布的能源订单
  • 权限拦截:未经授权的设备无法上链发电数据
  • 安全断路器:极端价格波动应导致市场暂停
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { parseEther, getAddress, zeroAddress, encodeFunctionData ,keccak256} from "viem";
import { network } from "hardhat";

describe("Energy-Fi Protocol Full Integration", function () {
  
  async function deployFixture() {
    const { viem } = await (network as any).connect();
    const [admin, user, iotDevice] = await viem.getWalletClients();
    const publicClient = await viem.getPublicClient();

    // 1. 部署核心合约
    // 部署能源代币 (ENT)
    const energyToken = await viem.deployContract("BoykaYuriToken", [admin.account.address, admin.account.address]);
    // 部署碳信用 NFT (GCC)
    const carbonNFT = await viem.deployContract("GreenCarbonNFT", [admin.account.address]);
    // 部署算法定价逻辑
    const pricingLogic = await viem.deployContract("AlgorithmicEnergyPricing", [admin.account.address]);
    // 部署能源市场
    const market = await viem.deployContract("GreenEnergyMarket", [energyToken.address, admin.account.address]);

    // 2. 初始化配置
    const ACCESS_MANAGER_ROLE = keccak256("DEPIN_DEVICE_ROLE"); // 假设合约中定义的角色
    // 模拟授权 IOT 设备权限
    await market.write.authorizeDevice([iotDevice.account.address], { account: admin.account });

    return {
      energyToken, carbonNFT, pricingLogic, market,
      admin, user, iotDevice,
      publicClient
    };
  }

it("算法定价:电价应随电网负荷动态调整", async function () {
    const { pricingLogic } = await deployFixture();

    const currentLoad = 1200n;
    const targetLoad = 1000n;
    const basePrice = 100n;
    const multiplier = 50n;

    await pricingLogic.write.updateLoadFromOracle([currentLoad]);
    
    // 修正脚本中的计算逻辑以匹配合约:
    const excessLoad = currentLoad - targetLoad; // 200
    const dynamicPart = (multiplier * excessLoad) / targetLoad; // 10
    const expectedPrice = basePrice + (basePrice * dynamicPart / 100n); // 110
    
    const currentPrice = await pricingLogic.read.getCurrentPrice();
    assert.equal(currentPrice, expectedPrice, "动态定价算法计算不准确"); // 现在应该匹配 110n
});
  it("产出上链:授权 IOT 设备应能记录发电量并触发 NFT 铸造逻辑", async function () {
    const { market, carbonNFT, iotDevice, user } = await deployFixture();
    
    const producedKWh = 1500n; // 产生 1500 度电
    
    // IOT 设备上链数据
    await market.write.recordProduction([user.account.address, producedKWh], {
      account: iotDevice.account,
    });

    // 验证:由于超过 1000kWh,应自动通过 AccessControl 调用 NFT 铸造 (模拟逻辑)
    // 注意:实际生产环境中需在 market 合约中 link carbonNFT 的 mint 函数
    await carbonNFT.write.mintCarbonCredit([user.account.address, 1n, 1500n]); // 手动模拟触发
    
    const nftBalance = await carbonNFT.read.balanceOf([user.account.address]);
    assert.equal(nftBalance, 1n, "达到减排标准后未正确铸造碳信用 NFT");
  });

  it("能源交易:用户应能利用代币购买发布的能源订单", async function () {
    const { market, energyToken, admin, user } = await deployFixture();
    const amountKWh = 100n;
    const pricePerKWh = 2n;

    // 1. admin 发布能源卖单
    await market.write.createOffer([amountKWh, pricePerKWh, 3600n], { account: admin.account });

    // 2. 给 user 发放 ENT 代币并授权
    const totalCost = amountKWh * pricePerKWh;
    await energyToken.write.transfer([user.account.address, totalCost], { account: admin.account });
    await energyToken.write.approve([market.address, totalCost], { account: user.account });

    // 3. user 购买能源
    await market.write.buyEnergy([0n], { account: user.account });

    // 4. 验证资金转移
    const adminBalance = await energyToken.read.balanceOf([admin.account.address]);
    assert.ok(adminBalance >= totalCost, "能源交易结算资金未正确到账");
  });

  it("权限拦截:未经授权的设备无法上链发电数据", async function () {
    const { market, user } = await deployFixture();

    await assert.rejects(
      async () => {
        await market.write.recordProduction([user.account.address, 100n], {
          account: user.account, // user 不是授权的 IOT 设备
        });
      },
      /UnauthorizedDevice/,
      "非授权设备非法上链数据未被拦截"
    );
  });

  it("安全断路器:极端价格波动应导致市场暂停", async function () {
    const { market, admin } = await deployFixture();

    // 模拟市场合约具备 Pausable 功能
    // 故意注入极端异常电价(波动率 > 30%)
    // 此处调用假设的校验接口
    await assert.rejects(
      async () => {
        await market.write.updatePriceSafe([1000n], { account: admin.account }); 
      },
      /PriceAnomalyDetected/
    );
  });
});

四、部署脚本

// scripts/deploy.js
import { network, artifacts } from "hardhat";
async function main() {
  // 连接网络
  const { viem } = await network.connect({ network: network.name });//指定网络进行链接
  
  // 获取客户端
  const [deployer] = await viem.getWalletClients();
  const publicClient = await viem.getPublicClient();
 
  const deployerAddress = deployer.account.address;
   console.log("部署者的地址:", deployerAddress);
  // 加载合约
  const BoykaYuriTokenArtifact = await artifacts.readArtifact("BoykaYuriToken");
  const GreenCarbonNFTArtifact = await artifacts.readArtifact("GreenCarbonNFT");
  const AlgorithmicEnergyPricingArtifact = await artifacts.readArtifact("AlgorithmicEnergyPricing");
  const GreenEnergyMarketArtifact = await artifacts.readArtifact("GreenEnergyMarket");
 
  // 部署(构造函数参数:recipient, initialOwner)
  const BoykaYuriTokenHash = await deployer.deployContract({
    abi: BoykaYuriTokenArtifact.abi,//获取abi
    bytecode: BoykaYuriTokenArtifact.bytecode,//硬编码
    args: [deployerAddress,deployerAddress],//部署者地址,初始所有者地址
  });
   const BoykaYuriTokenReceipt = await publicClient.waitForTransactionReceipt({ hash: BoykaYuriTokenHash });
   console.log("代币合约地址:", BoykaYuriTokenReceipt.contractAddress);
//
const GreenCarbonNFTHash = await deployer.deployContract({
    abi: GreenCarbonNFTArtifact.abi,//获取abi
    bytecode: GreenCarbonNFTArtifact.bytecode,//硬编码
    args: [deployerAddress],//部署者地址,初始所有者地址
  });
  // 等待确认并打印地址
  const GreenCarbonNFTReceipt = await publicClient.waitForTransactionReceipt({ hash: GreenCarbonNFTHash });
  console.log("绿色碳证合约地址:", GreenCarbonNFTReceipt.contractAddress);
  const AlgorithmicEnergyPricingHash = await deployer.deployContract({
    abi: AlgorithmicEnergyPricingArtifact.abi,//获取abi
    bytecode: AlgorithmicEnergyPricingArtifact.bytecode,//硬编码
    args: [deployerAddress],//部署者地址,初始所有者地址
  });
  // 等待确认并打印地址
  const AlgorithmicEnergyPricingReceipt = await publicClient.waitForTransactionReceipt({ hash: AlgorithmicEnergyPricingHash });
  console.log("算法能源定价合约地址:", AlgorithmicEnergyPricingReceipt.contractAddress);
  const GreenEnergyMarketHash = await deployer.deployContract({
    abi: GreenEnergyMarketArtifact.abi,//获取abi
    bytecode: GreenEnergyMarketArtifact.bytecode,//硬编码
    args: [BoykaYuriTokenReceipt.contractAddress,deployerAddress],//部署者地址,初始所有者地址
  });
  // 等待确认并打印地址
  const GreenEnergyMarketReceipt = await publicClient.waitForTransactionReceipt({ hash: GreenEnergyMarketHash });
  console.log("绿色能源市场合约地址:", GreenEnergyMarketReceipt.contractAddress);
}

main().catch(console.error);

五、风险提示与未来展望

当前风险

风险类型 描述 缓解方案
预言机延迟 物理数据上链延迟可能导致套利窗口 采用 Chainlink Functions + 多节点共识
硬件安全 物理电表被破解产生虚假产出 TEE 可信执行环境 + 设备信誉系统
价格波动 极端行情下的流动性枯竭 动态熔断机制 + 保险池设计
监管合规 能源交易涉及特许经营许可 渐进式去中心化,预留合规接口

未来演进

  1. DAO 治理过渡:将 onlyOwner 权限逐步迁移至 Governor 合约
  2. 跨链结算:通过 LayerZero 实现多链能源资产流通
  3. AI 预测市场:引入机器学习模型预测负荷,开启预测性交易
  4. 物理交割:与电网运营商合作,实现链上结算-物理交割闭环

总结

本文完整呈现了一套基于 DePIN + 算法定价 的 Energy-Fi 协议实现。通过 OpenZeppelin V5 的安全基座、Chainlink 的数据桥接、以及 Solidity 0.8.24 的现代化语法,构建了一个具备硬件认证、动态定价、熔断保护的去中心化能源市场。

该架构不仅适用于电力交易,更可扩展至碳排放权、水资源、带宽等一切可量化的物理资源,成为连接 Web3 与现实世界基础设施的关键协议层。

昨天以前首页

深度解析 AgentFi:基于 ERC-6551 与 AI 驱动的 DeFi 进化论

作者 木西
2026年3月16日 16:54

前言

在传统的 DeFi 生态中,用户往往需要手动操作或依赖中心化的机器人(Bot)来管理资产。AgentFi(代理金融)的出现,标志着资产管理从“自动化”向“智能化”的范式转移。它通过 ERC-6551 (Token Bound Accounts)  标准,赋予 NFT 独立的链上账户能力,使其进化为可以自主决策、自动捕获收益的 AI 智能体 (AI Agents)

补充说明:如果对ERC6551标准不了解,可以配合往期作品《拒绝NFT只好看!用代码给NFT装【独立账号】:ERC6551开发实战》

一、 业务逻辑:NFT 即智能体

AgentFi 的核心逻辑可以拆解为四个关键维度:

  1. 身份与账户绑定 (TBA) :通过 ERC-6551,每一个 NFT 不再仅仅是小图片,而是一个功能完备的智能合约钱包。
  2. 资产托管与策略封装:资产不存放在协议池,而是存放在 NFT 绑定的账户中。策略(如循环贷、流动性管理)直接在账户内执行。
  3. 原生收益捕获 (以 Blast 为例) :利用 Blast 等网络的 Rebase 机制,智能体账户能自动赚取 ETH 和稳定币的基础利息。
  4. 可交易的策略仓位:用户可以在二级市场交易这些 NFT。买家买到的不仅是所有权,还有该智能体持有的资产及其正在运行的获利策略。

二、 核心架构实现

AgentFi 的系统架构由 Registry(注册表)Proxy(代理层)  和 Implementation(逻辑层)  组成。

1. AgentNFT.sol (NFT 身份合约)

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract AgentNFT is ERC721, Ownable {
    uint256 private _nextTokenId;

    constructor() ERC721("AgentFi Bot", "AFIB") Ownable(msg.sender) {}

    // 用户铸造一个 Agent 智能体
    function mintAgent() public returns (uint256) {
        uint256 tokenId = _nextTokenId++;
        _safeMint(msg.sender, tokenId);
        return tokenId;
    }
}

2. AgentAccount.sol (TBA 策略执行合约)

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // 必须导入以使用 ownerOf

// 1. 将接口移出合约外部
interface IERC6551Account {
    function owner() external view returns (address);
    function token() external view returns (uint256 chainId, address tokenContract, uint256 tokenId);
}

// 模拟 DeFi 协议接口
interface ILendingPool {
    function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
}

contract AgentAccount is IERC6551Account {
    
    // 执行策略:自动将账户内的余额存入借贷协议获取收益
    function executeStrategy(address pool, address asset) external {
        // 只有 NFT 的持有者可以触发策略
        require(msg.sender == owner(), "Not authorized");

        uint256 balance = IERC20(asset).balanceOf(address(this));
        require(balance > 0, "No funds to deploy");

        // 授权并存入
        IERC20(asset).approve(pool, balance);
        ILendingPool(pool).deposit(asset, balance, address(this), 0);
    }

    // ERC-6551 标准必需函数:查询谁拥有这个智能体
    function owner() public view override returns (address) {
        (uint256 chainId, address tokenContract, uint256 tokenId) = token();
        if (chainId != block.chainid) return address(0);
        // 使用 OpenZeppelin 的 IERC721 接口
        return IERC721(tokenContract).ownerOf(tokenId);
    }

    function token() public view override returns (uint256, address, uint256) {
        // 简化演示:此处硬编码。实际开发中建议通过构造函数或 Immutable Args 传入。
        return (block.chainid, 0x5FbDB2315678afecb367f032d93F642f64180aa3, 1); 
    }

    // 允许接收 ETH
    receive() external payable {}
}

3.ERC-6551 Registry 合约实现

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/utils/Create2.sol";

// --- 1. 定义代理合约 (必须存在,否则 Registry 无法获取其 creationCode) ---
contract AgentProxy {
    // 代理合约通常非常简单:存储逻辑地址并转发调用
    address public immutable implementation;

    constructor(address _implementation, uint256, uint256, address, uint256) {
        implementation = _implementation;
    }

    // 转发所有调用到逻辑合约
    fallback() external payable {
        address _impl = implementation;
        assembly {
            calldatacopy(0, 0, calldatasize())
            let result := delegatecall(gas(), _impl, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch result
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }

    receive() external payable {}
}

// --- 2. 注册表接口 ---
interface IERC6551Registry {
    event ERC6551AccountCreated(
        address account,
        address indexed implementation,
        uint256 salt,
        uint256 chainId,
        address indexed tokenContract,
        uint256 indexed tokenId
    );

    function createAccount(
        address implementation,
        uint256 salt,
        uint256 chainId,
        address tokenContract,
        uint256 tokenId
    ) external returns (address);

    function account(
        address implementation,
        uint256 salt,
        uint256 chainId,
        address tokenContract,
        uint256 tokenId
    ) external view returns (address);
}

// --- 3. 注册表实现 ---
contract AgentRegistry is IERC6551Registry {
    function createAccount(
        address implementation,
        uint256 salt,
        uint256 chainId,
        address tokenContract,
        uint256 tokenId
    ) external returns (address) {
        bytes memory code = _creationCode(implementation, salt, chainId, tokenContract, tokenId);
        
        address _account = Create2.computeAddress(bytes32(salt), keccak256(code));
        
        // 如果已部署则直接返回
        if (_account.code.length > 0) return _account;

        // 部署代理合约
        _account = Create2.deploy(0, bytes32(salt), code);

        emit ERC6551AccountCreated(_account, implementation, salt, chainId, tokenContract, tokenId);
        return _account;
    }

    function account(
        address implementation,
        uint256 salt,
        uint256 chainId,
        address tokenContract,
        uint256 tokenId
    ) external view returns (address) {
        bytes memory code = _creationCode(implementation, salt, chainId, tokenContract, tokenId);
        return Create2.computeAddress(bytes32(salt), keccak256(code));
    }

    function _creationCode(
        address implementation,
        uint256 salt,
        uint256 chainId,
        address tokenContract,
        uint256 tokenId
    ) internal pure returns (bytes memory) {
        // 使用 abi.encodePacked 将 Proxy 的字节码与构造函数参数拼接
        return abi.encodePacked(
            type(AgentProxy).creationCode,
            abi.encode(implementation, salt, chainId, tokenContract, tokenId)
        );
    }
}

4.Blast 收益处理逻辑合约 (AgentImplementation.sol)

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24; // Blast 建议使用 0.8.24+ 以支持某些操作码

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";

// Blast 官方收益接口
interface IBlast {
    // 配置收益模式:0 = 被动, 1 = 自动复利(Automatic), 2 = 认领模式(Claimable)
    function configureClaimableYield() external;
    function configureAutomaticYield() external;
    function configureGovernor(address _governor) external;
}

interface IERC721 {
    function ownerOf(uint256 tokenId) external view returns (address);
}

contract AgentImplementation is Initializable {
    // Blast 系统合约固定地址
    IBlast public constant BLAST = IBlast(0x4300000000000000000000000000000000000002);
    
    // ERC-6551 账户元数据(通常在代理合约中,这里模拟读取)
    address public tokenContract;
    uint256 public tokenId;

    // 只有 NFT 持有者可以调用
    modifier onlyTokenOwner() {
        require(msg.sender == IERC721(tokenContract).ownerOf(tokenId), "Not Agent Owner");
        _;
    }

    /// @notice 初始化函数,由 Registry 部署代理后立即调用
    function initialize(address _tokenContract, uint256 _tokenId) public initializer {
        tokenContract = _tokenContract;
        tokenId = _tokenId;

        // 核心步骤:激活 Blast 原生收益
        // 这样存入这个 Agent 账户的 ETH 就会自动产生 4%+ 的利息
        if (block.chainid == 81457 || block.chainid == 168587773) { // Blast 主网或测试网
            BLAST.configureAutomaticYield(); 
            BLAST.configureGovernor(msg.sender); // 让 NFT 持有者管理收益设置
        }
    }

    /// @notice 业务逻辑:将账户内的资金投入外部协议(如去中心化交易所)
    /// @param target 外部协议地址
    /// @param data 交互的编码数据
    function executeStrategy(address target, bytes calldata data) 
        external 
        onlyTokenOwner 
        returns (bytes memory) 
    {
        // 这里的逻辑代表 Agent 正在根据“策略”操作资金
        (bool success, bytes memory result) = target.call(data);
        require(success, "Strategy execution failed");
        return result;
    }

    /// @notice 提取收益或本金
    function withdraw(address asset, uint256 amount) external onlyTokenOwner {
        if (asset == address(0)) {
            payable(msg.sender).transfer(amount);
        } else {
            IERC20(asset).transfer(msg.sender, amount);
        }
    }

    // 必须能够接收 ETH 才能获取 Blast 的原生收益
    receive() external payable {}
}

5.ERC20代币

// SPDX-License-Identifier: MIT
// Compatible with OpenZeppelin Contracts ^5.5.0
pragma solidity ^0.8.24;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract BoykaYuriToken is ERC20, ERC20Burnable, Ownable, ERC20Permit {
    constructor(address recipient, address initialOwner)
        ERC20("MyToken", "MTK")
        Ownable(initialOwner)
        ERC20Permit("MyToken")
    {
        _mint(recipient, 1000000 * 10 ** decimals());
    }
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }
}

三、 集成测试:验证智能体的自主性

测试用例

  • 初始化验证:Agent 账户应正确绑定 NFT 身份并开启 Blast 配置
  • 资产流动性:Agent 账户应能接收 ETH 并在持有者授权下转出
  • 策略执行:Agent 应能操作 ERC20 代币(模拟 USDB 收益)
  • 权限拦截:非 NFT 持有者无法调用 executeStrategy 或 withdraw
  • 所有权动态转移:NFT 卖出后,新持有者自动获得 Agent 资金控制权
import assert from "node:assert/strict";
import { describe, it, beforeEach } from "node:test";
import { parseEther, encodeFunctionData, zeroAddress, getAddress } from "viem";
import { network } from "hardhat";

describe("AgentFi Protocol Full Integration", function () {
  async function deployFixture() {
    const { viem } = await (network as any).connect();
    const [owner, otherAccount] = await viem.getWalletClients();
    const publicClient = await viem.getPublicClient();

    // 1. 部署基础合约
    const nft = await viem.deployContract("AgentNFT");
    const registry = await viem.deployContract("AgentRegistry");
    const implementation = await viem.deployContract("AgentImplementation");
    // 模拟一个 ERC20 代币用于策略测试
    const mockUSDB = await viem.deployContract("BoykaYuriToken", [owner.account.address, owner.account.address]);

    const salt = 0n;
    const chainId = BigInt(await publicClient.getChainId());
    const tokenId = 0n; // 第一个 mint 的 ID

    // 2. 铸造 Agent NFT
    await nft.write.mintAgent({ account: owner.account });

    // 3. 计算并预部署 TBA (Token Bound Account)
    const tbaAddress = await registry.read.account([
        implementation.address, 
        salt, 
        chainId, 
        nft.address, 
        tokenId
    ]);

    // 4. 部署账户合约
    await registry.write.createAccount([
        implementation.address, 
        salt, 
        chainId, 
        nft.address, 
        tokenId
    ]);

    const tbaContract = await viem.getContractAt("AgentImplementation", tbaAddress);

    // 5. 初始化 Agent (配置 Blast 收益模式等)
    await tbaContract.write.initialize([nft.address, tokenId], { account: owner.account });

    return { 
        nft, registry, implementation, mockUSDB, 
        owner, otherAccount, publicClient, 
        tbaAddress, tbaContract, tokenId, chainId, salt 
    };
  }

  it("初始化验证:Agent 账户应正确绑定 NFT 身份并开启 Blast 配置", async function () {
    const { tbaContract, nft, tokenId } = await deployFixture();
    
    const boundNFT = await tbaContract.read.tokenContract();
    const boundID = await tbaContract.read.tokenId();

    assert.equal(getAddress(boundNFT), getAddress(nft.address), "绑定的 NFT 地址不匹配");
    assert.equal(boundID, tokenId, "绑定的 TokenID 不匹配");
  });

  it("资产流动性:Agent 账户应能接收 ETH 并在持有者授权下转出", async function () {
    const { tbaAddress, tbaContract, otherAccount, publicClient } = await deployFixture();
    const amount = parseEther("1");

    // 外部用户向 Agent 转账
    await otherAccount.sendTransaction({ to: tbaAddress, value: amount });
    assert.equal(await publicClient.getBalance({ address: tbaAddress }), amount);

    // NFT 持有者指挥 Agent 将 ETH 转回
    const beforeBalance = await publicClient.getBalance({ address: otherAccount.account.address });
    await tbaContract.write.withdraw([zeroAddress, amount], { account: (await deployFixture()).owner.account });

    assert.equal(await publicClient.getBalance({ address: tbaAddress }), 0n);
  });

  it("策略执行:Agent 应能操作 ERC20 代币(模拟 USDB 收益)", async function () {
    const { tbaAddress, tbaContract, mockUSDB, owner } = await deployFixture();
    const amount = parseEther("100");

    // 给 Agent 发放 USDB
    await mockUSDB.write.transfer([tbaAddress, amount]);

    // 模拟策略:通过 executeStrategy 接口调用 ERC20 transfer
    const transferData = encodeFunctionData({
      abi: mockUSDB.abi,
      functionName: "transfer",
      args: [owner.account.address, amount],
    });

    await tbaContract.write.executeStrategy([mockUSDB.address, transferData], {
      account: owner.account,
    });

    assert.equal(await mockUSDB.read.balanceOf([tbaAddress]), 0n, "策略执行后代币应已转出");
  });

  it("权限拦截:非 NFT 持有者无法调用 executeStrategy 或 withdraw", async function () {
    const { tbaContract, otherAccount } = await deployFixture();

    // 尝试越权提取
    await assert.rejects(
      async () => {
        await tbaContract.write.withdraw([zeroAddress, 1n], {
          account: otherAccount.account,
        });
      },
      /Not Agent Owner/,
      "非所有者不应被允许提取资金"
    );
  });

  it("所有权动态转移:NFT 卖出后,新持有者自动获得 Agent 资金控制权", async function () {
    const { nft, tbaContract, owner, otherAccount, tokenId } = await deployFixture();

    // 1. 转移 NFT
    await nft.write.transferFrom([owner.account.address, otherAccount.account.address, tokenId]);

    // 2. 旧持有者(owner)尝试操作,应该失败
    await assert.rejects(
      async () => {
        await tbaContract.write.withdraw([zeroAddress, 0n], { account: owner.account });
      },
      /Not Agent Owner/
    );

    // 3. 新持有者(otherAccount)尝试操作,应该成功
    const tx = await tbaContract.write.withdraw([zeroAddress, 0n], {
      account: otherAccount.account,
    });
    assert.ok(tx, "新持有者应能成功发起交易");
  });
});

四、 部署脚本

// scripts/deploy.js
import { network, artifacts } from "hardhat";
async function main() {
  // 连接网络
  const { viem } = await network.connect({ network: network.name });//指定网络进行链接
  
  // 获取客户端
  const [deployer] = await viem.getWalletClients();
  const publicClient = await viem.getPublicClient();
 
  const deployerAddress = deployer.account.address;
   console.log("部署者的地址:", deployerAddress);
  // 加载合约
  const BoykaYuriTokenArtifact = await artifacts.readArtifact("BoykaYuriToken");
  const AgentNFTArtifact = await artifacts.readArtifact("AgentNFT");
  const AgentRegistryArtifact = await artifacts.readArtifact("AgentRegistry");
  const AgentImplementationArtifact = await artifacts.readArtifact("AgentImplementation");
  // 部署(构造函数参数:recipient, initialOwner)
  const BoykaYuriTokenHash = await deployer.deployContract({
    abi: BoykaYuriTokenArtifact.abi,//获取abi
    bytecode: BoykaYuriTokenArtifact.bytecode,//硬编码
    args: [deployerAddress,deployerAddress],//process.env.RECIPIENT, process.env.OWNER
  });

  // 等待确认并打印地址
  const BoykaYuriTokenReceipt = await publicClient.waitForTransactionReceipt({ hash: BoykaYuriTokenHash });
  console.log("BoykaYuriToken合约地址:", BoykaYuriTokenReceipt.contractAddress);
  const AgentNFTHash = await deployer.deployContract({
    abi: AgentNFTArtifact.abi,//获取abi
    bytecode: AgentNFTArtifact.bytecode,//硬编码
    args: [],//process.env.RECIPIENT, process.env.OWNER
  });
    const AgentNFTReceipt = await publicClient.waitForTransactionReceipt({ hash: AgentNFTHash });
    console.log("AgentNFT合约地址:", AgentNFTReceipt.contractAddress);
    const AgentRegistryHash = await deployer.deployContract({   
      abi: AgentRegistryArtifact.abi,//获取abi
      bytecode: AgentRegistryArtifact.bytecode,//硬编码
      args: [],//process.env.RECIPIENT, process.env.OWNER
    });
    const AgentRegistryReceipt = await publicClient.waitForTransactionReceipt({ hash: AgentRegistryHash });
    console.log("AgentRegistry合约地址:", AgentRegistryReceipt.contractAddress);
    const AgentImplementationHash = await deployer.deployContract({ 
        abi: AgentImplementationArtifact.abi,//获取abi
        bytecode: AgentImplementationArtifact.bytecode,//硬编码
        args: [],//process.env.RECIPIENT, process.env.OWNER
    });
    const AgentImplementationReceipt = await publicClient.waitForTransactionReceipt({ hash: AgentImplementationHash });
    console.log("AgentImplementation合约地址:", AgentImplementationReceipt.contractAddress);
}

main().catch(console.error);

五、 总结与展望

AgentFi 不仅仅是 DeFi 的一个分支,它是  “意图中心(Intent-centric)”  架构的终极形态。通过这种架构:

  • 对于用户:无需关注底层的 Swap 或 LP 路径,只需持有 NFT 即可享受 AI 优化的收益。
  • 对于开发者:可以编写更复杂的链上逻辑,将 AI 模型预测的结果直接推送到 TBA 账户执行。

AgentFi 的未来在于 跨链互操作性 与 链上 AI 推理 (On-chain Inference)  的结合。当智能体能够跨越链的限制寻找最佳利息,并实时调整风险参数时,真正的去中心化资产管理时代才算真正开启。

❌
❌