@zlattice/lattice-js
Version:
Lattice blockchain TypeScript SDK with dual module support (CJS + ESM)
59 lines • 2.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlockCacheImpl = void 0;
const logger_1 = require("../logger.js");
const index_1 = require("../utils/index.js");
/**
* block cache implementation
*/
class BlockCacheImpl {
/**
* constructor
* @param config cache config
* @param httpClient http client
* @param daemonHashExpirationSeconds daemon hash expiration seconds, default is 10 seconds
*/
constructor(config, daemonHashExpirationSeconds = 10) {
this.daemonHashExpireAtMap = new Map();
this.cache = new index_1.CacheService(config);
this.daemonHashExpirationMs = daemonHashExpirationSeconds * 1000;
}
async putBlock(chainId, address, block) {
const key = `${chainId}-${address}`;
await this.cache.set(key, block);
if (!this.daemonHashExpireAtMap.has(chainId.toString())) {
this.daemonHashExpireAtMap.set(chainId.toString(), new Date(Date.now() + this.daemonHashExpirationMs));
}
}
async getBlock(chainId, address, fallback) {
const key = `${chainId}-${address}`;
const block = await this.cache.get(key);
if (!block) {
try {
const newBlock = await fallback(chainId, address);
await this.putBlock(chainId, address, newBlock);
return newBlock;
}
catch (error) {
logger_1.log.error(`Failed to get block: ${error}`);
throw error instanceof Error ? error : new Error(String(error));
}
}
const expireAt = this.daemonHashExpireAtMap.get(chainId.toString());
if (expireAt && expireAt < new Date()) {
logger_1.log.warn(`daemon hash expired, chainId: ${chainId}`);
try {
const latestBlock = await fallback(chainId, address);
this.daemonHashExpireAtMap.set(chainId.toString(), new Date(Date.now() + this.daemonHashExpirationMs));
block.currentDBlockHash = latestBlock.currentDBlockHash;
await this.cache.set(key, block);
}
catch (error) {
logger_1.log.error(`Failed to update block hash: ${error}`);
}
}
return block;
}
}
exports.BlockCacheImpl = BlockCacheImpl;
//# sourceMappingURL=block_cache.js.map