> ## 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.

# Início Rápido

> Configure seu ambiente e implante um contrato na Plasma Testnet com Hardhat ou Foundry.

Este guia cobre a configuração do ambiente, a implantação de contratos e a interação com a testnet compatível com EVM da Plasma usando o Hardhat. Assume familiaridade básica com o ferramental Ethereum e o desenvolvimento de smart contracts.

## Pré-requisitos

* Node.js 20+
* Conhecimento básico de desenvolvimento Ethereum
* Wallet de navegador

## Configuração do Ambiente

Use o Hardhat para construir e implantar contratos.

### Configuração do Hardhat

1. Crie um novo diretório de projeto e inicialize:

   ```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. Siga as etapas para criar um projeto JavaScript. Salve o projeto onde desejar. Provavelmente não precisará de um arquivo `.gitignore` para este início rápido.
3. Configure `hardhat.config.js` para a 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.
       }
     }
   };
   ```

## Configuração da Wallet e Testnet

### Adicione a Plasma Testnet à Sua Wallet de Navegador

1. Abra sua wallet de navegador (MetaMask, Trust Wallet ou Rabby) e clique no seletor de rede.
2. Selecione a opção para adicionar uma rede personalizada (por exemplo, **Add Network**, **Add manually** ou **Add custom network**).
3. Insira estes detalhes:
   * **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. Salve a rede e mude para a Plasma Testnet em sua wallet.

### Obtenha Tokens da Testnet

1. Copie o endereço da sua wallet a partir da wallet de navegador.
2. Visite [openfaucet.org](https://openfaucet.org/).
3. Insira seu endereço e solicite tokens da testnet.
4. Aguarde a transação ser concluída (deverá aparecer em sua wallet em alguns segundos).

### Configure Variáveis de Ambiente

1. Exporte a chave privada da sua conta usando as configurações de conta da sua wallet de navegador.
2. Crie um arquivo `.env` na raiz do projeto:

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

<Warning>
  Nunca faça commit da sua chave privada ou mnemônico em um sistema de controle de versão. Adicione `.env` ao seu arquivo `.gitignore`.
</Warning>

## Escreva um Smart Contract Simples

1. Crie um contrato básico de armazenamento `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. Compile o contrato:

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

   Isso deverá gerar uma saída semelhante a:

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

## Testes

1. Crie um script de teste `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. Execute os testes:

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

   Isso deverá gerar uma saída semelhante a:

   ```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)
   ```

### Implante na Plasma Testnet

1. Primeiro, crie um diretório `scripts`:

   ```shell theme={null}
   mkdir scripts
   ```
2. Em seguida, crie um script para implantar o contrato `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. Implante o contrato:

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

   Isso deverá gerar uma saída semelhante a:

   ```plaintext theme={null}
   Deploying SimpleStorage...
   SimpleStorage deployed to: 0xaa4FB2A8eD6953A4e57b8097BAf048d7919e6262
   ```
4. Anote o endereço `deployed to:`. Este é o endereço do seu contrato na Plasma testnet.

## Verifique a Implantação

1. Copie o endereço do contrato.
2. Visite o [Plasma testnet explorer](https://testnet.plasmascan.to/).
3. Pesquise pelo endereço do seu contrato para visualizar a transação de implantação.

## Solução de Problemas

| Problema                   | Resolução                                                                      |
| :------------------------- | :----------------------------------------------------------------------------- |
| Erros de estimativa de gas | Garanta que a wallet tenha XPL suficiente                                      |
| Erros de conexão de rede   | Verifique a URL do RPC e a disponibilidade da testnet                          |
| Erros de chave privada     | Garanta que `.env` está configurado corretamente (sem prefixo `0x` se exigido) |
| Atraso do explorer         | Aguarde alguns minutos; o explorer pode estar sincronizando                    |
