# eth_getCode - Moonbase RPC Method

Returns the bytecode at a given address on Moonbase Alpha.

> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.

## When to Use This Method

`eth_getCode` is essential for Moonbeam developers, dApp testers, and teams validating cross-chain integrations:

- **Contract Verification** -- Verify that the bytecode deployed at an address matches the expected source code compilation output on Moonbase
- **EOA vs Contract Detection** -- Determine whether an address is an externally owned account (returns `0x`) or a deployed smart contract (returns bytecode)
- **Proxy Pattern Detection** -- Check if a proxy contract has been initialized by examining whether its implementation slot contains code
- **Security Auditing** -- Validate contract deployments before interacting with them on EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification

## Common Use Cases

### 1. Detect Contract vs EOA

Determine if an address is a smart contract or a regular wallet on Moonbase:

```javascript
import { JsonRpcProvider } from 'ethers';

const provider = new JsonRpcProvider('https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY');

async function isContract(address) {
  const code = await provider.getCode(address);
  return code !== '0x' && code !== '0x0';
}

async function classifyAddress(address) {
  if (await isContract(address)) {
    const balance = await provider.getBalance(address);
    console.log('Contract at', address, '- balance:', balance.toString());
    return 'contract';
  }
  console.log('EOA at', address);
  return 'eoa';
}
```

### 2. Verify Proxy Implementation Initialization

Check whether a proxy contract has been initialized with an implementation on Moonbase:

```javascript
import { JsonRpcProvider } from 'ethers';

const provider = new JsonRpcProvider('https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY');

async function checkProxyInitialized(proxyAddress) {
  // EIP-1967 implementation slot
  const IMPL_SLOT = '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc';
  
  const slotValue = await provider.getStorage(proxyAddress, IMPL_SLOT);
  const implAddress = '0x' + slotValue.slice(26);
  
  const implCode = await provider.getCode(implAddress);
  const hasCode = implCode !== '0x' && implCode !== '0x0';
  
  console.log(`Proxy: ${proxyAddress}`);
  console.log(`Implementation: ${implAddress} (has code: ${hasCode})`);
  
  return hasCode;
}
```

### 3. Batch Contract Detection

Scan multiple addresses to classify them efficiently:

```javascript
async function scanAddresses(provider, addresses) {
  const results = [];
  
  for (const address of addresses) {
    try {
      const code = await provider.getCode(address);
      const type = (code === '0x' || code === '0x0') ? 'EOA' : 'Contract';
      results.push({ address, type, bytecodeSize: code.length });
    } catch (error) {
      results.push({ address, type: 'Error', error: error.message });
    }
  }
  
  const summary = {
    total: results.length,
    contracts: results.filter(r => r.type === 'Contract').length,
    eoas: results.filter(r => r.type === 'EOA').length,
    errors: results.filter(r => r.type === 'Error').length
  };
  
  console.log('Scan results:', summary);
  return { results, summary };
}
```

## Best Practices

- Check both `0x` and `0x0` return values -- different client implementations return one or the other for EOAs
- Use historical block numbers with `eth_getCode` to verify contract state at a specific point in time
- For proxy pattern detection, combine `eth_getCode` with `eth_getStorageAt` to fully verify initialization
- Cache bytecode by address, as deployed contract code is immutable
- The return value length is roughly 2x the deployment bytecode size (hex encoding doubles the byte count)

## Request Parameters

- `address` (`DATA, required`): 20-byte address
- `blockParameter` (`QUANTITY|TAG, required`): Block number or tag

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getCode",
  "params": [
    "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
    "latest"
  ],
  "id": 1
}
```

## Response Fields

- `result` (`DATA, required`): Contract bytecode or 0x if EOA

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "<value>"
}
```

## Code Examples

cURL
JavaScript
Python
Go

```bash
curl -X POST https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_getCode",
    "params": [
      "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
      "latest"
    ],
    "id": 1
  }'
```

```javascript
import { JsonRpcProvider } from 'ethers';

const provider = new JsonRpcProvider('https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY');

const address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';
const code = await provider.getCode(address);

if (code === '0x') {
  console.log('Address is an EOA (externally owned account)');
} else {
  console.log('Address is a contract');
  console.log('Bytecode length:', code.length);
}

// Check if address is a contract
async function isContract(address) {
  const code = await provider.getCode(address);
  return code !== '0x';
}
```

```python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY'))

address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
code = w3.eth.get_code(address)

if code == b'':
    print('Address is an EOA')
else:
    print('Address is a contract')
    print(f'Bytecode length: {len(code.hex())}')

# Check if address is a contract
def is_contract(address):
    code = w3.eth.get_code(address)
    return code != b''
```

```go
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY")
    if err != nil {
        log.Fatal(err)
    }

    address := common.HexToAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
    code, err := client.CodeAt(context.Background(), address, nil)
    if err != nil {
        log.Fatal(err)
    }

    if len(code) == 0 {
        fmt.Println("Address is an EOA")
    } else {
        fmt.Printf("Contract bytecode length: %d\n", len(code))
    }
}
```

## Related Methods

- [`eth_getBalance`](https://www.dwellir.com/docs/moonbase-alpha/eth_getBalance) - Get account balance
- [`eth_getStorageAt`](https://www.dwellir.com/docs/moonbase-alpha/eth_getStorageAt) - Get contract storage
