Skip to content

Commit

Permalink
Add replacer to the stringify function inside the createMemoizedFunction
Browse files Browse the repository at this point in the history
  • Loading branch information
yagopv committed Apr 26, 2024
1 parent 0bdf76b commit 10e0a93
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion packages/protocol-kit/src/utils/memoized.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,30 @@ export function createMemoizedFunction<T extends (...args: Parameters<T>) => Ret
cache: Record<string, ReturnType<T>> = {}
) {
return (...args: Parameters<T>): ReturnType<T> => {
const key = JSON.stringify(args)
const key = JSON.stringify(args, bigIntSerializerReplacer)

cache[key] = cache[key] || callback(...args)

return cache[key]
}
}

// EIP1193 providers from web3.currentProvider and hre.network.provider fail to serialize BigInts
function bigIntSerializerReplacer() {
const seen = new Set()

return (_: string, value: unknown) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return undefined
}
seen.add(value)
}

if (typeof value === 'bigint') {
return value.toString()
}

return value
}
}

0 comments on commit 10e0a93

Please sign in to comment.