# Deploying Contracts

## Complete Guide to Deploying Smart Contracts on Goliath Network

This guide walks you through deploying smart contracts on Goliath, from simple contracts to complex DeFi protocols. Goliath's EVM compatibility means your existing Solidity contracts work without modification.

## 🚀 Quick Deploy

### Using Remix IDE (Easiest)

1. **Open Remix**: Visit [remix.ethereum.org](https://remix.ethereum.org)
2. **Write Contract**: Create your Solidity contract
3. **Compile**: Use Solidity compiler 0.8.19+
4. **Deploy**:
   * Select "Injected Provider - MetaMask"
   * Connect to Goliath Testnet
   * Click "Deploy"
   * Confirm transaction in MetaMask

### Using Command Line

```bash
# Install Hardhat
npm install --save-dev hardhat

# Deploy
npx hardhat run scripts/deploy.js --network goliath-testnet
```

## 📝 Writing Your Contract

### Basic ERC-20 Token

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract GoliathToken is ERC20, Ownable {
    uint256 public constant INITIAL_SUPPLY = 1000000 * 10**18;
    
    constructor() ERC20("Goliath Token", "GTK") {
        _mint(msg.sender, INITIAL_SUPPLY);
    }
    
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }
    
    function burn(uint256 amount) public {
        _burn(msg.sender, amount);
    }
}
```

### NFT Collection

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

contract GoliathNFT is ERC721, ERC721URIStorage {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;
    
    uint256 public constant MAX_SUPPLY = 10000;
    uint256 public constant MINT_PRICE = 0.01 ether;
    
    constructor() ERC721("Goliath NFT", "GNFT") {}
    
    function mintNFT(string memory tokenURI) public payable returns (uint256) {
        require(msg.value >= MINT_PRICE, "Insufficient payment");
        require(_tokenIds.current() < MAX_SUPPLY, "Max supply reached");
        
        _tokenIds.increment();
        uint256 newItemId = _tokenIds.current();
        
        _safeMint(msg.sender, newItemId);
        _setTokenURI(newItemId, tokenURI);
        
        return newItemId;
    }
    
    function withdraw() public onlyOwner {
        payable(owner()).transfer(address(this).balance);
    }
}
```

## 🔧 Deployment with Hardhat

### 1. Project Setup

```bash
mkdir my-goliath-project
cd my-goliath-project
npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
npx hardhat init
```

### 2. Configuration

Create `hardhat.config.js`:

```javascript
require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config();

module.exports = {
  solidity: {
    version: "0.8.19",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200
      }
    }
  },
  networks: {
    goliathTestnet: {
      url: "https://rpc.testnet.goliath.net",
      chainId: 8901,
      accounts: [process.env.PRIVATE_KEY],
      gasPrice: 1000000000, // 1 Gwei
    },
    goliathMainnet: {
      url: "https://rpc.goliath.net",
      chainId: 327,
      accounts: [process.env.PRIVATE_KEY],
    }
  },
  etherscan: {
    apiKey: {
      goliathMainnet: "not-required",
      goliathTestnet: "not-required",
    },
    customChains: [
      {
        network: "goliathMainnet",
        chainId: 327,
        urls: {
          apiURL: "https://explorer.goliath.net/api",
          browserURL: "https://explorer.goliath.net"
        }
      },
      {
        network: "goliathTestnet",
        chainId: 8901,
        urls: {
          apiURL: "https://testnet.explorer.goliath.net/api",
          browserURL: "https://testnet.explorer.goliath.net"
        }
      }
    ]
  }
};
```

### 3. Deployment Script

Create `scripts/deploy.js`:

```javascript
const hre = require("hardhat");

async function main() {
  console.log("🚀 Deploying to Goliath Network...");
  
  // Get deployer account
  const [deployer] = await hre.ethers.getSigners();
  console.log("Deploying with account:", deployer.address);
  
  // Check balance
  const balance = await deployer.provider.getBalance(deployer.address);
  console.log("Account balance:", hre.ethers.formatEther(balance), "XCN");
  
  // Deploy contract
  const Contract = await hre.ethers.getContractFactory("GoliathToken");
  const contract = await Contract.deploy();
  
  await contract.waitForDeployment();
  
  const address = await contract.getAddress();
  console.log("✅ Contract deployed to:", address);
  const explorerUrl = network.name === "goliathMainnet"
    ? "https://explorer.goliath.net"
    : "https://testnet.explorer.goliath.net";
  console.log("🔍 View on explorer:", `${explorerUrl}/address/${address}`);

  // Verify contract (optional)
  if (network.name === "goliathTestnet" || network.name === "goliathMainnet") {
    console.log("🔎 Verifying contract...");
    await hre.run("verify:verify", {
      address: address,
      constructorArguments: [],
    });
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
```

### 4. Deploy

```bash
# Set private key
echo "PRIVATE_KEY=your_private_key_here" > .env

# Deploy to mainnet
npx hardhat run scripts/deploy.js --network goliathMainnet

# Deploy to testnet
npx hardhat run scripts/deploy.js --network goliathTestnet
```

## 🎩 Deployment with Foundry

### 1. Setup

```bash
# Install Foundry
curl -L https://foundry.paradigm.xyz | bash
foundryup

# Create project
forge init my-goliath-project
cd my-goliath-project
```

### 2. Configuration

Create `foundry.toml`:

```toml
[profile.default]
src = 'src'
out = 'out'
libs = ['lib']
optimizer = true
optimizer_runs = 200

[rpc_endpoints]
goliath_mainnet = "https://rpc.goliath.net"
goliath_testnet = "https://rpc.testnet.goliath.net"

[etherscan]
goliath_mainnet = { key = "not-needed", chain = 327 }
goliath_testnet = { key = "not-needed", chain = 8901 }
```

### 3. Deploy Script

Create `script/Deploy.s.sol`:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {Script} from "forge-std/Script.sol";
import {GoliathToken} from "../src/GoliathToken.sol";

contract DeployScript is Script {
    function run() external {
        uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
        
        vm.startBroadcast(deployerPrivateKey);
        
        GoliathToken token = new GoliathToken();
        
        vm.stopBroadcast();
        
        // Log deployment
        console.log("Token deployed at:", address(token));
    }
}
```

### 4. Deploy

```bash
# Deploy
forge script script/Deploy.s.sol:DeployScript \
  --rpc-url goliath_testnet \
  --broadcast \
  --verify
```

## ⛽ Gas Optimization

### Best Practices

1. **Use Optimizer**: Enable Solidity optimizer
2. **Pack Storage**: Group similar types
3. **Short Circuit**: Order conditions efficiently
4. **Batch Operations**: Combine multiple calls

### Gas-Efficient Patterns

```solidity
// ❌ Expensive
mapping(address => uint256) public balance1;
mapping(address => uint256) public balance2;
mapping(address => uint256) public balance3;

// ✅ Efficient
struct UserData {
    uint128 balance1;
    uint128 balance2;
    uint256 balance3;
}
mapping(address => UserData) public userData;

// ❌ Expensive loop
for (uint i = 0; i < items.length; i++) {
    total += items[i].value;
}

// ✅ Efficient with unchecked
unchecked {
    for (uint i = 0; i < items.length; ++i) {
        total += items[i].value;
    }
}
```

## 🔐 Security Checklist

### Before Deployment

* [ ] Run comprehensive tests
* [ ] Audit smart contracts
* [ ] Check for reentrancy vulnerabilities
* [ ] Validate access controls
* [ ] Test upgrade mechanisms
* [ ] Verify gas optimization
* [ ] Review external calls
* [ ] Check integer overflows

### Testing Commands

```bash
# Hardhat tests
npx hardhat test
npx hardhat coverage

# Foundry tests
forge test
forge coverage

# Static analysis
npm install -g @consensys/mythril
myth analyze contracts/Token.sol

# Slither
pip install slither-analyzer
slither .
```

## 🎉 Post-Deployment

### 1. Verify Contract

```bash
# Hardhat
npx hardhat verify --network goliathTestnet \
  DEPLOYED_CONTRACT_ADDRESS \
  "Constructor Arg 1" "Constructor Arg 2"

# Foundry
forge verify-contract \
  --chain-id 8901 \
  --compiler-version v0.8.19 \
  CONTRACT_ADDRESS \
  src/Contract.sol:ContractName
```

### 2. Update Frontend

```javascript
// Update contract address
const CONTRACT_ADDRESS = "0x...";

// Update ABI
import ContractABI from './artifacts/Contract.json';

// Initialize contract
const contract = new ethers.Contract(
  CONTRACT_ADDRESS,
  ContractABI.abi,
  signer
);
```

### 3. Monitor Contract

```javascript
// Listen to events
contract.on("Transfer", (from, to, amount) => {
  console.log(`Transfer: ${from} -> ${to}: ${amount}`);
});

// Check contract state
const totalSupply = await contract.totalSupply();
const owner = await contract.owner();
```

## 📈 Advanced Deployment

### Proxy Contracts (Upgradeable)

```solidity
// Using OpenZeppelin Upgrades
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

contract MyContractV1 is Initializable, UUPSUpgradeable {
    uint256 public value;
    
    function initialize(uint256 _value) public initializer {
        value = _value;
    }
    
    function _authorizeUpgrade(address) internal override onlyOwner {}
}
```

Deploy with proxy:

```javascript
const { deployProxy } = require('@openzeppelin/hardhat-upgrades');

const Contract = await ethers.getContractFactory("MyContractV1");
const proxy = await deployProxy(Contract, [42], {
  initializer: 'initialize',
  kind: 'uups'
});
```

### Multi-Signature Deployment

```javascript
// Deploy with Gnosis Safe
const safeTx = await safe.createTransaction({
  to: FACTORY_ADDRESS,
  data: deploymentData,
  value: 0
});

const txHash = await safe.getTransactionHash(safeTx);
const signatures = await collectSignatures(txHash);
await safe.executeTransaction(safeTx, signatures);
```

## 🆘 Common Issues

### "Insufficient funds"

```bash
# Check balance
cast balance YOUR_ADDRESS --rpc-url https://rpc.testnet.goliath.net

# Get test XCN
# Open faucet bot: https://t.me/GoliathFaucetBot
# /request <ADDRESS>
# /request <ADDRESS> sepoliaxcn
# /request <ADDRESS> sepoliaxcn staked
```

### "Gas price too low"

```javascript
// Increase gas price
const tx = await contract.deploy({
  gasPrice: ethers.parseUnits('2', 'gwei'),
  gasLimit: 3000000
});
```

### "INSUFFICIENT\_GAS" on transfers

If a simple transfer fails with `INSUFFICIENT_GAS`, the destination address likely does not exist yet on Goliath. Lazy account creation requires \~587,000 gas instead of 21,000. Always use `eth_estimateGas` rather than hardcoding the gas limit. See the [Lazy Account Creation Guide](/developer-guide/lazy-create-gas.md) for details.

### "Contract size exceeds limit"

```solidity
// Enable optimizer in hardhat.config.js
solidity: {
  settings: {
    optimizer: {
      enabled: true,
      runs: 200
    }
  }
}
```

## 📚 Resources

### Templates & Examples

* [Goliath Contract Templates](https://github.com/goliath/templates)
* [DeFi Protocol Examples](https://github.com/goliath/defi-examples)
* [NFT Marketplace Template](https://github.com/goliath/nft-marketplace)

### Tools

* [Contract Wizard](https://wizard.openzeppelin.com/)
* [Remix IDE](https://remix.ethereum.org)
* [Tenderly](https://tenderly.co) - Debugging
* [Mainnet Explorer](https://explorer.goliath.net) / [Testnet Explorer](https://testnet.explorer.goliath.net)

### Learning

* [Solidity Documentation](https://docs.soliditylang.org/)
* [OpenZeppelin Contracts](https://docs.openzeppelin.com/)
* [Smart Contract Security](https://consensys.github.io/smart-contract-best-practices/)

***

*Deploy with confidence on Goliath Network - where performance meets reliability.*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.goliath.net/developer-guide/deploying-contracts.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
