-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathetherscanVerifyContractApi.js
336 lines (293 loc) · 9.08 KB
/
etherscanVerifyContractApi.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
const fetch = require('isomorphic-fetch');
const fs = require('fs');
const path = require('path');
const { runProcess } = require('./helpers');
const proxyFile = path.join(__dirname, './build/proxyAddresses.json');
const FormData = require('form-data');
require('dotenv').config({ path: path.resolve(process.cwd(), './.env.private')});
const contractToLibrary = {
'TwoKeyUpgradableExchange' : ['PriceDiscovery'],
'TwoKeyRegistry' : ['Call'],
'TwoKeySignatureValidator' : ['Call'],
'TwoKeyParticipationMiningPool' : ['Call']
}
let API;
let EXPLORER;
/**
* Function to build the endpoints
* @param networkId
*/
const buildEndpoint = (networkId) => {
if(networkId.toString() === '3') {
API = 'api-ropsten.etherscan.io';
EXPLORER = 'ropsten.etherscan.io';
}
if(networkId.toString() === '1') {
API = 'api.etherscan.io';
EXPLORER = 'etherscan.io';
}
}
/**
* Function to build etherscan url depending on the network
* @param contractAddress
* @returns {string}
*/
const buildEtherscanUrl = (contractAddress) => {
return `https://${EXPLORER}/address/${contractAddress}#code`;
}
/**
* Mock method to simulate async call
*
* @param val {any}
* @param time {Number}
* @return {Promise<any>}
*/
const wait = (time = 500, val = true) => new Promise((resolve) => {
setTimeout(() => { resolve(val); }, time);
});
/**
* Load all deployed proxies
* @returns {{}}
*/
const loadAddressesAndNetworks = () => {
// Open proxyAddresses file
let fileObject = {};
if (fs.existsSync(proxyFile)) {
fileObject = JSON.parse(fs.readFileSync(proxyFile, { encoding: 'utf8' }));
}
return fileObject;
};
/**
* Load library address from build
* @param libraryName
* @param networkId
* @returns {null|*}
*/
const loadLibraryAddress = (libraryName, networkId) => {
const artifactFile = path.join(__dirname, `./build/contracts/${libraryName}.json`);
let artifact = {}
if(fs.existsSync(artifactFile)) {
artifact = JSON.parse(fs.readFileSync(artifactFile));
return artifact['networks'][networkId].address;
} else {
console.log('Library does not exist.');
return null;
}
}
/**
* By passing contract name and directory name (just parent folder)
* @param directoryName
* @param contractName
* @returns {Promise<void>}
*/
const flattenContract = async (directoryName, contractName) => {
// Compute the path stuff
let workingDirectory = process.cwd();
let solcAllowPaths = `--solc-path="solc --allow-paths ${workingDirectory}/contracts/2key/ 2key=${workingDirectory}/contracts/2key"`
let contractPath = `contracts/2key/${directoryName}/${contractName}.sol`;
let outputPath = `${workingDirectory}/flattenedContracts/${contractName+"Flattened"}.sol`
try {
await runProcess('solidity_flattener', [solcAllowPaths,contractPath,'--output',outputPath])
} catch (e) {
console.log('Error caught during flattening.');
}
}
/**
* Fetch all contracts inside specific directory
* @type {function(*): string[]}
*/
const fetchAllContracts = ((directoryName) => {
let contracts = fs.readdirSync(`contracts/2key/${directoryName}`);
return contracts.map(contractName => contractName.substring(0, contractName.indexOf('.sol')))
})
/**
* Function to flatten all contracts in selected directory
* @type {function(*=): Promise<void>}
*/
const flattenContracts = (async (directoryName) => {
let contracts = fetchAllContracts(directoryName);
for (const contract of contracts) {
await flattenContract(directoryName, contract)
.then(r => console.log('Contract flattened: ', contract));
}
})
const checkLoadedFile = (contracts, contractName, networkId) => {
if(!contracts[contractName]) {
return {
'status' : 1,
'message': 'Contract does not have any address. Probably it is abstract.'
}
} else if(!contracts[contractName][networkId]) {
return {
'status' : 1,
'message': 'Contract is not deployed to selected network.'
}
}
return {
'status' : 0
}
}
/**
* Function to run contract verification
* @param contractName
* @param networkId
* @returns {Promise<string>}
*/
const verifyContract = async(contractName, networkId) => {
let contracts = loadAddressesAndNetworks();
let resp = checkLoadedFile(contracts, contractName, networkId);
if(resp.status === 0) {
let contractAddress = contracts[contractName][networkId].implementationAddressLogic;
let contract = fs.readFileSync(__dirname + `/flattenedContracts/${contractName}Flattened.sol`,'utf8');
// Build a new form
let form = new FormData();
form.append( 'apikey' , process.env.ETHERSCAN_API_KEY)
form.append( 'module' , 'contract')
form.append( 'action' , 'verifysourcecode')
form.append( 'contractaddress' , contractAddress)
form.append( 'sourceCode' , contract)
form.append( 'codeformat', 'solidity-single-file' )
form.append( 'contractname',contractName)
form.append( 'compilerversion','v0.4.24+commit.e67f0147')
form.append( 'optimizationUsed' , '0')
form.append( 'runs',200)
form.append( 'constructorArguements' , "")
form.append('evmversion',"")
// In case contract has libraries
if(contractToLibrary[contractName]) {
let libraries = contractToLibrary[contractName];
for(let i=0; i<libraries.length; i++) {
let libraryName = libraries[i];
let libraryAddress = loadLibraryAddress(libraryName, networkId);
form.append(`libraryname${i+1}`, libraryName);
form.append(`libraryaddress${i+1}`, libraryAddress);
}
}
await etherscanApiCall(form);
console.log('Etherscan url: ', buildEtherscanUrl(contractAddress));
}
}
/**
* Function to retry calls until the response is given
* @param guid
* @returns {Promise<any>}
*/
const retryVerify = async (guid) => {
let url = `https://${API}/api?apikey=${process.env.ETHERSCAN_API_KEY}&guid=${guid}&module=contract&action=checkverifystatus`
const resp = await fetch(
url,
{
method: 'GET'
},
);
if (!resp) {
await wait(10000);
return retryVerify(guid);
}
return resp.json();
};
/**
*
* @param form
* @returns {Promise<void>}
*/
const etherscanApiCall = async (form) => {
const resp = await fetch(
`http://${API}/api`,
{
method: 'POST',
body: form
}
).then((r) => {
return r.json();
});
if (resp.status !== '0') {
let guid = resp.result;
console.log('✅ Contract submitted for verification --> Receipt:',guid);
await wait(10000);
const resp1 = await retryVerify(guid);
console.log('Verification status: ', resp1);
}
else if (resp.status === '0' && resp.result === 'Contract source code already verified') {
console.log(`✅ This contract is already verified`)
}
else {
console.log('❌ There was an issue with verification request.');
console.log(resp);
}
}
/**
*
* @returns {Promise<void>}
*/
async function main() {
const mode = process.argv[2];
switch (mode) {
case '--flattenAll': {
const dirName = process.argv[3];
await flattenContracts(dirName);
process.exit(0);
break;
}
case '--flattenOne': {
const dirName = process.argv[3];
const contractName = process.argv[4];
await flattenContract(dirName, contractName);
process.exit(0);
break;
}
case '--verifyContract': {
let contractName = process.argv[3].toString();
let networkId = process.argv[4].toString();
buildEndpoint(networkId);
await verifyContract(contractName, networkId);
process.exit(0);
break;
}
case '--verifyAllSingletons' : {
let contracts = fs.readdirSync(`contracts/2key/singleton-contracts`);
contracts = contracts.map(contractName => contractName.substring(0, contractName.indexOf('.sol')));
const networkId = process.argv[3].toString();
buildEndpoint(networkId);
for(const contract of contracts) {
console.log(contract,networkId);
await verifyContract(contract, networkId);
}
process.exit(0);
break;
}
case '--logVerifiedSingletons' : {
let contracts = fs.readdirSync(`contracts/2key/singleton-contracts`);
contracts = contracts.map(contractName => contractName.substring(0, contractName.indexOf('.sol')));
const networkId = process.argv[3].toString();
let contractAddresses = loadAddressesAndNetworks();
for(const contractName of contracts) {
let resp = checkLoadedFile(contractAddresses, contractName, networkId);
if(resp.status === 1) {
continue;
}
let contractImplementation = contractAddresses[contractName][networkId].implementationAddressLogic;
let contractProxy = contractAddresses[contractName][networkId].Proxy;
console.log(JSON.stringify({
'Contract name' : contractName,
'Contract verified implementation' : buildEtherscanUrl(contractImplementation),
'Contract verified proxy' : buildEtherscanUrl(contractProxy)
}
,
0,
3
)
);
}
process.exit(0);
break;
}
default:
console.log('Bye');
break;
}
}
main().catch((e) => {
console.log(e);
process.exit(1);
});