feat: add dumpable cache object for evm onchain config

This commit is contained in:
c4605
2025-03-18 22:36:53 +01:00
parent ef6522f7cb
commit fa97bbc982
3 changed files with 61 additions and 1 deletions

View File

@@ -118,6 +118,7 @@ import {
evmNativeCurrencyAddress,
} from "./xlinkSdkUtils/types"
import { SDKGlobalContext } from "./xlinkSdkUtils/types.internal"
import { DumpableCache, getCacheInside } from "./utils/DumpableCache"
export {
GetSupportedRoutesFn_Conditions,
@@ -183,6 +184,7 @@ export {
GetTimeLockedAssetsInput,
GetTimeLockedAssetsOutput,
} from "./xlinkSdkUtils/timelockFromEVM"
export type { DumpableCache } from "./utils/DumpableCache"
export interface XLinkSDKOptions {
__experimental?: {
@@ -198,6 +200,9 @@ export interface XLinkSDKOptions {
runes?: {
ignoreValidateResult?: boolean
}
evm?: {
onChainConfigCachePrepared?: (cache: DumpableCache) => void
}
}
evm?: {
/**
@@ -231,6 +236,17 @@ export class XLinkSDK {
const cacheEVMOnChainConfig =
options.evm?.cacheOnChainConfig ?? defaultConfig.evm?.cacheOnChainConfig
let onChainConfigCache:
| undefined
| SDKGlobalContext["evm"]["onChainConfigCache"]
if (cacheEVMOnChainConfig) {
const onChainConfigDumpableCache = new DumpableCache()
options.__experimental?.evm?.onChainConfigCachePrepared?.(
onChainConfigDumpableCache,
)
onChainConfigCache = getCacheInside(onChainConfigDumpableCache)
}
this.sdkContext = {
routes: {
detectedCache: new Map(),
@@ -262,7 +278,7 @@ export class XLinkSDK {
evm: {
routesConfigCache: new Map(),
feeRateCache: new Map(),
onChainConfigCache: cacheEVMOnChainConfig ? new Map() : undefined,
onChainConfigCache,
viemClients: {
...defaultEvmClients,
...options.evm?.viemClients,

View File

@@ -0,0 +1,43 @@
import { props } from "./promiseHelpers"
import { GeneralCacheInterface } from "./types/GeneralCacheInterface"
const dumpableCacheKey = Symbol("dumpableCacheKey")
export const getCacheInside = <K, V>(
obj: DumpableCache,
): GeneralCacheInterface<K, V> => {
return obj[dumpableCacheKey] as any
}
export class DumpableCache {
readonly [dumpableCacheKey]: Map<unknown, unknown>
constructor() {
this[dumpableCacheKey] = new Map()
}
async dump(): Promise<string> {
return JSON.stringify({
["**NOTICE**"]:
"This is a dumped cache, DO NOT use it or modify it, only for SDK internal usage.",
version: 1,
data: await props(Object.fromEntries(this[dumpableCacheKey])),
})
}
async load(data: string): Promise<void> {
try {
const parsed = JSON.parse(data)
if (parsed.version !== 1) {
throw new Error("Unsupported cache version")
}
this[dumpableCacheKey].clear()
for (const [key, value] of Object.entries(parsed.data)) {
this[dumpableCacheKey].set(key, value)
}
} catch (error) {
console.trace("Failed to load cache", error)
}
}
}

View File

@@ -13,6 +13,7 @@ import { EVMAddress } from "./types"
export interface SDKGlobalContextCache<K, V>
extends GeneralCacheInterface<K, V> {}
export function withGlobalContextCache<K, V>(
cache: undefined | SDKGlobalContextCache<K, Promise<V>>,
cacheKey: K,