UNPKG

shove-js

Version:

SDK for shove.bet

95 lines 3.39 kB
import { Contract } from "ethers"; export class BaseContract { constructor(address, abi, runner) { Object.defineProperty(this, "contract", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "address", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "blockTimestampCache", { enumerable: true, configurable: true, writable: true, value: new Map() }); this.address = address; this.contract = new Contract(address, abi, runner); } getInterface() { return this.contract.interface; } async call(method, args, overrides) { const fn = this.contract[method]; if (typeof fn !== "function") { throw new Error(`Method "${method}" not found on contract`); } const result = await fn(...args, { ...overrides }); return result; } async read(method, args = [], overrides) { return this.call(method, args, overrides); } async write(method, args = [], overrides) { return this.call(method, args, overrides); } async getEvents(filterArgs = [], fromBlock, toBlock, parser) { const provider = this.contract.runner?.provider; if (!provider || typeof provider.getLogs !== "function") { throw new Error("Provider not available to fetch logs from the contract"); } const parseRaw = (log) => { try { const parsed = this.contract.interface.parseLog(log); return { name: parsed.name, args: parsed.args, blockNumber: log.blockNumber, transactionHash: log.transactionHash, log, }; } catch (err) { return { name: undefined, args: undefined, blockNumber: log.blockNumber, transactionHash: log.transactionHash, log, }; } }; let logs; logs = await provider.getLogs({ address: this.address, topics: filterArgs, fromBlock, toBlock, }); const parsedEntries = logs.map(parseRaw); const uniqueBlocks = Array.from(new Set(parsedEntries.map((e) => e.blockNumber).filter((bn) => !!bn))); const missingBlocks = uniqueBlocks.filter((bn) => !this.blockTimestampCache.has(bn)); if (missingBlocks.length) { const blockPromises = missingBlocks.map((bn) => provider.getBlock(bn)); const blocks = await Promise.all(blockPromises); for (const b of blocks) { if (b) this.blockTimestampCache.set(b.number, b.timestamp); } } const entriesWithTs = parsedEntries.map((e) => ({ ...e, timestamp: this.blockTimestampCache.get(e.blockNumber) ?? null, })); if (parser) return entriesWithTs.map(parser); return entriesWithTs; } } //# sourceMappingURL=BaseContract.js.map