-
Notifications
You must be signed in to change notification settings - Fork 0
/
abiFactory.ts
94 lines (73 loc) · 2.77 KB
/
abiFactory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'
import fetch from 'node-fetch'
import { AbiItem } from 'web3-utils'
import { config } from '@aleph-indexer/core'
import { Blockchain } from '@aleph-indexer/framework'
import { EthereumClient } from '../../../sdk/index.js'
export type Abi = [AbiItem]
// @todo: Implement inmemory cache
export class EthereumAbiFactory {
constructor(
protected basePath: string,
protected ethereumClient: EthereumClient,
protected blockchainId: Blockchain = Blockchain.Ethereum,
protected apiKey = config.ETHEREUM_SCAN_API_KEY,
) {}
async getAbi(address: string): Promise<Abi | undefined> {
address = address.toLowerCase()
let abi = await this.getAbiFromCache(address)
if (abi) return abi
const isContract = await this.ethereumClient.isContractAddress(address)
if (!isContract) return
abi = await this.getAbiFromRemote(address)
if (!abi) throw new Error(`Abi not found for address ${address}`)
await this.saveAbiInCache(address, abi)
this.log(`ABI ${address}`, abi)
return abi
}
protected async getAbiFromCache(address: string): Promise<Abi | void> {
try {
const cachePath = path.join(this.basePath, `${address}.json`)
this.log('load abi from cache => ', cachePath)
const file = await readFile(cachePath, 'utf8')
const abi = JSON.parse(file)
this.log('cached abi => ', abi)
return abi
} catch (e) {
// @note: module not found
if ((e as any)?.code === 'ENOENT') return undefined
this.log('cached abi error', e)
throw e
}
}
protected async saveAbiInCache(address: string, abi: Abi): Promise<void> {
const cachePath = path.join(this.basePath, `${address}.json`)
this.log('save abi in cache => ', cachePath)
await writeFile(cachePath, JSON.stringify(abi))
}
protected async getAbiFromRemote(address: string): Promise<Abi> {
const url = this.getRemoteUrl(address)
const response = await fetch(url)
// @note: http errors
if (response.status !== 200) throw new Error(await response.text())
const body: any = await response.json()
// @note: Rate limit error sent with status 200 OK...
// {
// "status": "0",
// "message": "NOTOK",
// "result": "Max rate limit reached, please use API Key for higher rate limit"
// }
if (body.status === '0' || body.message === 'NOTOK')
throw new Error(body.result)
return body.result as Abi
}
protected getRemoteUrl(address: string): string {
return `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}${
this.apiKey ? `&apikey=${this.apiKey}` : ''
}`
}
protected log(...msgs: any[]): void {
console.log(`${this.blockchainId} ${msgs.join(' ')}`)
}
}