> ## Documentation Index
> Fetch the complete documentation index at: https://docs.plasma.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Быстрый старт

> Настройте окружение и разверните контракт на Plasma Testnet с помощью Hardhat или Foundry.

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

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

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

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

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

### Настройка Hardhat

1. Создайте новый каталог проекта и инициализируйте:

   ```shell theme={null}
   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:

   ```javascript theme={null}
   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](https://openfaucet.org/).
3. Введите свой адрес и запросите тестовые токены.
4. Дождитесь завершения транзакции (она должна появиться в кошельке в течение нескольких секунд).

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

1. Экспортируйте приватный ключ аккаунта через настройки аккаунта в браузерном кошельке.
2. Создайте файл `.env` в корне проекта:

   ```shell theme={null}
   PRIVATE_KEY=your_private_key_here
   RPC_ENDPOINT=https://testnet-rpc.plasma.to
   ```

<Warning>
  Никогда не коммитьте приватный ключ или мнемонику в систему контроля версий. Добавьте `.env` в файл `.gitignore`.
</Warning>

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

1. Создайте базовый контракт хранения `contracts/SimpleStorage.sol`:

   ```solidity theme={null}
   // 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. Скомпилируйте контракт:

   ```shell theme={null}
   npx hardhat compile
   ```

   Должен получиться вывод примерно такой:

   ```plaintext theme={null}
   Downloading compiler 0.8.28
   Downloading compiler 0.8.28
   Compiled 2 Solidity files successfully (evm target: paris).
   ```

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

1. Создайте тестовый скрипт `test/SimpleStorage.js`:

   ```javascript theme={null}
   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. Запустите тесты:

   ```shell theme={null}
   npx hardhat test
   ```

   Вывод должен быть примерно такой:

   ```plaintext theme={null}
   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`:

   ```shell theme={null}
   mkdir scripts
   ```
2. Затем создайте скрипт для развёртывания контракта `scripts/deploy.js`:

   ```javascript theme={null}
   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. Разверните контракт:

   ```shell theme={null}
   npx hardhat run scripts/deploy.js --network plasmaTestnet
   ```

   Вывод должен быть примерно такой:

   ```plaintext theme={null}
   Deploying SimpleStorage...
   SimpleStorage deployed to: 0xaa4FB2A8eD6953A4e57b8097BAf048d7919e6262
   ```
4. Запишите адрес `deployed to:`. Это адрес вашего контракта в Plasma testnet.

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

1. Скопируйте адрес контракта.
2. Перейдите в [обозреватель Plasma testnet](https://testnet.plasmascan.to/).
3. Найдите адрес контракта, чтобы увидеть транзакцию развёртывания.

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

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