创建和部署合约

我们来了解一下基本的工作流程:

  • 创建一个新的文件

  • 在文件中编写合约代码

  • 编译一个合约

  • 将其部署到本地模拟区块链(Remix虚拟机)上。

  • 与部署的合约函数进行交互

创建一个新文件

在文件资源管理器中,点击新建文件图标创建一个新文件,并给它命名。在 Remix 中,默认的文件扩展名是 .sol ,如果文件名没有扩展名,将会自动添加 .sol扩展名。

NOTE: For information about templates or workspaces, see the File Explorer docs.

在编辑器中,将以下合约粘贴到空白文件中:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.18;

contract testContract {

    uint256 value;

    constructor (uint256 _p) {
        value = _p;
    }

    function setP(uint256 _n) payable public {
        value = _n;
    }

    function setNP(uint256 _n) public {
        value = _n;
    }

    function get () view public returns (uint256) {
        return value;
    }
}

在粘贴代码时,请确保您理解代码内容,并在部署或与其交互之前进行检查。不要上当受骗!

编译合约

With the contract above as the active tab in the Editor, compile the contract.
A quick way to compile is to hit ctrl + s. You can also compile by going to the Solidity Compiler and clicking the compile button, or by right clicking a file in the File Explorer, or by clicking the play button at the top of the Editor.

For More Info see the docs on the Solidity Compiler.

部署合约

进入Deploy & Run Transactions插件。

At the top of this plugin is the Environment selectbox. Here you can choose where you want to deploy your contract. There are many choices. For more info about these options see this section of the docs.

简要概述:

  • Injected Provider 将 Remix 与浏览器钱包(例如 Metamask)连接,通常用于部署到公共网络。

  • Remix VM is a test blockchain in the browser. There are quite a few "flavors" of the Remix VM. Each "flavor" is associated with a different hard fork with the name in parathesies - e.g. Remix VM (Shanghai) or for the choice of a chain to fork into the Remix VM.

  • **Remix VM **非常方便,因为它是在浏览器中运行的区块链,无需安装其他任何内容即可运行它。

  • Dev 将 Remix 连接到在您计算机上运行的本地区块链。

  • L2 is for connecting Remix to Optimism or Arbitrum via a browser wallet. Its essentially the same as Injected Provider, but it sets the wallet with the configuration of the specified L2.

(有关详细信息,请参见 Running transactions

选择 Remix VM环境

在下拉菜单中选择第一个 Remix 虚拟机。

Remix虚拟机带有10个账户,每个账户都有100个以太币。

NOTE: When you are in the Remix VM and you reload the browser - the Remix VM will also restart to its fresh & default state. For a more realistic testing environment, use a public testnet.

部署合约

testContract的构造函数需要一个类型为uint256的参数。输入一个uint256并点击部署

创建交易以部署testContract实例。

在更真实的区块链环境中,您需要批准交易,然后等待交易被打包和确认。然而,由于我们使用的是 Remix VM ,将立即执行。

终端将提供有关交易的信息。

新创建的实例显示在已部署合约部分

![](images/create_deploy/a-remix-vm-inst ance.png)

与部署的实例进行交互

点击 TESTCONTRACT 实例左侧的三角形图标将展开该实例,以显示其函数。

这个新实例包含了三个函数(setPsetPNget)。

点击 setP setPN 将会创建一个新的合约。

setP 是一个payable函数(payable函数有红色按钮)。使用payable函数,可以向合约发送价值(ETH)。ETH 的数量可以在 VALUE 输入字段中选择,ETH 的单位可以在右侧的框中选择。

setPN函数不接受支付(一个橙色按钮 - 根据主题而定)。无法向此函数发送价值(以太币)。

get 是一个视图函数(一个蓝色按钮 - 根据主题而定)。它不执行交易,因为 get 不会修改状态(它只返回变量 value 的值)。

返回值会显示在“获取”按钮的正下方。