web3_sha3
The web3_sha3 method calculates the Keccak-256 hash of the provided data using the node's built-in cryptographic functions. Despite its name referencing SHA3, this method implements Keccak-256, which is the cryptographic hash function used throughout Ethereum-compatible blockchains, including ZetaChain's EVM layer.
This method is essential for various blockchain operations including verifying data integrity, generating unique identifiers, computing smart contract function selectors, and performing cryptographic operations that are fundamental to blockchain security. The Keccak-256 algorithm produces a 256-bit (32-byte) hash value represented as a 64-character hexadecimal string prefixed with '0x'. For ZetaChain's omnichain applications, consistent hashing is crucial for cross-chain message verification and interoperability with connected blockchains.
Understanding the distinction between Keccak-256 and the finalized SHA3-256 standard is crucial for developers. While Ethereum originally adopted Keccak before SHA-3 was finalized, the name 'web3_sha3' was retained for historical compatibility. For ZetaChain applications, this method ensures consistent hashing across the entire EVM-compatible ecosystem, enabling seamless interoperability with Ethereum, BSC, and other connected chains.
Parameters
- Data -
DATA(hex-encoded string)- The data to hash, represented as a hexadecimal string with '0x' prefix
- Can be any arbitrary data including strings, numbers, or binary data
- Input must be properly hex-encoded
{
"jsonrpc": "2.0",
"method": "web3_sha3",
"params": ["0x68656c6c6f20776f726c64"],
"id": 1
}
Returns
DATA - 32-byte Keccak-256 hash of the input data, returned as a 66-character hexadecimal string (including '0x' prefix).
Use Cases
- Cross-Chain Data Verification: Generate hashes to verify data integrity across different blockchains
- Function Selectors: Calculate the first 4 bytes of function signatures for contract interactions
- Event Topic Generation: Create topics for filtering and identifying smart contract events
- Merkle Tree Construction: Build cryptographic proofs for efficient cross-chain data verification
- Unique Identifier Generation: Create deterministic IDs for omnichain messages and transactions
- Off-chain Signature Preparation: Hash messages before signing for cross-chain verification
Best Practices for Production
- Always hex-encode input data properly using '0x' prefix to avoid errors
- Use client-side libraries for bulk hashing operations to reduce RPC load
- Cache frequently used hashes to minimize redundant computations
- Validate input data length to prevent processing overly large payloads
- Use dedicated cryptographic libraries (ethers.js, web3.js) for complex operations
- Consider implementing client-side hashing for performance-critical applications
- Document hash usage patterns for security audits and compliance reviews
Integration with Web3 Libraries
Using ethers.js
import { JsonRpcProvider, keccak256, toUtf8Bytes, hexlify } from 'ethers';
const provider = new JsonRpcProvider('https://zetachain-evm.blockpi.network/v1/rpc/public');
async function hashData() {
// Example 1: Hash a string using RPC
const message = 'hello world';
const hexMessage = hexlify(toUtf8Bytes(message));
const rpcHash = await provider.send('web3_sha3', [hexMessage]);
console.log('RPC hash:', rpcHash);
// Example 2: Hash locally (recommended for performance)
const localHash = keccak256(toUtf8Bytes(message));
console.log('Local hash:', localHash);
console.log('Hashes match:', rpcHash === localHash); // true
return rpcHash;
}
// Example 3: Calculate function selector for omnichain contracts
async function getFunctionSelector(signature) {
const hash = await provider.send('web3_sha3', [
hexlify(toUtf8Bytes(signature))
]);
const selector = hash.slice(0, 10); // First 4 bytes
console.log(`Function selector for ${signature}: ${selector}`);
return selector;
}
// Usage
getFunctionSelector('sendMessage(address,bytes)');
// Output: Function selector for cross-chain messaging
Using web3.js
import Web3 from 'web3';
const web3 = new Web3('https://zetachain-evm.blockpi.network/v1/rpc/public');
async function demonstrateHashing() {
const data = 'hello world';
// Method 1: Using web3.utils (client-side, faster)
const clientHash = web3.utils.sha3(data);
console.log('Client-side hash:', clientHash);
// Method 2: Using RPC (server-side)
const hexData = web3.utils.utf8ToHex(data);
const rpcHash = await web3.eth.extend({
methods: [{
name: 'sha3',
call: 'web3_sha3',
params: 1
}]
}).sha3(hexData);
console.log('RPC hash:', rpcHash);
// Calculate event topic for cross-chain events
const eventSignature = 'MessageSent(address,uint256,bytes)';
const eventTopic = web3.utils.sha3(eventSignature);
console.log('Cross-chain event topic:', eventTopic);
return { clientHash, rpcHash, eventTopic };
}
Advanced Example: Cross-Chain Message Hashing
import { JsonRpcProvider, keccak256, solidityPackedKeccak256 } from 'ethers';
async function createCrossChainMessageHash(
sourceChain,
destinationChain,
sender,
recipient,
amount
) {
const provider = new JsonRpcProvider('https://zetachain-evm.blockpi.network/v1/rpc/public');
// Pack and hash cross-chain message data
const messageHash = solidityPackedKeccak256(
['uint256', 'uint256', 'address', 'address', 'uint256'],
[sourceChain, destinationChain, sender, recipient, amount]
);
console.log('Cross-chain message hash:', messageHash);
return messageHash;
}
Example Request/Response
Request:
{
"jsonrpc": "2.0",
"method": "web3_sha3",
"params": ["0x68656c6c6f20776f726c64"],
"id": 1
}
Response:
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"
}
The input 0x68656c6c6f20776f726c64 is the hex encoding of "hello world", and the result is its Keccak-256 hash.
Related Methods
- eth_call - Execute contract calls that may use hashed data
- eth_getLogs - Filter events using hashed topics