Перейти к основному содержанию
Это руководство охватывает настройку окружения, развёртывание контракта и взаимодействие с EVM-совместимым testnet Plasma с использованием Hardhat. Предполагается базовое знакомство с инструментами Ethereum и разработкой смарт-контрактов.

Предварительные требования

  • Node.js 20+
  • Базовые знания разработки на Ethereum
  • Браузерный кошелёк

Настройка окружения

Используйте Hardhat для сборки и развёртывания контрактов.

Настройка Hardhat

  1. Создайте новый каталог проекта и инициализируйте:
    mkdir my-plasma-project
    cd my-plasma-project
    npm init -y
    npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
    npm install dotenv
    npx hardhat init
    
  2. Следуйте шагам для создания JavaScript-проекта. Сохраните проект где угодно. Файл .gitignore для этого быстрого старта, скорее всего, не понадобится.
  3. Настройте hardhat.config.js для Plasma testnet:
    require("@nomicfoundation/hardhat-toolbox");
    require("dotenv").config();
    
    /** @type import('hardhat/config').HardhatUserConfig */
    module.exports = {
      solidity: "0.8.28",
      networks: {
        plasmaTestnet: {
          url: process.env.RPC_ENDPOINT,
          chainId: 9746,
          accounts: [process.env.PRIVATE_KEY] // We'll set this up next.
        }
      }
    };
    

Настройка кошелька и Testnet

Добавьте Plasma Testnet в браузерный кошелёк

  1. Откройте браузерный кошелёк (MetaMask, Trust Wallet или Rabby) и нажмите на селектор сетей.
  2. Выберите опцию добавления пользовательской сети (например, Add Network, Add manually или Add custom network).
  3. Введите следующие данные:
    • Network Name: Plasma Testnet
    • New RPC URL: https://testnet-rpc.plasma.to
    • Chain ID: 9746
    • Currency Symbol: XPL
    • Block Explorer URL: https://testnet.plasmascan.to
  4. Сохраните сеть и переключитесь на Plasma Testnet в кошельке.

Получите тестовые токены

  1. Скопируйте адрес кошелька из вашего браузерного кошелька.
  2. Перейдите на openfaucet.org.
  3. Введите свой адрес и запросите тестовые токены.
  4. Дождитесь завершения транзакции (она должна появиться в кошельке в течение нескольких секунд).

Настройте переменные окружения

  1. Экспортируйте приватный ключ аккаунта через настройки аккаунта в браузерном кошельке.
  2. Создайте файл .env в корне проекта:
    PRIVATE_KEY=your_private_key_here
    RPC_ENDPOINT=https://testnet-rpc.plasma.to
    
Никогда не коммитьте приватный ключ или мнемонику в систему контроля версий. Добавьте .env в файл .gitignore.

Напишите простой смарт-контракт

  1. Создайте базовый контракт хранения contracts/SimpleStorage.sol:
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.28;
    
    contract SimpleStorage {
        string private storedData;
        
        event DataStored(string data);
        
        constructor() {
            storedData = "Hello, Plasma!";
        }
        
        function setData(string memory data) public {
            storedData = data;
            emit DataStored(data);
        }
        
        function getData() public view returns (string memory) {
            return storedData;
        }
    }
    
  2. Скомпилируйте контракт:
    npx hardhat compile
    
    Должен получиться вывод примерно такой:
    Downloading compiler 0.8.28
    Downloading compiler 0.8.28
    Compiled 2 Solidity files successfully (evm target: paris).
    

Тестирование

  1. Создайте тестовый скрипт test/SimpleStorage.js:
    const { expect } = require("chai");
    
    describe("SimpleStorage", function () {
      let simpleStorage;
    
      beforeEach(async function () {
        const SimpleStorage = await ethers.getContractFactory("SimpleStorage");
        simpleStorage = await SimpleStorage.deploy();
        await simpleStorage.waitForDeployment();
      });
    
      it("Should return the initial greeting", async function () {
        expect(await simpleStorage.getData()).to.equal("Hello, Plasma!");
      });
    
      it("Should update the stored data", async function () {
        await simpleStorage.setData("Updated data");
        expect(await simpleStorage.getData()).to.equal("Updated data");
      });
    });
    
  2. Запустите тесты:
    npx hardhat test
    
    Вывод должен быть примерно такой:
    Lock
      Deployment
        ✔ Should set the right unlockTime (454ms)
        ✔ Should set the right owner
        ✔ Should receive and store the funds to lock
        ✔ Should fail if the unlockTime is not in the future
      Withdrawals
        Validations
          ✔ Should revert with the right error if called too soon
          ✔ Should revert with the right error if called from another account
          ✔ Shouldn't fail if the unlockTime has arrived and the owner calls it
        Events
          ✔ Should emit an event on withdrawals
        Transfers
          ✔ Should transfer the funds to the owner
    
    SimpleStorage
      ✔ Should return the initial greeting
      ✔ Should update the stored data
    
    
    11 passing (541ms)
    

Разверните на Plasma Testnet

  1. Сначала создайте каталог scripts:
    mkdir scripts
    
  2. Затем создайте скрипт для развёртывания контракта scripts/deploy.js:
    async function main() {
      const SimpleStorage = await ethers.getContractFactory("SimpleStorage");
      
      console.log("Deploying SimpleStorage...");
      const simpleStorage = await SimpleStorage.deploy();
      await simpleStorage.waitForDeployment();
      
      const address = await simpleStorage.getAddress();
      console.log("SimpleStorage deployed to:", address);
    }
    
    main()
      .then(() => process.exit(0))
      .catch((error) => {
        console.error(error);
        process.exit(1);
      });
    
  3. Разверните контракт:
    npx hardhat run scripts/deploy.js --network plasmaTestnet
    
    Вывод должен быть примерно такой:
    Deploying SimpleStorage...
    SimpleStorage deployed to: 0xaa4FB2A8eD6953A4e57b8097BAf048d7919e6262
    
  4. Запишите адрес deployed to:. Это адрес вашего контракта в Plasma testnet.

Проверка развёртывания

  1. Скопируйте адрес контракта.
  2. Перейдите в обозреватель Plasma testnet.
  3. Найдите адрес контракта, чтобы увидеть транзакцию развёртывания.

Устранение неполадок

ПроблемаРешение
Ошибки оценки газаУбедитесь, что в кошельке достаточно XPL
Ошибки сетевого подключенияПроверьте RPC URL и доступность testnet
Ошибки приватного ключаУбедитесь, что .env настроен правильно (без префикса 0x, если требуется)
Задержка обозревателяПодождите несколько минут; обозреватель может синхронизироваться