原文作者:PaperMoon团队

通过这份全面指南,开启你的智能合约开发之旅。学习如何在 Polkadot 上创建、部署并与智能合约交互。无论你是智能合约新手,还是希望进一步打磨技能,这套教程都能为你提供一条结构清晰的项目启动路径。

现在就开始构建你的第一个智能合约:
    •    使用合适的工具和框架搭建开发环境
    •    编写并编译你的第一个智能合约
    •    在 Polkadot 上部署并与合约交互
    •    测试并优化代码,使其达到生产级标准
    •    跟随分步教程,自信地完成项目上线

开发路径(Development Pathway)
    •    新手友好:循序渐进的步骤,适合刚接触智能合约的开发者
    •    动手实践:通过实操练习,培养真实世界中的开发能力
    •    面向生产:从基础概念逐步过渡到可部署的生产级合约

使用 Hardhat 进行测试与部署

简介

在完成智能合约编写后,接下来的关键步骤是测试和部署。充分的测试可以确保合约行为符合预期,而部署则会让合约真正运行在区块链上。

本教程将引导你使用 Hardhat(一个流行的以太坊兼容开发环境)来测试和部署你在“创建智能合约”教程中完成的 Storage.sol 合约。
如需了解更多 Hardhat 用法,请参考官方 Hardhat 指南。

前置条件

在开始之前,请确保你已具备以下条件:
    •    已完成上一教程中的 Storage.sol 合约
    •    已安装 Node.js(v16.0.0 或更高) 和 npm
    •    具备基础的 JavaScript 知识(用于编写测试)
    •    拥有一些 PAS 测试代币(用于支付交易手续费,可通过 Polkadot faucet 获取)

搭建开发环境

我们从为 Storage 合约项目配置 Hardhat 开始。

1. 创建项目目录并进入

mkdir storage-hardhat
cd storage-hardhat

2. 初始化 npm 项目

npm init -y

3. 安装 hardhat-polkadot 及所需依赖

npm install --save-dev @parity/hardhat-polkadot@0.1.9 solc@0.8.28

由于依赖兼容性问题,请使用 --force 安装 Hardhat 工具箱:

npm install --force @nomicfoundation/hardhat-toolbox

4. 初始化 Hardhat 项目

npx hardhat-polkadot init

在提示中选择 Create an empty hardhat.config.js。

配置 Hardhat

编辑 hardhat.config.js 文件如下:

require("@nomicfoundation/hardhat-toolbox");
require("@parity/hardhat-polkadot");

const { vars } = require("hardhat/config");

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.28",
  resolc: {
    compilerSource: "npm",
  },
  networks: {
    hardhat: {
      polkavm: true,
      nodeConfig: {
        nodeBinaryPath: 'INSERT_PATH_TO_SUBSTRATE_NODE',
        rpcPort: 8000,
        dev: true,
      },
      adapterConfig: {
        adapterBinaryPath: 'INSERT_PATH_TO_ETH_RPC_ADAPTER',
        dev: true,
      },
    },
    localNode: {
      polkavm: true,
      url: `http://127.0.0.1:8545`,
    },
    passetHub: {
      polkavm: true,
      url: 'https://testnet-passet-hub-eth-rpc.polkadot.io',
      accounts: [vars.get("PRIVATE_KEY")],
    },
  },
};

请将以下字段替换为你本地实际路径:
    •    INSERT_PATH_TO_SUBSTRATE_NODE
    •    INSERT_PATH_TO_ETH_RPC_ADAPTER

网络配置说明
    •    localNode:在 http://127.0.0.1:8545 上运行本地 PolkaVM,用于开发和测试
    •    passetHub:连接到 Polkadot Hub 测试网,使用 RPC 接口与环境变量中的私钥

配置私钥

使用以下命令设置私钥:

npx hardhat vars set PRIVATE_KEY "INSERT_PRIVATE_KEY"

请将 INSERT_PRIVATE_KEY 替换为你自己的私钥。

请妥善保管你的私钥,切勿泄露。一旦私钥泄露,你的资产可能会被盗。

添加智能合约

创建 contracts 文件夹,并新建 Storage.sol 文件,内容如下:

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

contract Storage {
    uint256 private number;

    event NumberChanged(uint256 newNumber);

    function store(uint256 newNumber) public {
        number = newNumber;
        emit NumberChanged(newNumber);
    }

    function retrieve() public view returns (uint256) {
        return number;
    }
}

编译合约

npx hardhat compile

成功后,你将看到类似输出:

Compiling 1 Solidity file
Successfully compiled 1 Solidity file

项目根目录中会生成 artifacts-pvm 和 cache-pvm 文件夹。

编写测试

测试是智能合约开发中至关重要的一环。Hardhat 支持使用 Mocha 和 Chai 编写 JavaScript 测试。

创建测试文件

mkdir test

创建 test/Storage.js:

const { expect } = require('chai');
const { ethers } = require('hardhat');

describe('Storage', function () {
  let storage;
  let owner;
  let addr1;

  beforeEach(async function () {
    [owner, addr1] = await ethers.getSigners();
    const Storage = await ethers.getContractFactory('Storage');
    storage = await Storage.deploy();
    await storage.waitForDeployment();
  });

  describe('Basic functionality', function () {
    // 添加测试逻辑
  });
});

beforeEach 会在每个测试前重新部署合约,确保测试之间互不干扰。

示例测试用例

初始状态测试

it('Should return 0 initially', async function () {
  expect(await storage.retrieve()).to.equal(0);
});

说明:
    •    验证合约初始值为 0
    •    确保 retrieve() 在新部署时工作正常

存储与读取测试

it('Should update when store is called', async function () {
  const testValue = 42;
  await storage.store(testValue);
  expect(await storage.retrieve()).to.equal(testValue);
});

事件触发测试

it('Should emit an event when storing a value', async function () {
  const testValue = 100;
  await expect(storage.store(testValue))
    .to.emit(storage, 'NumberChanged')
    .withArgs(testValue);
});

连续存储测试

it('Should allow storing sequentially increasing values', async function () {
  const values = [10, 20, 30, 40];
  for (const value of values) {
    await storage.store(value);
    expect(await storage.retrieve()).to.equal(value);
  }
});

运行测试

npx hardhat test

测试通过后,你会看到类似输出:

4 passing (31s)

使用 Ignition 部署合约

Hardhat Ignition 是一个可预测、可管理的部署系统。

创建部署模块

mkdir -p ignition/modules

StorageModule.js:

const { buildModule } = require('@nomicfoundation/hardhat-ignition/modules');

module.exports = buildModule('StorageModule', (m) => {
  const storage = m.contract('Storage');
  return { storage };
});

部署到本地网络

npx hardhat node

另开一个终端:

npx hardhat ignition deploy ./ignition/modules/StorageModule.js --network localNode

部署到 Polkadot Hub 测试网

确保账户中有足够的 PAS:

npx hardhat ignition deploy ./ignition/modules/StorageModule.js --network passetHub

请保存输出的合约地址。

与已部署合约交互

创建 scripts/interact.js:

const hre = require('hardhat');

async function main() {
  const contractAddress = 'INSERT_DEPLOYED_CONTRACT_ADDRESS';
  const Storage = await hre.ethers.getContractFactory('Storage');
  const storage = await Storage.attach(contractAddress);

  const currentValue = await storage.retrieve();
  console.log('当前存储值:', currentValue.toString());

  const newValue = 42;
  console.log(`存储新值: ${newValue}`);
  const tx = await storage.store(newValue);
  await tx.wait();

  const updatedValue = await storage.retrieve();
  console.log('更新后的值:', updatedValue.toString());
}

main().catch(console.error);

运行脚本:

npx hardhat run scripts/interact.js --network passetHub

总结

恭喜!你已经成功完成了以下步骤:
    •    搭建 Hardhat + PolkaVM 开发环境
    •    编写并测试 Storage 智能合约
    •    将合约部署到本地和 Polkadot Hub 测试网
    •    与已部署合约进行交互

如果你希望直接运行一个完整示例项目,可以克隆官方仓库:

git clone https://github.com/polkadot-developers/polkavm-hardhat-examples.git -b v0.0.8
cd polkavm-hardhat-examples/storage-hardhat

原文链接:https://docs.polkadot.com/tutorials/smart-contracts/launch-your-first-project/test-and-deploy-with-hardhat/

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐