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

# Inicio rápido

> Configura tu entorno y despliega un contrato en la Testnet de Plasma con Hardhat o Foundry.

Esta guía cubre la configuración del entorno, el despliegue de contratos y la interacción con la testnet compatible con EVM de Plasma usando Hardhat. Asume familiaridad básica con el tooling de Ethereum y el desarrollo de smart contracts.

## Requisitos previos

* Node.js 20+
* Conocimiento básico del desarrollo en Ethereum
* Wallet de navegador

## Configuración del entorno

Usa Hardhat para construir y desplegar contratos.

### Configuración de Hardhat

1. Crea un nuevo directorio del proyecto e inicialízalo:

   ```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. Sigue los pasos para crear un proyecto JavaScript. Guarda el proyecto donde quieras. Probablemente no necesites un archivo `.gitignore` para este quickstart.
3. Configura `hardhat.config.js` para la testnet de Plasma:

   ```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.
       }
     }
   };
   ```

## Configuración de la wallet y la testnet

### Agrega la testnet de Plasma a tu wallet de navegador

1. Abre tu wallet de navegador (MetaMask, Trust Wallet o Rabby) y haz clic en el selector de red.
2. Selecciona la opción para agregar una red personalizada (por ejemplo, **Add Network**, **Add manually** o **Add custom network**).
3. Ingresa estos datos:
   * **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. Guarda la red y cambia a la Testnet de Plasma en tu wallet.

### Obtén tokens de testnet

1. Copia la dirección de tu wallet desde tu wallet de navegador.
2. Visita [openfaucet.org](https://openfaucet.org/).
3. Ingresa tu dirección y solicita tokens de testnet.
4. Espera a que la transacción se complete (debería aparecer en tu wallet en unos segundos).

### Configura las variables de entorno

1. Exporta la clave privada de tu cuenta usando la configuración de cuenta de tu wallet de navegador.
2. Crea un archivo `.env` en la raíz de tu proyecto:

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

<Warning>
  Nunca subas tu clave privada o mnemónico al control de versiones. Agrega `.env` a tu archivo `.gitignore`.
</Warning>

## Escribe un smart contract simple

1. Crea un contrato básico de almacenamiento `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. Compila el contrato:

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

   Esto debería generar algo como:

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

## Pruebas

1. Crea un script de prueba `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. Ejecuta las pruebas:

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

   Esto debería generar algo como:

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

### Despliega en la testnet de Plasma

1. Primero, crea un directorio `scripts`:

   ```shell theme={null}
   mkdir scripts
   ```
2. Luego, crea un script para desplegar el 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. Despliega el contrato:

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

   Esto debería generar algo como:

   ```plaintext theme={null}
   Deploying SimpleStorage...
   SimpleStorage deployed to: 0xaa4FB2A8eD6953A4e57b8097BAf048d7919e6262
   ```
4. Anota la dirección `deployed to:`. Esta es la dirección de tu contrato en la testnet de Plasma.

## Verifica el despliegue

1. Copia la dirección del contrato.
2. Visita el [explorador de la testnet de Plasma](https://testnet.plasmascan.to/).
3. Busca la dirección de tu contrato para ver la transacción de despliegue.

## Solución de problemas

| Problema                     | Resolución                                                                            |
| :--------------------------- | :------------------------------------------------------------------------------------ |
| Errores de estimación de gas | Asegúrate de que la wallet tenga suficiente XPL                                       |
| Errores de conexión de red   | Verifica la URL del RPC y la disponibilidad de la testnet                             |
| Errores de clave privada     | Verifica que `.env` esté configurado correctamente (sin prefijo `0x` si es requerido) |
| Retraso del explorador       | Espera unos minutos; el explorador puede estar sincronizando                          |
