UNPKG

@worldcoin/idkit-core

Version:

The identity SDK. Privacy-preserving identity and proof of personhood with World ID.

51 lines (49 loc) 1.57 kB
// src/lib/hashing.ts import { Buffer } from "buffer/index.js"; import { AbiParameters, Bytes, Hex, Hash } from "ox"; function hashToField(input) { if (Bytes.validate(input) || Hex.validate(input)) return hashEncodedBytes(input); return hashString(input); } function packAndEncode(input) { const [types, values] = input.reduce( ([types2, values2], [type, value]) => { types2.push(type); values2.push(value); return [types2, values2]; }, [[], []] ); return hashEncodedBytes(AbiParameters.encodePacked(types, values)); } function hashString(input) { const bytesInput = Buffer.from(input); return hashEncodedBytes(bytesInput); } function hashEncodedBytes(input) { const hash = BigInt(Hash.keccak256(input, { as: "Hex" })) >> 8n; const rawDigest = hash.toString(16); return { hash, digest: `0x${rawDigest.padStart(64, "0")}` }; } var solidityEncode = (types, values) => { if (types.length !== values.length) { throw new Error("Types and values arrays must have the same length."); } return { types, values }; }; var generateSignal = (signal) => { if (!signal || typeof signal === "string") return hashToField(signal ?? ""); return packAndEncode(signal.types.map((type, index) => [type, signal.values[index]])); }; var encodeAction = (action) => { if (!action) return ""; if (typeof action === "string") return action; return action.types.map((type, index) => `${type}(${action.values[index]})`).join(","); }; export { hashToField, packAndEncode, solidityEncode, generateSignal, encodeAction };