# Getting Started

## Build Powerful dApps on Goliath Network

Welcome to the Goliath developer documentation! This guide will help you set up your development environment and start building decentralized applications on one of the fastest and most secure distributed ledger platforms.

## 🎯 Overview

Goliath provides developers with:

* **⚡ EVM Compatibility**: Deploy existing Solidity contracts without modification
* **🚀 High Performance**: 100,000+ TPS with sub-second block confirmations and 3-5 second finality
* **💰 Low Costs**: Transaction fees under $0.001 USD
* **🔧 Rich Tooling**: Comprehensive SDKs and APIs
* **🌐 Dual Layer Architecture**: Access both EVM and native Core Ledger capabilities

## ⚠️ Critical: XCN Decimal Handling

{% hint style="danger" %}
**Important difference from Ethereum:** XCN uses **8 decimals** inside the EVM (`msg.value`, `address.balance`) but **18 decimals** in JSON-RPC responses. This is different from Ethereum where everything uses 18 decimals consistently.

**Before you start coding, read the** [**XCN Decimal Handling Guide**](https://docs.goliath.net/developer-guide/decimal-handling) **to avoid critical bugs.**
{% endhint %}

## ⚠️ Critical: Lazy Account Creation Gas

{% hint style="warning" %}
**Transfers to new addresses require \~587,000 gas**, not the usual 21,000. Goliath automatically creates accounts on first receive ("lazy-create"), and the `CryptoCreate` operation costs significantly more gas. **Never hardcode `gasLimit: 21000`** -- always call `eth_estimateGas` before submitting.

**Read the** [**Lazy Account Creation Guide**](https://docs.goliath.net/developer-guide/lazy-create-gas) **for details and code examples.**
{% endhint %}

## 🛠️ Prerequisites

Before you begin, ensure you have:

* **Node.js** (v16 or higher) - [Download](https://nodejs.org/)
* **Git** - [Download](https://git-scm.com/)
* **Code Editor** (VS Code recommended) - [Download](https://code.visualstudio.com/)
* **MetaMask** or similar Web3 wallet - [Install](https://metamask.io/)

## 🌐 Network Configuration

### Mainnet Details

```javascript
const GOLIATH_MAINNET = {
  name: 'Goliath Mainnet',
  chainId: 327,
  rpcUrl: 'https://rpc.goliath.net',
  explorerUrl: 'https://explorer.goliath.net',
  nativeCurrency: {
    name: 'XCN',
    symbol: 'XCN',
    decimals: 18  // JSON-RPC uses 18 decimals (but EVM internally uses 8)
  }
};
```

### Testnet Details

```javascript
const GOLIATH_TESTNET = {
  name: 'Goliath Testnet',
  chainId: 8901,
  rpcUrl: 'https://rpc.testnet.goliath.net',
  explorerUrl: 'https://testnet.explorer.goliath.net',
  nativeCurrency: {
    name: 'XCN',
    symbol: 'XCN',
    decimals: 18  // JSON-RPC uses 18 decimals (but EVM internally uses 8)
  }
};
```

### API Endpoints

#### Mainnet

| Service                 | Endpoint                                                           | Description                           |
| ----------------------- | ------------------------------------------------------------------ | ------------------------------------- |
| **EVM RPC**             | [`https://rpc.goliath.net`](https://rpc.goliath.net)               | Ethereum JSON-RPC compatible endpoint |
| **Block Explorer**      | [`https://explorer.goliath.net`](https://explorer.goliath.net)     | Transaction and contract explorer     |
| **Validator Dashboard** | [`https://validators.goliath.net`](https://validators.goliath.net) | Validator monitoring                  |

#### Testnet

| Service         | Endpoint                                                                     | Description                           |
| --------------- | ---------------------------------------------------------------------------- | ------------------------------------- |
| **EVM RPC**     | [`https://rpc.testnet.goliath.net`](https://rpc.testnet.goliath.net)         | Ethereum JSON-RPC compatible endpoint |
| **Core Node**   | [`https://testnet.core.goliath.net`](https://testnet.core.goliath.net)       | Native Goliath Core Node API          |
| **Mirror Node** | [`https://testnet.indexer.goliath.net`](https://testnet.indexer.goliath.net) | Historical data and queries           |
| **WebSocket**   | `wss://rpc.testnet.goliath.net/ws`                                           | Real-time event subscriptions         |

## 📝 Your First Smart Contract

### 1. Install Development Tools

```bash
# Install Hardhat (recommended framework)
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox

# Or install Foundry for advanced users
curl -L https://foundry.paradigm.xyz | bash
foundryup
```

### 2. Initialize Your Project

#### Using Hardhat:

```bash
mkdir my-goliath-dapp
cd my-goliath-dapp
npx hardhat init
```

Select "Create a JavaScript project" and follow the prompts.

### 3. Configure for Goliath

Update `hardhat.config.js`:

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

const PRIVATE_KEY = process.env.PRIVATE_KEY || "your-private-key-here";

module.exports = {
  solidity: "0.8.19",
  networks: {
    goliathMainnet: {
      url: "https://rpc.goliath.net",
      chainId: 327,
      accounts: [PRIVATE_KEY],
      gasPrice: 1000000000, // 1 Gwei
    },
    goliathTestnet: {
      url: "https://rpc.testnet.goliath.net",
      chainId: 8901,
      accounts: [PRIVATE_KEY],
      gasPrice: 1000000000, // 1 Gwei
    }
  },
  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"
        }
      }
    ]
  }
};
```

### 4. Write Your Smart Contract

Create `contracts/HelloGoliath.sol`:

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

contract HelloGoliath {
    string public greeting;
    mapping(address => uint256) public greetingCounts;
    
    event GreetingChanged(address indexed user, string newGreeting, uint256 count);
    
    constructor(string memory _greeting) {
        greeting = _greeting;
    }
    
    function setGreeting(string memory _newGreeting) public {
        greeting = _newGreeting;
        greetingCounts[msg.sender]++;
        
        emit GreetingChanged(msg.sender, _newGreeting, greetingCounts[msg.sender]);
    }
    
    function getGreeting() public view returns (string memory) {
        return greeting;
    }
    
    function getMyGreetingCount() public view returns (uint256) {
        return greetingCounts[msg.sender];
    }
}
```

### 5. Deploy Your Contract

Create `scripts/deploy.js`:

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

async function main() {
  console.log("Deploying to Goliath Testnet...");
  
  const HelloGoliath = await hre.ethers.getContractFactory("HelloGoliath");
  const hello = await HelloGoliath.deploy("Hello from Goliath!");
  
  await hello.waitForDeployment();
  
  const address = await hello.getAddress();
  console.log("Contract deployed to:", address);
  console.log("View on explorer:", `https://explorer.goliath.net/address/${address}`);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
```

Deploy:

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

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

## 🌐 Interacting with Your Contract

### Using Web3.js

```javascript
const Web3 = require('web3');
const web3 = new Web3('https://rpc.testnet.goliath.net');

// Contract ABI (get from compilation)
const abi = [...]; 
const contractAddress = '0x...'; // Your deployed contract address

const contract = new web3.eth.Contract(abi, contractAddress);

// Read data
const greeting = await contract.methods.getGreeting().call();
console.log('Current greeting:', greeting);

// Write data (requires private key)
const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey);
web3.eth.accounts.wallet.add(account);

const tx = await contract.methods.setGreeting('Hello Goliath!').send({
  from: account.address,
  gas: 100000,
  gasPrice: web3.utils.toWei('1', 'gwei')
});

console.log('Transaction hash:', tx.transactionHash);
```

### Using Ethers.js

```javascript
const { ethers } = require('ethers');

// Connect to Goliath
const provider = new ethers.JsonRpcProvider('https://rpc.testnet.goliath.net');
const signer = new ethers.Wallet(privateKey, provider);

// Connect to contract
const contract = new ethers.Contract(contractAddress, abi, signer);

// Read data
const greeting = await contract.getGreeting();
console.log('Current greeting:', greeting);

// Write data
const tx = await contract.setGreeting('Hello from Ethers!');
const receipt = await tx.wait();
console.log('Transaction confirmed in block:', receipt.blockNumber);
```

## ⛽ Gas Optimization

Goliath offers extremely low gas fees, but optimization is still important:

### Gas Prices

| Priority     | Gas Price | Use Case                |
| ------------ | --------- | ----------------------- |
| **Low**      | 0.5 Gwei  | Non-urgent transactions |
| **Standard** | 1 Gwei    | Regular transactions    |
| **Fast**     | 2 Gwei    | Priority transactions   |

### Best Practices

1. **Batch Operations**: Combine multiple operations in a single transaction
2. **Use Events**: Emit events instead of storing data when possible
3. **Optimize Storage**: Pack structs and use appropriate data types
4. **View Functions**: Mark read-only functions as `view` or `pure`

## 🔧 Development Tools

### Essential Tools

| Tool             | Purpose                  | Link                                             |
| ---------------- | ------------------------ | ------------------------------------------------ |
| **Hardhat**      | Development framework    | [hardhat.org](https://hardhat.org)               |
| **Foundry**      | Advanced testing suite   | [getfoundry.sh](https://getfoundry.sh)           |
| **Remix**        | Online IDE               | [remix.ethereum.org](https://remix.ethereum.org) |
| **OpenZeppelin** | Secure contracts library | [openzeppelin.com](https://openzeppelin.com)     |
| **Tenderly**     | Debugging & monitoring   | [tenderly.co](https://tenderly.co)               |

### Goliath-Specific Tools

* **Mainnet Explorer**: [explorer.goliath.net](https://explorer.goliath.net)
* **Testnet Explorer**: [testnet.explorer.goliath.net](https://testnet.explorer.goliath.net)
* **Onyx App (Mainnet DeFi)**: [app.onyx.org](https://app.onyx.org)
* **Slingshot (Testnet DeFi)**: [slingshot.goliath.net](https://slingshot.goliath.net)
* **Contract Addresses**: [Full registry](https://docs.goliath.net/reference/contracts) for both networks
* **Slingshot Integration**: [Swap, Bridge, Migrate, Yield contract map](https://docs.goliath.net/developer-guide/slingshot-integration)
* **Test Tokens (Telegram Bot)**: [Goliath Faucet Bot](https://t.me/GoliathFaucetBot)
  * `/request <ADDRESS>`
  * `/request <ADDRESS> sepoliaxcn`
  * `/request <ADDRESS> sepoliaxcn staked`

## 🎯 Advanced Features

### 1. Native Token Integration

Goliath supports native token creation without smart contracts:

```javascript
// Using Core Ledger API
const response = await fetch('https://testnet.core.goliath.net/api/v1/tokens', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    name: 'My Token',
    symbol: 'MTK',
    decimals: 18,
    initialSupply: '1000000',
    treasury: accountId
  })
});
```

### 2. File Storage Service

Store files directly on the network:

```javascript
// Store file on Goliath
const fileId = await goliathClient.createFile({
  contents: Buffer.from('Hello World'),
  memo: 'My first file on Goliath'
});
```

### 3. Consensus Service (Goliath Mesh)

Achieve fair ordering for off-chain applications:

```javascript
// Submit message to consensus
const message = {
  threadId: 'my-app-thread',
  data: { action: 'trade', amount: 100 },
  timestamp: Date.now()
};

const consensusTimestamp = await goliathMesh.submitMessage(message);
```

## 📚 Learning Resources

### Tutorials

1. [**Deploy an ERC-20 Token**](https://github.com/Onyx-Protocol/goliath-docs/blob/main/developer-guide/smart-contracts/erc-standards.md)
2. [**Build a DeFi Application**](https://docs.goliath.net/developer-guide/deploying-contracts)
3. [**Integrate with Goliath Mesh**](https://github.com/Onyx-Protocol/goliath-docs/blob/main/services/goliath-mesh.md)

### Code Examples

* **Simple dApp**: Basic wallet interaction
* **NFT Marketplace**: Full-stack NFT platform
* **DeFi Protocol**: Lending and borrowing
* **DAO Governance**: On-chain voting system

### Documentation

* [**EVM JSON-RPC Reference**](https://docs.goliath.net/apis/evm-json-rpc)
* [**Core Ledger API**](https://github.com/Onyx-Protocol/goliath-docs/blob/main/apis/core-ledger/README.md)
* [**Smart Contract Best Practices**](https://github.com/Onyx-Protocol/goliath-docs/blob/main/security/best-practices.md)

## 🆘 Common Issues & Solutions

### Connection Issues

```javascript
// Always use try-catch for RPC calls
try {
  const balance = await provider.getBalance(address);
} catch (error) {
  console.error('RPC Error:', error);
  // Implement retry logic or fallback
}
```

### Gas Estimation

```javascript
// Always estimate gas before sending -- do NOT hardcode gasLimit.
// Transfers to new addresses on Goliath require ~587,000 gas (lazy-create),
// not the usual 21,000. See: smart-contracts/lazy-create-gas.md
const estimatedGas = await contract.estimateGas.myMethod(params);
const tx = await contract.myMethod(params, {
  gasLimit: estimatedGas * 120n / 100n // Add 20% buffer for safety
});
```

### Transaction Monitoring

```javascript
// Monitor transaction status
const receipt = await provider.waitForTransaction(txHash, 1, 30000);
if (receipt.status === 0) {
  console.error('Transaction failed');
  // Handle failure
}
```

## 🎆 What's Next?

Now that you have your development environment set up:

1. [**Deploy Smart Contracts**](https://docs.goliath.net/developer-guide/deploying-contracts) - Deep dive into deployment
2. [**Hardhat Integration**](https://github.com/Onyx-Protocol/goliath-docs/blob/main/developer-guide/smart-contracts/hardhat.md) - Advanced Hardhat configuration
3. [**ERC Standards**](https://github.com/Onyx-Protocol/goliath-docs/blob/main/developer-guide/smart-contracts/erc-standards.md) - Implement token standards
4. [**Gas Optimization**](https://github.com/Onyx-Protocol/goliath-docs/blob/main/apis/evm-json-rpc/gas-fees.md) - Minimize transaction costs
5. [**Security Best Practices**](https://github.com/Onyx-Protocol/goliath-docs/blob/main/security/best-practices.md) - Build secure contracts

## 🤝 Get Support

* [**Telegram**](https://t.me/Onyx): Join our developer community
* [**GitHub**](https://github.com/Onyx-Protocol): Report issues and contribute
* [**Community Forum**](https://community.onyx.org/): Technical discussions
* **Office Hours**: Weekly developer calls

***

*Ready to build? Start deploying your smart contracts on Goliath today!*


---

# 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/getting-started.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.
