forked from rkalis/truffle-plugin-verify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify.js
296 lines (246 loc) · 10.3 KB
/
verify.js
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
const axios = require('axios')
const cliLogger = require('cli-logger')
const delay = require('delay')
const fs = require('fs')
const path = require('path')
const querystring = require('querystring')
const { API_URLS, EXPLORER_URLS, RequestStatus, VerificationStatus } = require('./constants')
const { enforce, enforceOrThrow, normaliseContractPath } = require('./util')
const { version } = require('./package.json')
const logger = cliLogger({ level: 'info' })
module.exports = async (config) => {
// Set debug logging
if (config.debug) logger.level('debug')
logger.debug('DEBUG logging is turned ON')
logger.debug(`Running truffle-plugin-verify v${version}`)
const options = parseConfig(config)
// Verify each contract
const contractNameAddressPairs = config._.slice(1)
// Track which contracts failed verification
const failedContracts = []
for (const contractNameAddressPair of contractNameAddressPairs) {
logger.info(`Verifying ${contractNameAddressPair}`)
try {
const [contractName, contractAddress] = contractNameAddressPair.split('@')
const artifact = getArtifact(contractName, options)
if (contractAddress) {
logger.debug(`Custom address ${contractAddress} specified`)
if (!artifact.networks[`${options.networkId}`]) {
artifact.networks[`${options.networkId}`] = {}
}
artifact.networks[`${options.networkId}`].address = contractAddress
}
let status = await verifyContract(artifact, options)
if (status === VerificationStatus.FAILED) {
failedContracts.push(`${contractNameAddressPair}`)
} else {
// Add link to verified contract on Etherscan
const explorerUrl = `${EXPLORER_URLS[options.networkId]}/${artifact.networks[`${options.networkId}`].address}#contracts`
status += `: ${explorerUrl}`
}
logger.info(status)
} catch (error) {
logger.error(error.message)
failedContracts.push(contractNameAddressPair)
}
logger.info()
}
enforce(
failedContracts.length === 0,
`Failed to verify ${failedContracts.length} contract(s): ${failedContracts.join(', ')}`,
logger
)
logger.info(`Successfully verified ${contractNameAddressPairs.length} contract(s).`)
}
const parseConfig = (config) => {
// Truffle handles network stuff, just need to get network_id
const networkId = config.network_id
const apiUrl = API_URLS[networkId]
enforce(apiUrl, `Etherscan has no support for network ${config.network} with id ${networkId}`, logger)
const etherscanApiKey = config.api_keys && config.api_keys.etherscan
const bscscanApiKey = config.api_keys && config.api_keys.bscscan
const hecoinfoApiKey = config.api_keys && config.api_keys.hecoinfo
const ftmscanApiKey = config.api_keys && config.api_keys.ftmscan
const polygonscanApiKey = config.api_keys && config.api_keys.polygonscan
const apiKey = apiUrl.includes('bscscan') && bscscanApiKey
? bscscanApiKey
: apiUrl.includes('ftmscan') && ftmscanApiKey
? ftmscanApiKey
: apiUrl.includes('hecoinfo') && hecoinfoApiKey
? hecoinfoApiKey
: apiUrl.includes('polygonscan') && polygonscanApiKey
? polygonscanApiKey
: etherscanApiKey
enforce(apiKey, 'No Etherscan API key specified', logger)
enforce(config._.length > 1, 'No contract name(s) specified', logger)
const workingDir = config.working_directory
const contractsBuildDir = config.contracts_build_directory
const contractsDir = config.contracts_directory
let forceConstructorArgsType, forceConstructorArgs
if (config.forceConstructorArgs) {
[forceConstructorArgsType, forceConstructorArgs] = config.forceConstructorArgs.split(':')
enforce(forceConstructorArgsType === 'string', 'Force constructor args must be string type', logger)
logger.debug(`Force custructor args provided: 0x${forceConstructorArgs}`)
}
return {
apiUrl,
apiKey,
networkId,
workingDir,
contractsBuildDir,
contractsDir,
forceConstructorArgs
}
}
const getArtifact = (contractName, options) => {
const artifactPath = path.resolve(options.contractsBuildDir, `${contractName}.json`)
logger.debug(`Reading artifact file at ${artifactPath}`)
enforceOrThrow(fs.existsSync(artifactPath), `Could not find ${contractName} artifact at ${artifactPath}`)
// Stringify + parse to make a deep copy (to avoid bugs with PR #19)
return JSON.parse(JSON.stringify(require(artifactPath)))
}
const verifyContract = async (artifact, options) => {
enforceOrThrow(
artifact.networks && artifact.networks[`${options.networkId}`],
`No instance of contract ${artifact.contractName} found for network id ${options.networkId}`
)
const res = await sendVerifyRequest(artifact, options)
enforceOrThrow(res.data, `Failed to connect to Etherscan API at url ${options.apiUrl}`)
if (res.data.result === VerificationStatus.ALREADY_VERIFIED) {
return VerificationStatus.ALREADY_VERIFIED
}
enforceOrThrow(res.data.status === RequestStatus.OK, res.data.result)
return verificationStatus(res.data.result, options)
}
const sendVerifyRequest = async (artifact, options) => {
const compilerVersion = extractCompilerVersion(artifact)
const encodedConstructorArgs = options.forceConstructorArgs || await fetchConstructorValues(artifact, options)
const inputJSON = getInputJSON(artifact, options)
// Remove the 'project:' prefix that was added in Truffle v5.3.14
const relativeFilePath = artifact.ast.absolutePath.replace('project:', '')
const postQueries = {
apikey: options.apiKey,
module: 'contract',
action: 'verifysourcecode',
contractaddress: artifact.networks[`${options.networkId}`].address,
sourceCode: JSON.stringify(inputJSON),
codeformat: 'solidity-standard-json-input',
contractname: `${relativeFilePath}:${artifact.contractName}`,
compilerversion: compilerVersion,
constructorArguements: encodedConstructorArgs
}
try {
logger.debug('Sending verify request with POST arguments:')
logger.debug(JSON.stringify(postQueries, null, 2))
return await axios.post(options.apiUrl, querystring.stringify(postQueries))
} catch (error) {
logger.debug(error.message)
throw new Error(`Failed to connect to Etherscan API at url ${options.apiUrl}`)
}
}
const extractCompilerVersion = (artifact) => {
const metadata = JSON.parse(artifact.metadata)
const compilerVersion = `v${metadata.compiler.version}`
return compilerVersion
}
const fetchConstructorValues = async (artifact, options) => {
const contractAddress = artifact.networks[`${options.networkId}`].address
// Fetch the contract creation transaction to extract the input data
let res
try {
const qs = querystring.stringify({
apiKey: options.apiKey,
module: 'account',
action: 'txlist',
address: contractAddress,
page: 1,
sort: 'asc',
offset: 1
})
const url = `${options.apiUrl}?${qs}`
logger.debug(`Retrieving constructor parameters from ${url}`)
res = await axios.get(url)
} catch (error) {
logger.debug(error.message)
throw new Error(`Failed to connect to Etherscan API at url ${options.apiUrl}`)
}
// The last part of the transaction data is the constructor arguments
// If it can't be accessed for any reason, try using empty constructor arguments
if (res.data && res.data.status === RequestStatus.OK && res.data.result[0] !== undefined) {
const constructorArgs = res.data.result[0].input.substring(artifact.bytecode.length)
logger.debug(`Constructor parameters retrieved: 0x${constructorArgs}`)
return constructorArgs
} else {
logger.debug('Could not retrieve constructor parameters, using empty parameters as fallback')
return ''
}
}
const getInputJSON = (artifact, options) => {
const metadata = JSON.parse(artifact.metadata)
const libraries = getLibraries(artifact, options)
const sources = {}
for (const contractPath in metadata.sources) {
// If we're on Windows we need to de-Unixify the path so that Windows can read the file
// We also need to replace the 'project:' prefix so that the file can be read
const normalisedContractPath = normaliseContractPath(contractPath, options.contractsDir)
const absolutePath = require.resolve(normalisedContractPath)
const content = fs.readFileSync(absolutePath, 'utf8')
// Remove the 'project:' prefix that was added in Truffle v5.3.14
const relativeContractPath = contractPath.replace('project:', '')
sources[relativeContractPath] = { content }
}
const inputJSON = {
language: metadata.language,
sources,
settings: {
remappings: metadata.settings.remappings,
optimizer: metadata.settings.optimizer,
evmVersion: metadata.settings.evmVersion,
libraries
}
}
return inputJSON
}
const getLibraries = (artifact, options) => {
const libraries = {
// Example data structure of libraries object in Standard Input JSON
// 'ConvertLib.sol': {
// 'ConvertLib': '0x...',
// 'OtherLibInSameSourceFile': '0x...'
// }
}
const links = artifact.networks[`${options.networkId}`].links || {}
for (const libraryName in links) {
// Retrieve the source path for this library
const libraryArtifact = getArtifact(libraryName, options)
// Remove the 'project:' prefix that was added in Truffle v5.3.14
const librarySourceFile = libraryArtifact.ast.absolutePath.replace('project:', '')
// Add the library to the object of libraries for this source path
const librariesForSourceFile = libraries[librarySourceFile] || {}
librariesForSourceFile[libraryName] = links[libraryName]
libraries[librarySourceFile] = librariesForSourceFile
}
return libraries
}
const verificationStatus = async (guid, options) => {
logger.debug(`Checking status of verification request ${guid}`)
// Retry API call every second until status is no longer pending
while (true) {
await delay(1000)
try {
const qs = querystring.stringify({
apiKey: options.apiKey,
module: 'contract',
action: 'checkverifystatus',
guid
})
const verificationResult = await axios.get(`${options.apiUrl}?${qs}`)
if (verificationResult.data.result !== VerificationStatus.PENDING) {
return verificationResult.data.result
}
} catch (error) {
logger.debug(error.message)
throw new Error(`Failed to connect to Etherscan API at url ${options.apiUrl}`)
}
}
}