UNPKG

@broxus/js-core

Version:

MobX-based JavaScript Core library

46 lines (45 loc) 2.4 kB
import { debug, groupCollapsed, groupEnd, sliceAddress } from '@broxus/js-utils'; import { baseLabelStyle, getScanLink, inheritTextStyle, successTextStyle } from '../console'; import { resolveTvmAddress } from '../utils/resolve-tvm-address'; const cache = new Map(); const ttl = 10 * 1000; export async function getFullContractState(connection, address, options) { const addr = address.toString().toLowerCase(); try { const cached = cache.get(addr); if (cached && !options?.force) { const _ttl = options?.ttl ?? ttl; const { state, timestamp } = cached; if (Date.now() - timestamp < _ttl && state) { if (process.env.NODE_ENV !== 'production') { connection.getProviderState().then(providerState => { groupCollapsed(`%cRPC%c Full contract state [%c${sliceAddress(addr.toString())}%c] retrieved from cache`, baseLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle); debug(`Address: %c${sliceAddress(addr.toString())}%c ${getScanLink(addr.toString(), providerState.networkId.toString())}`, successTextStyle, inheritTextStyle); debug(`Last updated at: %c${new Date(timestamp).toLocaleString()}`, inheritTextStyle); groupEnd(); }).catch(() => undefined); } return await state; } } const state = connection.getFullContractState({ address: resolveTvmAddress(address) }) .then(r => r.state) .catch(e => { cache.delete(addr); throw e; }); if (process.env.NODE_ENV !== 'production') { connection.getProviderState().then(providerState => { groupCollapsed(`%cRPC%c Request a full contract state [%c${sliceAddress(addr.toString())}%c]`, baseLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle); debug(`Address: %c${sliceAddress(addr.toString())}%c ${getScanLink(addr.toString(), providerState.networkId.toString())}`, successTextStyle, inheritTextStyle); groupEnd(); }).catch(() => undefined); } cache.set(addr, { state, timestamp: Date.now() }); return await state; } catch (e) { cache.delete(addr); return undefined; } }