Skip to content

Commit

Permalink
Improve memoizing
Browse files Browse the repository at this point in the history
  • Loading branch information
yagopv committed Apr 30, 2024
1 parent e10c7e7 commit 4d94af6
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions packages/protocol-kit/src/utils/memoized.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import SafeProvider from '../SafeProvider'

export function createMemoizedFunction<T extends (...args: Parameters<T>) => ReturnType<T>>(
callback: T,
cache: Record<string, ReturnType<T>> = {}
) {
const replacer = createBigIntSerializerReplacer()
const replacer = createSafeContractSerializerReplacer()
return (...args: Parameters<T>): ReturnType<T> => {
const key = JSON.stringify(args, replacer)

Expand All @@ -13,19 +15,27 @@ export function createMemoizedFunction<T extends (...args: Parameters<T>) => Ret
}

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

return (_: string, value: unknown) => {
if (typeof value === 'object' && value !== null) {
// Serialize Bigints as strings
if (typeof value === 'bigint') {
return value.toString()
}

// Avoid circular references
if (value instanceof SafeProvider && value !== null) {
if (seen.has(value)) {
return undefined
}
seen.add(value)
}

if (typeof value === 'bigint') {
return value.toString()
return {
$safeProvider: {
provider: typeof value.provider === 'object' ? 'EIP1193Provider' : value.provider,
signer: value.signer
}
}
}

return value
Expand Down

0 comments on commit 4d94af6

Please sign in to comment.