Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions packages/utils/src/decode-message.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import type { BigNumberish } from "ethers"
import { decodeBytes32String } from "ethers/abi"
import { toBeHex } from "ethers/utils"
import { BigNumberish, decodeBytes32String, toBeHex } from "ethers"

/**
* Typically used for decoding on-chain Semaphore messages.
Expand All @@ -9,9 +7,20 @@ import { toBeHex } from "ethers/utils"
* This function help devs converting bigint messages to text again.
* If the original message was not text the output of this
* function won't probably be human-readable text.
*
* Note: If the input is not a valid bytes32 string, the function will return null instead of throwing.
* This makes the function safer to use with untrusted or dynamic input.
*
* @param message The Semaphore message as a bigint.
* @returns The Semaphore message as a text.
* @returns The Semaphore message as a text, or null if decoding fails.
*/
export default function decodeMessage(message: BigNumberish) {
return decodeBytes32String(toBeHex(message, 32))
try {
// Attempt to decode the message as a bytes32 string.
// If the input is not valid, return null instead of throwing an error.
return decodeBytes32String(toBeHex(message, 32))
} catch {
// Decoding failed (invalid input or not a valid bytes32 string)
return null
}
}