-
Notifications
You must be signed in to change notification settings - Fork 63
/
hardhat.config.ts
694 lines (619 loc) · 18.9 KB
/
hardhat.config.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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// This adds support for typescript paths mappings
import 'tsconfig-paths/register'
import '@nomiclabs/hardhat-waffle'
import '@tenderly/hardhat-tenderly'
import 'hardhat-contract-sizer'
import 'hardhat-deploy'
import 'hardhat-gas-reporter'
import '@nomiclabs/hardhat-ethers'
import '@typechain/hardhat'
import fs from 'fs'
import path from 'path'
import {
TransactionReceipt,
TransactionRequest,
} from '@ethersproject/providers'
//import { HardhatEthersHelpers } from '@nomiclabs/hardhat-ethers/src/types'
import chalk from 'chalk'
import { config } from 'dotenv'
import { Signer, utils } from 'ethers'
//import { HardhatUserConfig, task } from '@tenderly/hardhat-tenderly'
import {
HardhatNetworkHDAccountsUserConfig,
NetworkUserConfig,
} from 'hardhat/types'
import rrequire from './helpers/rrequire'
import semver from 'semver'
import { task ,HardhatUserConfig} from 'hardhat/config'
import { HardhatEthersHelpers } from '@nomiclabs/hardhat-ethers/types'
require('@mangrovedao/hardhat-test-solidity');
const NODE_VERSION = 'v16.13.1'
if (!semver.satisfies(process.version, NODE_VERSION))
throw new Error(
`Incorrect NodeJS version being used (${process.version}). Expected: ${NODE_VERSION}`
)
config()
const { isAddress, getAddress, formatUnits, parseUnits, parseEther } = utils
const {
COMPILING,
CMC_KEY,
DEFAULT_NETWORK,
FORKING_NETWORK,
SAVE_GAS_REPORT,
SKIP_SIZER,
TESTING,
} = process.env
const isCompiling = COMPILING === 'true'
const skipContractSizer = SKIP_SIZER === 'true' && !isCompiling
if (!isCompiling) {
rrequire(path.resolve(__dirname, 'helpers', 'tasks'))
require('./helpers/hre-extensions')
}
const isTesting = TESTING === '1'
if (isTesting) {
require('./helpers/chai-helpers')
}
//
// Select the network you want to deploy to here:
//
const defaultNetwork = DEFAULT_NETWORK ?? 'hardhat'
const pathToMnemonic = path.resolve(__dirname, 'mnemonic.secret')
export const getMnemonic = (): string => {
try {
return fs.readFileSync(pathToMnemonic).toString().trim()
} catch (e) {
// @ts-ignore
if (defaultNetwork !== 'localhost') {
console.log(
'☢️ WARNING: No mnemonic file created for a deploy account. Try `yarn run generate` and then `yarn run account`.'
)
}
}
return ''
}
const accounts: HardhatNetworkHDAccountsUserConfig = {
mnemonic: getMnemonic(),
count: 15,
accountsBalance: parseEther('100000000').toString(),
}
const networkUrls: { [network: string]: string } = {
mainnet: process.env.MAINNET_RPC_URL ?? '',
kovan: process.env.KOVAN_RPC_URL ?? '',
rinkeby: process.env.RINKEBY_RPC_URL ?? 'https://eth-rinkeby.alchemyapi.io/v2/k78WV2Yf8yVKW42DzDXz4EKfHgRyR1kK',
ropsten: process.env.ROPSTEN_RPC_URL ?? '',
polygon: process.env.POLYGON_RPC_URL ?? '',
mumbai: process.env.MUMBAI_RPC_URL ?? '',
goerli: process.env.GOERLI_RPC_URL ?? '',
xdai: process.env.XDAI_RPC_URL ?? '',
rinkebyArbitrum: process.env.RINKEBY_ARBITRUM_RPC_URL ?? '',
optimism: process.env.OPTIMISM_RPC_URL ?? '',
kovanOptimism: process.env.KOVAN_OPTIMISM_RPC_URL ?? '',
fujiAvalanche: process.env.FUJI_AVALANCHE_RPC_URL ?? '',
mainnetAvalanche: process.env.MAINNET_AVALANCHE_RPC_URL ?? '',
testnetHarmony: process.env.TESTNET_HARMONY_RPC_URL ?? '',
mainnetHarmony: process.env.MAINNET_HARMONY_RPC_URL ?? '',
}
const getLatestDeploymentBlock = (networkName: string): number | undefined => {
try {
return parseInt(
fs
.readFileSync(
path.resolve(
__dirname,
'deployments',
networkName,
'.latestDeploymentBlock'
)
)
.toString()
)
} catch {
// Network deployment does not exist
}
}
const networkConfig = (config: NetworkUserConfig): NetworkUserConfig => ({
live: true,
...config,
accounts,
gas: 'auto',
saveDeployments: true
})
/*
📡 This is where you configure your deploy configuration for 🏗 scaffold-eth
check out `packages/scripts/deploy.js` to customize your deployment
out of the box it will auto deploy anything in the `contracts` folder and named *.sol
plus it will use *.args for constructor args
*/
const mainnetGwei = 21
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
export default <HardhatUserConfig>{
defaultNetwork,
etherscan: {
apiKey: '{see `updateEtherscanConfig` function in utils/hre-extensions.ts}',
},
tenderly: {
username: 'soltel',
project: '{see `updateTenderlyConfig` function in utils/hre-extensions.ts}',
},
paths: {
cache: './generated/cache',
artifacts: './generated/artifacts',
},
typechain: {
outDir: './generated/typechain',
},
external: {
contracts: [
{
artifacts: 'node_modules/hardhat-deploy/extendedArtifacts',
},
],
},
solidity: {
compilers: [
{
version: '0.8.6',
settings: {
optimizer: {
enabled: !isTesting,
runs: 200,
},
},
},
{
version: '0.4.18',
settings: {
optimizer: {
enabled: !isTesting,
runs: 200,
},
},
},
{
version: '0.4.24',
settings: {
optimizer: {
enabled: !isTesting,
runs: 200,
},
},
},
],
},
ovm: {
solcVersion: '0.8.4',
},
contractSizer: {
runOnCompile: skipContractSizer,
alphaSort: false,
disambiguatePaths: false,
},
/**
* gas reporter configuration that let's you know
* an estimate of gas for contract deployments and function calls
* More here: https://hardhat.org/plugins/hardhat-gas-reporter.html
*/
gasReporter: {
enabled: true,
currency: 'USD',
coinmarketcap: CMC_KEY,
outputFile: SAVE_GAS_REPORT ? 'gas-reporter.txt' : undefined,
noColors: !!SAVE_GAS_REPORT,
showMethodSig: false,
showTimeSpent: true,
},
namedAccounts: {
deployer: {
default: 0, // here this will by default take the first account as deployer
},
funder: 1,
miner: 2
},
// if you want to deploy to a testnet, mainnet, or xdai, you will need to configure:
// 1. An Infura key (or similar)
// 2. A private key for the deployer
// DON'T PUSH THESE HERE!!!
// An `example.env` has been provided in the Hardhat root. Copy it and rename it `.env`
// Follow the directions, and uncomment the network you wish to deploy to.
networks: {
hardhat: networkConfig({
chainId: 31337,
live: false,
allowUnlimitedContractSize: true,
saveDeployments: !isTesting,
forking:undefined
/*
FORKING_NETWORK == null
? undefined
: {
enabled: true,
url: networkUrls[FORKING_NETWORK],
blockNumber: getLatestDeploymentBlock(FORKING_NETWORK),
},
*/
}),
localhost: networkConfig({
url: 'http://localhost:8545',
live: false,
}),
mainnet: networkConfig({
url: networkUrls.mainnet,
chainId: 1,
gasPrice: mainnetGwei * 1000000000,
}),
kovan: networkConfig({
url: networkUrls.kovan,
chainId: 42,
}),
rinkeby: networkConfig({
url: networkUrls.rinkeby,
chainId: 4,
}),
ropsten: networkConfig({
url: networkUrls.ropsten,
chainId: 3,
}),
goerli: networkConfig({
url: networkUrls.goerli,
// chainId: ,
}),
xdai: networkConfig({
url: networkUrls.xdai,
// chainId: ,
gasPrice: 1000000000,
}),
polygon: networkConfig({
url: networkUrls.polygon,
chainId: 137,
// gasPrice: 1000000000,
}),
mumbai: networkConfig({
url: networkUrls.mumbai,
gasPrice: 2100000000, // @lazycoder - deserves another Sherlock badge
chainId: 80001,
}),
rinkebyArbitrum: networkConfig({
url: networkUrls.rinkebyArbitrum,
gasPrice: 0,
companionNetworks: {
l1: 'rinkeby',
},
}),
localArbitrum: networkConfig({
url: 'http://localhost:8547',
gasPrice: 0,
companionNetworks: {
l1: 'localArbitrumL1',
},
live: false,
}),
localArbitrumL1: networkConfig({
url: 'http://localhost:7545',
gasPrice: 0,
companionNetworks: {
l2: 'localArbitrum',
},
live: false,
}),
optimism: networkConfig({
url: networkUrls.optimism,
companionNetworks: {
l1: 'mainnet',
},
}),
kovanOptimism: networkConfig({
url: networkUrls.kovanOptimism,
companionNetworks: {
l1: 'kovan',
},
}),
localOptimism: networkConfig({
url: 'http://localhost:8545',
companionNetworks: {
l1: 'localOptimismL1',
},
live: false,
}),
localOptimismL1: networkConfig({
url: 'http://localhost:9545',
gasPrice: 0,
companionNetworks: {
l2: 'localOptimism',
},
live: false,
}),
localAvalanche: networkConfig({
url: 'http://localhost:9650/ext/bc/C/rpc',
gasPrice: 225000000000,
chainId: 43112,
live: false,
}),
fujiAvalanche: networkConfig({
url: networkUrls.fujiAvalanche,
gasPrice: 225000000000,
chainId: 43113,
}),
mainnetAvalanche: networkConfig({
url: networkUrls.mainnetAvalanche,
gasPrice: 225000000000,
chainId: 43114,
}),
testnetHarmony: networkConfig({
url: networkUrls.testnetHarmony,
gasPrice: 1000000000,
chainId: 1666700000,
}),
mainnetHarmony: networkConfig({
url: networkUrls.mainnetHarmony,
gasPrice: 1000000000,
chainId: 1666600000,
}),
},
mocha: {
timeout: 60000,
},
}
const DEBUG = false
const debug = (text: string): void => {
if (DEBUG) {
console.log(text)
}
}
task('wallet', 'Create a wallet (pk) link', async (_, { ethers }) => {
const randomWallet = ethers.Wallet.createRandom()
const privateKey = randomWallet._signingKey().privateKey
console.log(`🔐 WALLET Generated as ${randomWallet.address}`)
console.log(`🔗 http://localhost:3000/pk#${privateKey}`)
})
task('fundedwallet', 'Create a wallet (pk) link and fund it with deployer?')
.addOptionalParam(
'amount',
'Amount of ETH to send to wallet after generating'
)
.addOptionalParam('url', 'URL to add pk to')
.setAction(async (taskArgs, { ethers }) => {
const randomWallet = ethers.Wallet.createRandom()
console.log(`🔐 WALLET Generated as ${randomWallet.address}`)
const url: string = taskArgs.url ? taskArgs.url : 'http://localhost:3000'
const amount: string = taskArgs.amount ? taskArgs.amount : '0.01'
const tx = {
to: randomWallet.address,
value: ethers.utils.parseEther(amount),
}
// SEND USING LOCAL DEPLOYER MNEMONIC IF THERE IS ONE
// IF NOT SEND USING LOCAL HARDHAT NODE:
const localDeployerMnemonic = getMnemonic()
if (localDeployerMnemonic) {
let deployerWallet = ethers.Wallet.fromMnemonic(localDeployerMnemonic)
deployerWallet = deployerWallet.connect(ethers.provider)
console.log(
`💵 Sending ${amount} ETH to ${randomWallet.address} using deployer account`
)
const sendResult = await deployerWallet.sendTransaction(tx)
console.log()
console.log(`${url}/pk#${randomWallet.privateKey}`)
console.log()
return sendResult
} else {
console.log(
`💵 Sending ${amount} ETH to ${randomWallet.address} using local node`
)
console.log()
console.log(`${url}/pk#${randomWallet.privateKey}`)
console.log()
return await send(ethers.provider.getSigner(), tx)
}
})
task(
'generate',
'Create a mnemonic for builder deploys',
async (_, { ethers }) => {
const wallet = ethers.Wallet.createRandom()
if (DEBUG) {
console.log('mnemonic', wallet.mnemonic.phrase)
console.log('fullPath', wallet.mnemonic.path)
console.log('privateKey', wallet.privateKey)
}
console.log(
`🔐 Account Generated as ${wallet.address} and set as mnemonic in packages/hardhat`
)
console.log(
"💬 Use 'yarn run account' to get more information about the deployment account."
)
fs.writeFileSync(`./${wallet.address}.secret`, wallet.mnemonic.phrase)
fs.writeFileSync('./mnemonic.secret', wallet.mnemonic.phrase)
}
)
task(
'mineContractAddress',
'Looks for a deployer account that will give leading zeros'
)
.addOptionalParam('searchFor', 'String to search for')
.addOptionalParam('startsWith', 'String to search for')
.setAction(async (taskArgs, { ethers }) => {
if (!taskArgs.searchFor && !taskArgs.startsWith) {
console.error(chalk.red('No arguments set.'))
return
}
let wallet: ReturnType<typeof ethers.Wallet.createRandom>
let contractAddress = ''
let attempt = 0
let shouldRetry = true
while (shouldRetry) {
if (attempt > 0) {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
}
attempt++
process.stdout.write(`Mining attempt ${attempt}`)
wallet = ethers.Wallet.createRandom()
contractAddress = ethers.utils.getContractAddress({
from: wallet.address,
nonce: 0,
})
if (taskArgs.searchFor) {
shouldRetry = contractAddress.indexOf(taskArgs.searchFor) != 0
} else if (taskArgs.startsWith) {
shouldRetry =
!contractAddress
.substr(2)
.startsWith(taskArgs.startsWith.toLowerCase()) &&
!contractAddress
.substr(2)
.startsWith(taskArgs.startsWith.toUpperCase())
}
}
process.stdout.write('\n')
if (DEBUG) {
console.log('mnemonic', wallet!.mnemonic.phrase)
console.log('fullPath', wallet!.mnemonic.path)
console.log('privateKey', wallet!.privateKey)
}
console.log(
`⛏ Account Mined as ${
wallet!.address
} and set as mnemonic in packages/hardhat`
)
console.log(
`📜 This will create the first contract: ${chalk.magenta(
contractAddress
)}`
)
console.log(
"💬 Use 'yarn run account' to get more information about the deployment account."
)
fs.writeFileSync(
`./${wallet!.address}_produces${contractAddress}.secret`,
wallet!.mnemonic.phrase
)
fs.writeFileSync('./mnemonic.secret', wallet!.mnemonic.phrase)
})
task(
'account',
'Get balance information for the deployment account.',
async (_, { ethers, config }) => {
try {
const mnemonic = getMnemonic()
const wallet = ethers.Wallet.fromMnemonic(mnemonic)
if (DEBUG) {
console.log('mnemonic', wallet.mnemonic.phrase)
console.log('fullPath', wallet.mnemonic.path)
console.log('privateKey', wallet.privateKey)
}
const qrcode = require('qrcode-terminal')
qrcode.generate(wallet.address)
console.log(`📬 Deployer Account is ${wallet.address}`)
for (const networkName in config.networks) {
const network = config.networks[networkName]
if (!('url' in network)) continue
try {
const provider = new ethers.providers.JsonRpcProvider(network.url)
const balance = await provider.getBalance(wallet.address)
console.log(` -- ${chalk.bold(networkName)} -- -- -- 📡 `)
console.log(` balance: ${ethers.utils.formatEther(balance)}`)
console.log(
` nonce: ${await provider.getTransactionCount(wallet.address)}`
)
console.log()
} catch (e) {
if (DEBUG) {
console.log(e)
}
}
}
} catch (err) {
console.log(`--- Looks like there is no mnemonic file created yet.`)
console.log(
`--- Please run ${chalk.greenBright('yarn generate')} to create one`
)
}
}
)
/**
* Get a checksumed address.
* @param ethers {HardhatEthersHelpers} Ethers object from Hardhat.
* @param addr {string | number} The address string to be checksumed or an index in the account's mnemonic.
* @return Promise<string> The checksumed address
*/
async function findFirstAddr(
ethers: HardhatEthersHelpers,
addr: string | number
): Promise<string> {
if (typeof addr === 'string' && isAddress(addr)) {
return getAddress(addr)
} else if (typeof addr === 'number') {
const accounts = await ethers.provider.listAccounts()
if (accounts[addr] !== undefined) {
return getAddress(accounts[addr])
}
}
throw new Error(`Could not normalize address: ${addr}`)
}
task('accounts', 'Prints the list of accounts', async (_, { ethers }) => {
const accounts = await ethers.provider.listAccounts()
accounts.forEach((account) => console.log(account))
})
task('blockNumber', 'Prints the block number', async (_, { ethers }) => {
const blockNumber = await ethers.provider.getBlockNumber()
console.log(blockNumber)
})
task('balance', "Prints an account's balance")
.addPositionalParam(
'account',
"The account's address or index in the mnemonic"
)
.setAction(async (taskArgs, { ethers }) => {
const balance = await ethers.provider.getBalance(
await findFirstAddr(ethers, taskArgs.account)
)
console.log(formatUnits(balance, 'ether'), 'ETH')
})
async function send(
signer: Signer,
txparams: TransactionRequest
): Promise<TransactionReceipt> {
const response = await signer.sendTransaction(txparams)
debug(`transactionHash: ${response.hash}`)
const waitBlocksForReceipt = 0 // 2
return await response.wait(waitBlocksForReceipt)
}
task('send', 'Send ETH')
.addParam('from', 'From address or account index')
.addOptionalParam('to', 'To address or account index')
.addOptionalParam('amount', 'Amount to send in ether')
.addOptionalParam('data', 'Data included in transaction')
.addOptionalParam('gasPrice', 'Price you are willing to pay in gwei')
.addOptionalParam('gasLimit', 'Limit of how much gas to spend')
.setAction(async (taskArgs, { network, ethers }) => {
const from = await findFirstAddr(ethers, taskArgs.from)
debug(`Normalized from address: ${from}`)
const fromSigner = ethers.provider.getSigner(from)
let to
if (taskArgs.to) {
to = await findFirstAddr(ethers, taskArgs.to)
debug(`Normalized to address: ${to}`)
}
const txRequest: TransactionRequest = {
from: await fromSigner.getAddress(),
to,
value: parseUnits(
taskArgs.amount ? taskArgs.amount : '0',
'ether'
).toHexString(),
nonce: await fromSigner.getTransactionCount(),
gasPrice: parseUnits(
taskArgs.gasPrice ? taskArgs.gasPrice : '1.001',
'gwei'
).toHexString(),
gasLimit: taskArgs.gasLimit ? taskArgs.gasLimit : 24000,
chainId: network.config.chainId,
}
if (taskArgs.data !== undefined) {
txRequest.data = taskArgs.data
debug(`Adding data to payload: ${txRequest.data}`)
}
// eslint-disable-next-line @typescript-eslint/no-base-to-string
debug(formatUnits(txRequest.gasPrice!.toString(), 'gwei'))
debug(JSON.stringify(txRequest, null, 2))
return await send(fromSigner, txRequest)
})