-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsourcify-abi.ts
More file actions
108 lines (96 loc) · 3 KB
/
sourcify-abi.ts
File metadata and controls
108 lines (96 loc) · 3 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { getAddress } from 'viem'
import { Effect } from 'effect'
import * as RequestModel from './request-model.js'
interface SourcifyResponse {
output: {
abi: object
}
}
const endpoint = 'https://repo.sourcify.dev/contracts/'
type FetchResult =
| { type: 'success'; data: RequestModel.ContractABI[] }
| { type: 'missing'; reason: string }
| { type: 'error'; cause: unknown }
async function fetchContractABI({ address, chainId }: RequestModel.GetContractABIStrategyParams): Promise<FetchResult> {
try {
const normalisedAddress = getAddress(address)
const full_match = await fetch(`${endpoint}/full_match/${chainId}/${normalisedAddress}/metadata.json`)
if (full_match.status === 200) {
const json = (await full_match.json()) as SourcifyResponse
return {
type: 'success',
data: [
{
type: 'address',
address,
chainID: chainId,
abi: JSON.stringify(json.output.abi),
},
],
}
}
const partial_match = await fetch(`${endpoint}/partial_match/${chainId}/${normalisedAddress}/metadata.json`)
if (partial_match.status === 200) {
const json = (await partial_match.json()) as SourcifyResponse
return {
type: 'success',
data: [
{
type: 'address',
address,
chainID: chainId,
abi: JSON.stringify(json.output.abi),
},
],
}
}
// Check if it's a 404 (not found) which means the contract is not verified on Sourcify
if (full_match.status === 404 && partial_match.status === 404) {
return {
type: 'missing',
reason: 'Contract not found on Sourcify',
}
}
return {
type: 'error',
cause: `Failed to fetch ABI for ${address} on chain ${chainId}`,
}
} catch (error) {
return {
type: 'error',
cause: error,
}
}
}
export const SourcifyStrategyResolver = (): RequestModel.ContractAbiResolverStrategy => {
return {
id: 'sourcify-strategy',
type: 'address',
resolver: (req: RequestModel.GetContractABIStrategyParams) =>
Effect.withSpan(
Effect.gen(function* () {
const result = yield* Effect.promise(() => fetchContractABI(req))
if (result.type === 'success') {
return result.data
} else if (result.type === 'missing') {
return yield* Effect.fail(
new RequestModel.MissingABIStrategyError(
req.address,
req.chainId,
'sourcify-strategy',
undefined,
undefined,
result.reason,
),
)
} else {
return yield* Effect.fail(
new RequestModel.ResolveStrategyABIError('sourcify', req.address, req.chainId, String(result.cause)),
)
}
}),
'AbiStrategy.SourcifyStrategyResolver',
{ attributes: { chainId: req.chainId, address: req.address } },
),
}
}