Xét ví dụ sau:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
 
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
 
// Why is this a library and not abstract?
// Why not an interface?
library PriceConverter {
    // We could make this public, but then we'd have to deploy it
    function getPrice() internal view returns (uint256) {
        // Sepolia ETH / USD Address
        // https://docs.chain.link/data-feeds/price-feeds/addresses
        AggregatorV3Interface priceFeed = AggregatorV3Interface(
            0x694AA1769357215DE4FAC081bf1f309aDC325306
        );
        (, int256 answer, , , ) = priceFeed.latestRoundData();
        // ETH/USD rate in 18 digit
        return uint256(answer * 10000000000);
    }
 
    // 1000000000
    function getConversionRate(
        uint256 ethAmount
    ) internal view returns (uint256) {
        uint256 ethPrice = getPrice();
        uint256 ethAmountInUsd = (ethPrice * ethAmount) / 1000000000000000000;
        // the actual ETH/USD conversion rate, after adjusting the extra 0s.
        return ethAmountInUsd;
    }
}

Để install AggregatorV3Interface.sol vào thư mục lib của project, ta cần chạy lệnh sau:

forge install smartcontractkit/chainlink-brownie-contracts@0.6.1 [--no-git] [--commit]

Với:

  • Đường dẫn của dependency có thể là URL, SSH URL hoặc path đến GitHub repo như trên.
  • --no-git là để không cài đặt package dưới dạng Git submodule.
  • --commit là để tự động tạo mới một commit sau khi install dependency.

Seealso

Chỉnh sửa foundry.toml bằng cách thêm dòng sau để mapping thư viện trong contract với đường dẫn tương đối của nó:

remappings = ['@chainlink/contracts/=lib/chainlink-brownie-contracts/contracts/']

Resources