> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/zkp2p/zkp2p-contracts/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart

> Get started with ZKP2P v2.1 contracts - Install dependencies, build, test, and deploy locally

## Prerequisites

Before getting started, ensure you have the following installed:

<CardGroup cols={2}>
  <Card title="Node.js 18+" icon="node-js">
    Required for running the Hardhat development environment
  </Card>

  <Card title="Yarn 4" icon="yarn">
    Package manager used for dependency management
  </Card>

  <Card title="Foundry" icon="hammer">
    Required for `forge` command to run Foundry-based tests
  </Card>

  <Card title="Git" icon="git">
    For cloning the repository and version control
  </Card>
</CardGroup>

<Note>
  The project uses Yarn 4 (Berry) with PnP. Make sure you have the correct version by running `yarn --version`.
</Note>

## Installation

<Steps>
  <Step title="Clone the Repository">
    Clone the zkp2p-v2-contracts repository from GitHub:

    ```bash theme={null}
    git clone https://github.com/zkp2p/zkp2p-v2-contracts.git
    cd zkp2p-v2-contracts
    ```
  </Step>

  <Step title="Install Dependencies">
    Install all project dependencies using Yarn:

    ```bash theme={null}
    yarn install
    ```

    This will install all necessary packages including:

    * Hardhat development framework
    * OpenZeppelin contracts
    * TypeChain for TypeScript bindings
    * Testing utilities (Chai, Mocha)
    * Foundry integration
  </Step>

  <Step title="Configure Environment Variables">
    Copy the default environment configuration and set your API keys:

    ```bash theme={null}
    cp .env.default .env
    ```

    Edit the `.env` file and add your keys:

    ```bash .env theme={null}
    # Required for deployment
    ALCHEMY_API_KEY=your_alchemy_api_key_here
    BASE_DEPLOY_PRIVATE_KEY=your_mainnet_private_key_here
    TESTNET_DEPLOY_PRIVATE_KEY=your_testnet_private_key_here

    # Required for contract verification
    BASESCAN_API_KEY=your_basescan_api_key_here
    ETHERSCAN_KEY=your_etherscan_api_key_here
    INFURA_TOKEN=your_infura_token_here
    ```

    <Warning>
      Never commit your `.env` file to version control. The `.gitignore` is already configured to exclude it.
    </Warning>
  </Step>
</Steps>

## Build the Project

The build process compiles Solidity contracts, generates TypeScript type definitions, and transpiles TypeScript code.

<CodeGroup>
  ```bash Full Build theme={null}
  # Clean, compile contracts, generate typechain, and transpile TypeScript
  yarn build
  ```

  ```bash Compile Only theme={null}
  # Compile Solidity contracts without cleaning
  yarn compile
  ```

  ```bash Clean Build theme={null}
  # Remove all build artifacts before compiling
  yarn clean && yarn build
  ```
</CodeGroup>

<Info>
  The `yarn build` command runs: `yarn clean && yarn compile && yarn build:ts:latest`

  This ensures a clean build with updated TypeChain bindings.
</Info>

### Build Artifacts

After building, you'll find:

* `artifacts/` - Compiled contract ABIs and bytecode
* `typechain/` - TypeScript type definitions for contracts
* `cache/` - Hardhat compilation cache
* `dist/` - Transpiled TypeScript files

## Run Tests

ZKP2P includes comprehensive test coverage using both Hardhat and Foundry.

### Hardhat Tests

<CodeGroup>
  ```bash All Tests theme={null}
  # Run the complete Hardhat test suite
  yarn test
  ```

  ```bash Fast Tests (No Compilation) theme={null}
  # Skip compilation for faster test iteration
  yarn test:fast
  ```

  ```bash Specific Test Suite theme={null}
  # Run tests for a specific component
  yarn test test/orchestrator/*.ts
  yarn test test/escrow/*.ts
  yarn test test/unifiedVerifier/*.ts
  ```

  ```bash Integration Tests theme={null}
  # Run end-to-end integration tests
  yarn test:integration
  ```
</CodeGroup>

### Foundry Tests

<CodeGroup>
  ```bash All Foundry Tests theme={null}
  # Run all Foundry test suites
  yarn test:forge
  ```

  ```bash Fuzz Testing theme={null}
  # Run property-based fuzz tests (100 runs)
  yarn test:forge:fuzz
  ```

  ```bash Invariant Testing theme={null}
  # Run protocol invariant tests
  yarn test:forge:invariant
  ```

  ```bash Fork Testing theme={null}
  # Run tests against forked networks
  yarn test:forge:fork
  ```
</CodeGroup>

<Tip>
  Use `yarn test:fast` during development to skip compilation and run tests faster. Only use `yarn test` when you've made contract changes.
</Tip>

### Test Coverage

Generate coverage reports to ensure comprehensive test coverage:

<CodeGroup>
  ```bash Hardhat Coverage theme={null}
  # Generate coverage report with Solidity Coverage
  yarn coverage
  ```

  ```bash Foundry Coverage theme={null}
  # Generate coverage report using Forge
  yarn test:forge:coverage
  ```
</CodeGroup>

<Note>
  The project maintains high test coverage across all core components. Coverage reports are also published to Codecov.
</Note>

## Local Development

Run a local Hardhat node for development and testing.

<Steps>
  <Step title="Start Local Node">
    Launch a local Hardhat network in a separate terminal:

    ```bash theme={null}
    yarn chain
    ```

    This starts a local Ethereum node at `http://localhost:8545` with:

    * 10 prefunded test accounts
    * Instant mining (no block time)
    * Deterministic account generation
  </Step>

  <Step title="Deploy Contracts Locally">
    In another terminal, deploy the complete contract system:

    ```bash theme={null}
    yarn deploy:localhost
    ```

    This runs the deployment scripts in order:

    1. `00_deploy_system.ts` - Core registries and system contracts
    2. `01_deploy_unified_verifier.ts` - Unified payment verifier
    3. `02_add_venmo_payment_method.ts` - Venmo configuration
    4. And subsequent payment method configurations...
  </Step>

  <Step title="Verify Deployment">
    Check that all contracts deployed successfully:

    ```bash theme={null}
    ls deployments/localhost/
    ```

    You should see deployment artifacts for:

    * `Orchestrator.json`
    * `Escrow.json`
    * `UnifiedPaymentVerifier.json`
    * `PaymentVerifierRegistry.json`
    * And other system contracts
  </Step>
</Steps>

<Info>
  Local deployment includes a USDC mock token for testing. In production deployments, the actual USDC token address is used.
</Info>

## Interact with Contracts

Once deployed locally, you can interact with contracts using Hardhat console or scripts.

### Using Hardhat Console

```bash theme={null}
npx hardhat console --network localhost
```

Then interact with deployed contracts:

```javascript theme={null}
const escrow = await ethers.getContract("Escrow");
const orchestrator = await ethers.getContract("Orchestrator");
const usdc = await ethers.getContract("USDCMock");

// Check balances
const [deployer] = await ethers.getSigners();
const balance = await usdc.balanceOf(deployer.address);
console.log("USDC Balance:", ethers.utils.formatUnits(balance, 6));

// Get protocol state
const protocolFee = await orchestrator.protocolFee();
console.log("Protocol Fee:", protocolFee.toString());
```

### Create a Test Deposit

Here's a complete example of creating a maker deposit:

```typescript theme={null}
import { ethers } from "hardhat";

async function createDeposit() {
  const escrow = await ethers.getContract("Escrow");
  const usdc = await ethers.getContract("USDCMock");
  const [maker] = await ethers.getSigners();
  
  // Payment method hash for Venmo
  const venmoHash = ethers.utils.keccak256(
    ethers.utils.toUtf8Bytes("venmo")
  );
  
  // Approve USDC
  const depositAmount = ethers.utils.parseUnits("1000", 6); // 1000 USDC
  await usdc.approve(escrow.address, depositAmount);
  
  // Create deposit
  const tx = await escrow.createDeposit({
    token: usdc.address,
    amount: depositAmount,
    intentAmountRange: {
      min: ethers.utils.parseUnits("10", 6),  // Min 10 USDC
      max: ethers.utils.parseUnits("500", 6)  // Max 500 USDC
    },
    delegate: ethers.constants.AddressZero,
    intentGuardian: ethers.constants.AddressZero,
    retainOnEmpty: false,
    paymentMethods: [venmoHash],
    paymentMethodData: [{
      payeeDetails: ethers.utils.keccak256(
        ethers.utils.toUtf8Bytes("@myvenmo")
      ),
      intentGatingService: ethers.constants.AddressZero
    }],
    currencies: [[
      {
        code: ethers.utils.keccak256(ethers.utils.toUtf8Bytes("USD")),
        minConversionRate: ethers.utils.parseUnits("1", 18) // 1:1 rate
      }
    ]]
  });
  
  const receipt = await tx.wait();
  console.log("Deposit created!", receipt.transactionHash);
}

createDeposit().catch(console.error);
```

<Tip>
  Check out the test files in `test/escrow/` and `test/orchestrator/` for more comprehensive examples of contract interactions.
</Tip>

## Deploy to Testnet

Deploy to Base Sepolia testnet for testing in a live environment.

<Steps>
  <Step title="Fund Deployment Account">
    Ensure your testnet private key account has ETH on Base Sepolia for gas fees. Get testnet ETH from:

    * [Base Sepolia Faucet](https://www.coinbase.com/faucets/base-ethereum-goerli-faucet)
  </Step>

  <Step title="Deploy to Base Sepolia">
    Run the deployment script:

    ```bash theme={null}
    yarn deploy:base_sepolia
    ```

    This deploys the complete system to Base Sepolia testnet.
  </Step>

  <Step title="Verify Contracts">
    Verify contracts on Basescan for public transparency:

    ```bash theme={null}
    yarn etherscan:base_sepolia
    ```

    <Note>
      Verification uses a 600-second delay between submissions to avoid rate limiting.
    </Note>
  </Step>
</Steps>

## Deploy to Production

<Warning>
  **Production deployments require extreme care!** Ensure you:

  * Have thoroughly tested on testnet
  * Reviewed all deployment parameters
  * Verified multisig addresses
  * Have sufficient ETH for gas fees
  * Understand the implications of contract ownership
</Warning>

<CodeGroup>
  ```bash Base Mainnet theme={null}
  # Deploy to Base mainnet
  yarn deploy:base
  ```

  ```bash Verify on Basescan theme={null}
  # Verify all contracts after deployment
  yarn etherscan:base
  ```
</CodeGroup>

### Deployment Parameters

Key parameters are configured in `deployments/parameters.ts`:

```typescript theme={null}
export const PROTOCOL_TAKER_FEE = {
  base: ethers.utils.parseUnits("0.01", 18), // 1% fee
};

export const INTENT_EXPIRATION_PERIOD = {
  base: 60 * 60 * 2, // 2 hours
};

export const MAX_INTENTS_PER_DEPOSIT = {
  base: 100,
};

export const ESCROW_DUST_THRESHOLD = {
  base: ethers.utils.parseUnits("1", 6), // 1 USDC
};
```

## Hardhat Configuration

The project uses Hardhat with the following key settings:

```typescript hardhat.config.ts theme={null}
export default {
  solidity: {
    compilers: [{
      version: "0.8.18",
      settings: {
        optimizer: {
          enabled: true,
          runs: 200,
        },
        viaIR: true  // Enable IR optimization
      },
    }],
  },
  networks: {
    localhost: {
      allowBlocksWithSameTimestamp: true,
    },
    base: {
      url: "https://base-mainnet.g.alchemy.com/v2/" + process.env.ALCHEMY_API_KEY,
      accounts: [`0x${process.env.BASE_DEPLOY_PRIVATE_KEY}`],
    },
    base_sepolia: {
      url: "https://base-sepolia.g.alchemy.com/v2/" + process.env.ALCHEMY_API_KEY,
      accounts: [`0x${process.env.TESTNET_DEPLOY_PRIVATE_KEY}`],
    },
  },
};
```

## Next Steps

Now that you have the contracts running locally, explore:

<CardGroup cols={2}>
  <Card title="Architecture Guide" icon="sitemap" href="/architecture">
    Deep dive into system design and component interactions
  </Card>

  <Card title="Contract Reference" icon="book" href="/contracts/escrow">
    Detailed API documentation for all contracts
  </Card>

  <Card title="Integration Examples" icon="code" href="/guides/creating-deposits">
    Learn how to integrate ZKP2P into your application
  </Card>

  <Card title="Architecture Guide" icon="sitemap" href="/architecture">
    Understand the protocol architecture and components
  </Card>
</CardGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Compilation errors with Solidity 0.8.18">
    Ensure you're using the correct Node.js version (18+) and have the latest Hardhat installed:

    ```bash theme={null}
    node --version
    yarn add -D hardhat@latest
    ```
  </Accordion>

  <Accordion title="Out of gas errors during tests">
    The project uses `viaIR` optimization which can increase gas costs. For local testing, the gas limit is set to 100M:

    ```typescript theme={null}
    hardhat: {
      blockGasLimit: 100_000_000,
      gas: 100_000_000,
    }
    ```
  </Accordion>

  <Accordion title="TypeChain types not found">
    Regenerate TypeChain types:

    ```bash theme={null}
    yarn clean
    yarn compile
    yarn typechain
    ```
  </Accordion>

  <Accordion title="Deployment scripts fail with 'skip' function error">
    This occurs when non-TypeScript files exist in the `deploy/` folder. The project is configured to skip `.md`, `.mdx`, and `.txt` files automatically.
  </Accordion>
</AccordionGroup>

<Info>
  For more help, check the [GitHub Issues](https://github.com/zkp2p/zkp2p-v2-contracts/issues) or join the community discussion.
</Info>
