3分钟Solidity: 6.2 import 跨文件引用

28 阅读1分钟

欢迎订阅专栏3分钟Solidity--智能合约--Web3区块链技术必学

如需获取本内容的最新版本,请参见 Cyfrin.io 上的Import(代码示例)

你可以在Solidity中导入本地和外部文件。

本地

这是我们的文件夹结构。

├── Import.sol
└── Foo.sol

Foo.sol

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

struct Point {
    uint256 x;
    uint256 y;
}

error Unauthorized(address caller);

function add(uint256 x, uint256 y) pure returns (uint256) {
    return x + y;
}

contract Foo {
    string public name = "Foo";
}

Remix Lite 尝试一下

solidity-import

Import.sol

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

// 从当前目录导入 Foo.sol
import "./Foo.sol";

// 从“文件名”导入 {symbol1 作为别名, symbol2};
import {Unauthorized, add as func, Point} from "./Foo.sol";

contract Import {
    // 初始化 Foo.sol
    Foo public foo = new Foo();

    通过获取其名称来测试 Foo.sol。
    function getFooName() public view returns (string memory) {
        return foo.name();
    }
}

Remix Lite 尝试一下

solidity-import2

External

你也可以通过复制 URL 从 GitHub导入

// https://github.com/owner/repo/blob/branch/path/to/Contract.sol
import "https://github.com/owner/repo/blob/branch/path/to/Contract.sol";

// 示例:从 openzeppelin-contract 代码库的 release-v4.5 分支导入 ECDSA.sol
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.5/contracts/utils/cryptography/ECDSA.sol
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.5/contracts/utils/cryptography/ECDSA.sol";

END