Gas-optimized implementations of the Poseidon2 hash function for the EVM. Updates on TG
See impl-specific documentation:
Goldilocks support is planned.
| Implementation | hash_1 | hash_2 | hash_3 | Notes |
|---|---|---|---|---|
| Solidity | 264,090 | 264,836 | 265,733 | Reference implementation |
| Yul | 20,304 | 20,304 | 20,304 | Recommended optimised |
| Huff | 14,845 | 14,845 | 14,845 | Heavy optimised |
It is recommended to use yul implementation.
- Install the dependency.
# Foundry
forge install zemse/poseidon2-evm
# npm
npm install poseidon2-evm- Import the file
import {Poseidon2} from "poseidon2-evm/src/bn254/Poseidon2.sol";
contract MyContract {
function someWork() external {
uint left;
uint right;
// Default: calls the globally deployed Yul contract with checked input
uint result = Poseidon2.hash_2(left, right);
}
function someExperiment() external pure returns (uint256) {
uint left;
uint right;
// Explicitly use Huff contract (lowest gas, unchecked)
uint result = Poseidon2.hash_2_huff_unchecked(secret, nullifier);
}
}Copy the interface into your project IPoseidon2.sol and use it.
interface IPoseidon2 {
function hash_2(uint256 x, uint256 y) external pure returns (uint256);
}
contract MyContract {
function someWork() external {
uint left;
uint right;
// Makes direct call to the contract. But you need to make sure inputs i.e.
// left & right are valid field elements (< PRIME).
uint result = IPoseidon2(0xDeployedAddress).hash_2(left, right);
}
}Contracts are deployed with same address on all EVM networks.
| Implementation | Address |
|---|---|
| Yul | TODO |
| Huff | TODO |
- Run tests: forge test
- Generate gas report: ./gas-report.sh
- Generate yul code: npm run generate:yul
- Generare huff code: npm run generate:huff
Tests include correctness vectors, fuzz testing against the reference Solidity implementation, and overflow safety checks for the ADDMOD optimization.
Not yet audited. These implementations have not undergone a formal third-party security audit. Review the code before using in production. Also see SECURITY.md.
MIT