-
Notifications
You must be signed in to change notification settings - Fork 47
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
63d904e
commit 5e84dd0
Showing
2 changed files
with
191 additions
and
73 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
apps/wallet-mobile/src/yoroi-wallets/cardano/wrappedCsl.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import {init} from '@emurgo/cross-csl-mobile' | ||
import {WasmModuleProxy} from '@emurgo/cross-csl-core' | ||
|
||
const cardano = init('wrappedCSL') | ||
|
||
export type CslPointer = {ptr: number; free: () => void} | ||
|
||
export const wrappedCsl = (): {csl: WasmModuleProxy; release: VoidFunction} => { | ||
let pointers: CslPointer[] = [] | ||
const track = (p: CslPointer) => pointers.push(p) | ||
const release = () => { | ||
pointers.forEach((p) => { | ||
if (p?.ptr !== 0) { | ||
try { | ||
p.free() | ||
} catch (e) {} | ||
} | ||
}) | ||
pointers = [] | ||
} | ||
|
||
const trackIfNeeded = <T>(obj: T): T => { | ||
if (typeof (obj as any)?.free === 'function') track(obj as any) | ||
if (obj instanceof Promise) { | ||
return obj.then((result) => trackIfNeeded(result)) as any | ||
} | ||
if (Array.isArray(obj)) return obj.map((o) => trackIfNeeded(o) as any) as any | ||
return obj | ||
} | ||
|
||
const proxy = new Proxy(cardano, { | ||
get(target: WasmModuleProxy, p: string | symbol, receiver: any): any { | ||
const prop = Reflect.get(target, p, receiver) | ||
if (!isClass(prop)) { | ||
return prop | ||
} | ||
|
||
return new Proxy(prop, { | ||
get: (target: any, name: string) => { | ||
if (name === 'prototype') return target[name] | ||
const isFunc = typeof target[name] === 'function' | ||
if (!isFunc) return target[name] | ||
return (...args: any[]) => { | ||
const result = target[name](...args) | ||
return trackIfNeeded(result) | ||
} | ||
}, | ||
}) | ||
}, | ||
}) | ||
|
||
return {csl: proxy, release} | ||
} | ||
|
||
const isClass = (func: any) => { | ||
return ( | ||
typeof func === 'function' && (/^\s*class\s+/.test(func.toString()) || func.name[0] === func.name[0].toUpperCase()) | ||
) | ||
} |