{"author":{"address":null,"user":"https://learnblockchain.cn/people/18158"},"content":{"body":"# 前言\r\n\r\n\u003e 本文主要介绍使用chainlink预言机中Data Feeds，全文包含了MockV3Aggregator合约和PriceConsumer合约的开发、测试、部署。`注意`：为了便于测试，在本地区块节点上部署一个MockV3Aggregator。\r\n\r\n# Chainlink(去中心化预言机)\r\n**Chainlink定义**：一个去中心化的预言机网络。它的主要作用是将区块链上的智能合约与现实世界的数据和事件连接起来；\u003cbr\u003e\r\n**Data Feeds（数据源）**：连接智能合约与现实世界数据的重要工具;\u003cbr\u003e\r\n**作用**：Chainlink Data Feeds通过提供高质量、安全可靠的外部数据，极大地扩展了智能合约的应用范围和功能；\r\n# 开发合约\r\n##### 本地部署MockV3Aggregator合约（便于本地测试使用）\r\n**说明**：`注意`\u003cbr\u003e \r\n1. chainlink的AggregatorV3Interface文件位置改变了；\r\n2. 本地部署变量声明和方法名要区分；\r\n3. 关于version方法把view修饰符改为pure\r\n```\r\n// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.20;\r\n\r\nimport { AggregatorV3Interface } from \"@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol\";\r\n\r\ncontract MockV3Aggregator is AggregatorV3Interface {\r\n    uint256 public constant versionvar = 4;\r\n\r\n    uint8 public decimalsvar;\r\n    int256 public latestAnswer;\r\n    uint256 public latestTimestamp;\r\n    uint256 public latestRound;\r\n    mapping(uint256 =\u003e int256) public getAnswer;\r\n    mapping(uint256 =\u003e uint256) public getTimestamp;\r\n    mapping(uint256 =\u003e uint256) private getStartedAt;\r\n    string private descriptionvar;\r\n\r\n    constructor(\r\n        uint8 _decimals,\r\n        string memory _description,\r\n        int256 _initialAnswer\r\n    ) {\r\n        decimalsvar = _decimals;\r\n        descriptionvar = _description;\r\n        updateAnswer(_initialAnswer);\r\n    }\r\n\r\n    function updateAnswer(int256 _answer) public {\r\n        latestAnswer = _answer;\r\n        latestTimestamp = block.timestamp;\r\n        latestRound++;\r\n        getAnswer[latestRound] = _answer;\r\n        getTimestamp[latestRound] = block.timestamp;\r\n        getStartedAt[latestRound] = block.timestamp;\r\n    }\r\n\r\n    function getRoundData(uint80 _roundId)\r\n        external\r\n        view\r\n        override\r\n        returns (\r\n            uint80 roundId,\r\n            int256 answer,\r\n            uint256 startedAt,\r\n            uint256 updatedAt,\r\n            uint80 answeredInRound\r\n        )\r\n    {\r\n        return (\r\n            _roundId,\r\n            getAnswer[_roundId],\r\n            getStartedAt[_roundId],\r\n            getTimestamp[_roundId],\r\n            _roundId\r\n        );\r\n    }\r\n\r\n    function latestRoundData()\r\n        external\r\n        view\r\n        override\r\n        returns (\r\n            uint80 roundId,\r\n            int256 answer,\r\n            uint256 startedAt,\r\n            uint256 updatedAt,\r\n            uint80 answeredInRound\r\n        )\r\n    {\r\n        return (\r\n            uint80(latestRound),\r\n            latestAnswer,\r\n            getStartedAt[latestRound],\r\n            latestTimestamp,\r\n            uint80(latestRound)\r\n        );\r\n    }\r\n\r\n    function decimals() external view override returns (uint8) {\r\n        return decimalsvar;\r\n    }\r\n\r\n    function description() external view override returns (string memory) {\r\n        return descriptionvar;\r\n    }\r\n\r\n    function version() external  pure override returns (uint256) {\r\n        return versionvar;\r\n    }\r\n}\r\n# 编译指令\r\n# npx hardhat compile\r\n```\r\n##### PriceConsumer合约\r\n```\r\n// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.20;\r\n\r\nimport {AggregatorV3Interface} from \"@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol\";\r\n\r\ncontract PriceConsumer {\r\n    AggregatorV3Interface internal priceFeed;\r\n\r\n    /**\r\n     * 网络: Sepolia\r\n     * 聚合器: ETH/USD\r\n     * 地址: 0x694AA1769357215DE4FAC081bf1f309aDC325306\r\n     */\r\n    constructor(address _priceFeed) {\r\n        priceFeed = AggregatorV3Interface(_priceFeed);\r\n    }\r\n\r\n    /**\r\n     * 返回最新价格\r\n     */\r\n    function getLatestPrice() public view returns (int) {\r\n        (\r\n            /* uint80 roundID */,\r\n            int price,\r\n            /*uint startedAt*/,\r\n            /*uint timeStamp*/,\r\n            /*uint80 answeredInRound*/\r\n        ) = priceFeed.latestRoundData();\r\n        return price;\r\n    }\r\n\r\n    /**\r\n     * 返回价格小数位数\r\n     */\r\n    function getDecimals() public view returns (uint8) {\r\n        return priceFeed.decimals();\r\n    }\r\n\r\n    /**\r\n     * 返回价格源描述\r\n     */ \r\n    function getDescription() public view returns (string memory) {\r\n        return priceFeed.description();\r\n    }\r\n}\r\n# 编译指令\r\n# npx hardhat compile\r\n```\r\n# 测试合约\r\n```\r\nconst { ethers } = require(\"hardhat\");\r\nconst { expect } = require(\"chai\");\r\nconst { loadFixture } = require(\"@nomicfoundation/hardhat-network-helpers\");\r\n\r\ndescribe(\"PriceConsumer\", function () {\r\n    // ETH/USD 价格配置\r\n    const DECIMALS = 8;\r\n    const INITIAL_PRICE = 200000000000; // $2000.00000000\r\n    const UPDATED_PRICE = 210000000000; // $2100.00000000\r\n    const DESCRIPTION = \"ETH/USD Price Feed\";\r\n\r\n    async function deployFixture() {\r\n        const [owner, addr1] = await ethers.getSigners();\r\n\r\n        // 部署模拟价格源\r\n        const MockV3Aggregator = await ethers.getContractFactory(\"MockV3Aggregator\");\r\n        const mockAggregator = await MockV3Aggregator.deploy(\r\n            DECIMALS,\r\n            DESCRIPTION,\r\n            INITIAL_PRICE\r\n        );\r\n\r\n        // 部署价格消费者合约\r\n        const PriceConsumer = await ethers.getContractFactory(\"PriceConsumer\");\r\n        const priceConsumer = await PriceConsumer.deploy(\r\n            await mockAggregator.getAddress()\r\n        );\r\n\r\n        return { mockAggregator, priceConsumer, owner, addr1 };\r\n    }\r\n\r\n    describe(\"初始化\", function () {\r\n        it(\"价格信息源地址\", async function () {\r\n            const { mockAggregator, priceConsumer } = await loadFixture(deployFixture);\r\n            expect(await priceConsumer.priceFeed()).to.equal(await mockAggregator.getAddress());\r\n        });\r\n\r\n        it(\"小数点位数\", async function () {\r\n            const { priceConsumer } = await loadFixture(deployFixture);\r\n            expect(await priceConsumer.getDecimals()).to.equal(DECIMALS);\r\n        });\r\n\r\n        it(\"返回正确的描述\", async function () {\r\n            const { priceConsumer } = await loadFixture(deployFixture);\r\n            expect(await priceConsumer.getDescription()).to.equal(DESCRIPTION);\r\n        });\r\n    });\r\n\r\n    describe(\"价格更新\", function () {\r\n        it(\"初始价格\", async function () {\r\n            const { priceConsumer } = await loadFixture(deployFixture);\r\n            expect(await priceConsumer.getLatestPrice()).to.equal(INITIAL_PRICE);\r\n        });\r\n\r\n        it(\"更新后的价格\", async function () {\r\n            const { mockAggregator, priceConsumer } = await loadFixture(deployFixture);\r\n            \r\n            await mockAggregator.updateAnswer(UPDATED_PRICE);\r\n            expect(await priceConsumer.getLatestPrice()).to.equal(UPDATED_PRICE);\r\n        });\r\n\r\n        it(\"处理多个价格更新\", async function () {\r\n            const { mockAggregator, priceConsumer } = await loadFixture(deployFixture);\r\n            \r\n            const prices = [\r\n                210000000000, // $2100\r\n                220000000000, // $2200\r\n                215000000000  // $2150\r\n            ];\r\n\r\n            for (const price of prices) {\r\n                await mockAggregator.updateAnswer(price);\r\n                expect(await priceConsumer.getLatestPrice()).to.equal(price);\r\n            }\r\n        });\r\n    });\r\n\r\n    describe(\"价格信息交互\", function () {\r\n        it(\"负价格的情况\", async function () {\r\n            const { mockAggregator, priceConsumer } = await loadFixture(deployFixture);\r\n            \r\n            const negativePrice = -100000000; // -$1\r\n            await mockAggregator.updateAnswer(negativePrice);\r\n            expect(await priceConsumer.getLatestPrice()).to.equal(negativePrice);\r\n        });\r\n\r\n        it(\"0价格的情况\", async function () {\r\n            const { mockAggregator, priceConsumer } = await loadFixture(deployFixture);\r\n            \r\n            await mockAggregator.updateAnswer(0);\r\n            expect(await priceConsumer.getLatestPrice()).to.equal(0);\r\n        });\r\n    });\r\n\r\n    describe(\"Gas费\", function () {\r\n        it(\"使用合理的气量（燃气量）进行价格查询\", async function () {\r\n            const { priceConsumer } = await loadFixture(deployFixture);\r\n            \r\n            const price = await priceConsumer.getLatestPrice();\r\n            expect(price).to.equal(INITIAL_PRICE);\r\n            \r\n            // 获取交易的gas使用量\r\n            const gasEstimate = await priceConsumer.getLatestPrice.estimateGas();\r\n            expect(gasEstimate).to.be.lt(50000);\r\n        });\r\n    });\r\n});\r\n# 测试指令\r\n# npx hardhat test ./test/xxx.js\r\n```\r\n# 部署合约\r\n#### MockV3Aggregator合约\r\n```\r\nmodule.exports = async ({ getNamedAccounts, deployments }) =\u003e {\r\n    const firstAccount=(await getNamedAccounts()).firstAccount;\r\n  const { deploy, log } = deployments\r\n  const MockV3Aggregator = await deploy(\"MockV3Aggregator\", {\r\n    contract: \"MockV3Aggregator\",\r\n    from: firstAccount,\r\n    log: true,\r\n    args: [8,\"ETH/USD\", 200000000000], // decimals, description, initial answer (2000 USD with 8 decimals) \r\n  })\r\n  console.log(\"MockV3Aggregator合约地址\",MockV3Aggregator.address)\r\n    \r\n}\r\nmodule.exports.tags = [\"all\", \"MockV3Aggregator\"]\r\n# 部署指令\r\n# npx hardhat deploy\r\n```\r\n#### PriceConsumer合约\r\n```\r\nmodule.exports = async ({ getNamedAccounts, deployments }) =\u003e {\r\n    const firstAccount=(await getNamedAccounts()).firstAccount;\r\n    const MockV3Aggregator=await deployments.get(\"MockV3Aggregator\");\r\n    const MockV3AggregatorAddress = MockV3Aggregator.address;\r\n    const { deploy, log } = deployments\r\n  const PriceConsumer = await deploy(\"PriceConsumer\", {\r\n    contract: \"PriceConsumer\",\r\n    from: firstAccount,\r\n    log: true,\r\n    args: [MockV3AggregatorAddress],//合约地址\r\n  })\r\n  console.log(\"PriceConsumer合约地址\",PriceConsumer.address)\r\n}\r\nmodule.exports.tags = [\"all\", \"PriceConsumer\"]\r\n# 部署指令\r\n# npx hardhat deploy\r\n```\r\n\r\n# 总结\r\n以上就是预言机中的数据流的智能合约的开发、测试、部署以及概念和作用的介绍；喂价主要场景的使用集中在代币之间的转换、结算；","title":"Chainlink预言机中的Data Feeds在智能合约中使用场景"},"history":null,"timestamp":1741151141,"version":1}