# web3_sha3 - Immutable RPC Method

Returns the Keccak-256 hash (not standard SHA3-256) of the given data on Immutable.

> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.

**Important**: Despite the method name, `web3_sha3` computes Keccak-256, which differs from the NIST-standardized SHA3-256. Ethereum adopted Keccak before NIST finalized the SHA-3 standard with different padding.

## When to Use This Method

`web3_sha3` is helpful for AAA game studios, indie game developers, and NFT gaming teams seeking enforceable royalties:

- **Hash Verification** - Confirm that your local Keccak-256 implementation matches the node's output
- **Smart Contract Development** - Compute function selectors and event topic hashes needed for ABI encoding
- **Data Integrity Checks** - Hash data server-side via RPC and compare against expected values
- **Debugging** - Verify hashing results when troubleshooting transaction or contract interactions

## Best Practices

- Input data must be hex-encoded with a `0x` prefix; plain text strings will cause errors
- Use for quick Keccak-256 hashing without a client-side library, but prefer local hashing for performance
- Compute function selectors by taking the first 4 bytes of the hash result

## Request Parameters

- `data` (`DATA, required`): The hex-encoded data to hash (must be 0x prefixed)

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "web3_sha3",
  "params": ["0x68656c6c6f"],
  "id": 1
}
```

## Response Fields

- `result` (`DATA, required`): The Keccak-256 hash of the provided data (32 bytes, 0x prefixed)

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8"
}
```

## Error Responses

### Error Response

- Code: `-32602`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32602,
    "message": "invalid argument 0: hex string without 0x prefix"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Go

```bash
curl -X POST https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "web3_sha3",
    "params": ["0x68656c6c6f"],
    "id": 1
  }'
```

```javascript
import { JsonRpcProvider, keccak256, toUtf8Bytes, hexlify } from 'ethers';

const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');

// Using RPC
const hash = await provider.send('web3_sha3', ['0x68656c6c6f']);
console.log('RPC hash:', hash);

// Using ethers locally (faster, no network call)
const localHash = keccak256(toUtf8Bytes('hello'));
console.log('Local hash:', localHash);

// Verify they match
console.log('Match:', hash === localHash);
```

```python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))

# Using RPC
data = '0x68656c6c6f'  # "hello" in hex
rpc_hash = w3.provider.make_request('web3_sha3', [data])['result']
print(f'RPC hash: {rpc_hash}')

# Using web3.py locally (faster)
local_hash = w3.keccak(text='hello').hex()
print(f'Local hash: 0x{local_hash}')

# Using requests directly
import requests

response = requests.post(
    'https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY',
    json={
        'jsonrpc': '2.0',
        'method': 'web3_sha3',
        'params': ['0x68656c6c6f'],
        'id': 1
    }
)
print(f'Hash: {response.json()["result"]}')
```

```go
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/rpc"
    "golang.org/x/crypto/sha3"
)

func main() {
    client, err := rpc.Dial("https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
    if err != nil {
        log.Fatal(err)
    }

    // Using RPC
    var rpcHash string
    err = client.CallContext(context.Background(), &rpcHash, "web3_sha3", "0x68656c6c6f")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("RPC hash: %s\n", rpcHash)

    // Using local Keccak-256
    hasher := sha3.NewLegacyKeccak256()
    hasher.Write([]byte("hello"))
    localHash := fmt.Sprintf("0x%x", hasher.Sum(nil))
    fmt.Printf("Local hash: %s\n", localHash)
}
```

## Common Use Cases

### 1. Function Selector Computation

Compute Solidity function selectors for ABI encoding:

```javascript
async function getFunctionSelector(provider, signature) {
  // Convert signature to hex
  const hexSignature = '0x' + Buffer.from(signature).toString('hex');

  // Hash via RPC
  const hash = await provider.send('web3_sha3', [hexSignature]);

  // Function selector is the first 4 bytes
  const selector = hash.slice(0, 10);
  console.log(`${signature} => ${selector}`);
  return selector;
}

// Example: compute selectors for common ERC-20 functions
const selectors = {
  'transfer(address,uint256)': await getFunctionSelector(provider, 'transfer(address,uint256)'),
  'balanceOf(address)': await getFunctionSelector(provider, 'balanceOf(address)'),
  'approve(address,uint256)': await getFunctionSelector(provider, 'approve(address,uint256)'),
};
```

### 2. Hash Verification Between Local and RPC

Verify your local hashing matches the node to catch library misconfigurations:

```javascript
async function verifyHashingConsistency(provider) {
  const testCases = [
    { input: '0x', label: 'empty bytes' },
    { input: '0x68656c6c6f', label: '"hello"' },
    { input: '0x0123456789abcdef', label: 'hex data' },
  ];

  for (const { input, label } of testCases) {
    const rpcHash = await provider.send('web3_sha3', [input]);
    const localHash = keccak256(input);

    const match = rpcHash === localHash;
    console.log(`${label}: ${match ? 'PASS' : 'FAIL'}`);

    if (!match) {
      console.error(`  RPC:   ${rpcHash}`);
      console.error(`  Local: ${localHash}`);
    }
  }
}
```

### 3. Event Topic Hash Generation

Generate event topic hashes for filtering logs:

```python
from web3 import Web3

def get_event_topic(w3, event_signature):
    """Generate the topic hash for an event signature."""
    hex_sig = '0x' + event_signature.encode().hex()
    result = w3.provider.make_request('web3_sha3', [hex_sig])
    return result['result']

w3 = Web3(Web3.HTTPProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))

# Common ERC-20 event topics
topics = {
    'Transfer(address,address,uint256)': get_event_topic(w3, 'Transfer(address,address,uint256)'),
    'Approval(address,address,uint256)': get_event_topic(w3, 'Approval(address,address,uint256)'),
}

for sig, topic in topics.items():
    print(f'{sig}\n  => {topic}')
```

## Related Methods

- [`eth_call`](https://www.dwellir.com/docs/immutable/eth_call) - Execute a call without creating a transaction
- [`eth_getCode`](https://www.dwellir.com/docs/immutable/eth_getCode) - Get contract bytecode at an address
- [`web3_clientVersion`](https://www.dwellir.com/docs/immutable/web3_clientVersion) - Get node client version
