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 XDC Network.
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'.
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 XDC Network applications, this method ensures consistent hashing across the entire EVM-compatible ecosystem, enabling interoperability with Ethereum tools and libraries.
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
- Data Verification: Generate hashes to verify data integrity and detect tampering
- 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 data verification
- Unique Identifier Generation: Create deterministic IDs from arbitrary data
- Off-chain Signature Preparation: Hash messages before signing for off-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://xdc-rpc.dwellir.com');
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
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('transfer(address,uint256)');
// Output: 0xa9059cbb
Using web3.js
import Web3 from 'web3';
const web3 = new Web3('https://xdc-rpc.dwellir.com');
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
const eventSignature = 'Transfer(address,address,uint256)';
const eventTopic = web3.utils.sha3(eventSignature);
console.log('Event topic:', eventTopic);
return { clientHash, rpcHash, eventTopic };
}
Advanced Example: Creating Merkle Proofs
import { JsonRpcProvider, keccak256, solidityPackedKeccak256 } from 'ethers';
async function createMerkleLeaf(address, amount) {
const provider = new JsonRpcProvider('https://xdc-rpc.dwellir.com');
// Pack and hash data (typically done client-side)
const packed = solidityPackedKeccak256(
['address', 'uint256'],
[address, amount]
);
console.log('Merkle leaf:', packed);
return packed;
}
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