-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeploy.ts
847 lines (782 loc) · 24.3 KB
/
deploy.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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
#!/usr/bin/env node
import fs from 'fs'
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
import {
ChildProcessWithoutNullStreams,
exec,
execSync,
spawn,
} from 'child_process'
import { ethers } from 'ethers'
import crypto from 'crypto'
import * as diff from 'diff'
import axios from 'axios'
import semver from 'semver'
const CROSS_CHAIN_CREATE2_FACTORY = '0x0000000000FFe8B47B3e2130213B802212439497'
yargs(hideBin(process.argv))
.usage('$0 <cmd> [args]')
.command(
'deploy <contract>',
'deploy the given contract',
(yargs) => {
return yargs
.positional('contract', {
describe: 'contract to deploy',
type: 'string',
demandOption: 'true',
})
.describe('rpc', 'The URL of the RPC to use for deployment')
.describe('pk', 'The private key to use for deployment')
.describe('salt', 'The salt used at deployment. Defaults to 0')
.describe(
'explorer-api-key',
'Explorer key for etherscan product on the given network'
)
.describe('webhook-url', 'Webhook URL for notifications')
.describe('github-token', 'GitHub token for creating gists')
.describe('store-abi', 'Store the ABI file for the deployed contract')
.array('constructor-args')
.string('constructor-args')
.string('pk')
.string('rpc')
.string('salt')
.string('explorer-api-key')
.string('webhook-url')
.string('github-token')
.boolean('store-abi')
.default('store-abi', false)
.demandOption(['rpc', 'pk'])
},
(argv) => {
runDeploy(
argv.contract,
argv.rpc,
argv.pk,
argv['constructor-args'],
argv.salt ?? ethers.ZeroHash,
argv.explorerApiKey,
argv.webhookUrl,
argv.githubToken,
argv.storeAbi
)
}
)
.command(
'verify <contract>',
'verifies the latest deploy of the given contract',
(yargs) => {
return yargs
.positional('contract', {
describe: 'contract to verify',
type: 'string',
demandOption: 'true',
})
.describe('rpc', 'The URL of the RPC to use for deployment')
.describe(
'explorer-api-key',
'Explorer key for etherscan product on the given network'
)
.string('rpc')
.string('explorer-api-key')
.demandOption(['rpc', 'explorer-api-key'])
},
(argv) => {
runVerify(argv.contract, argv.rpc, argv['explorer-api-key'])
}
)
.command(
'init <chainId>',
'initialize the deployment file for a given network',
(yargs) => {
return yargs.positional('chainId', {
describe: 'network id to initialize for',
type: 'string',
demandOption: 'true',
})
},
(argv) => {
initProject(argv.chainId)
}
)
.parse()
async function runVerify(
contract: string,
rpcUrl: string,
explorerApiKey: string
) {
const provider = new ethers.JsonRpcProvider(rpcUrl)
const chainId = (await provider.getNetwork()).chainId.toString()
const deploymentFile: DeploymentFile = JSON.parse(
fs.readFileSync(`deployments/${chainId}.json`, 'utf-8')
)
const deploy = deploymentFile.contracts[contract].deploys.at(-1)
if (!deploy) {
throw new Error(`Contract ${contract} has not been deployed yet`)
}
await verifyContract(rpcUrl, explorerApiKey, deploy, contract)
}
async function runDeploy(
contract: string,
rpcUrl: string,
privateKey: string,
constructorArgs: (string | number)[] | undefined,
salt: string,
explorerApiKey: string | undefined,
webhookUrl: string | undefined,
githubToken: string | undefined,
storeAbi: boolean
) {
const contracts = getProjectContracts()
if (!contracts.includes(contract)) {
throw new Error(`Contract ${contract} not found in project`)
}
const provider = new ethers.JsonRpcProvider(rpcUrl)
const chainId = (await provider.getNetwork()).chainId.toString()
// If no constructor args are given, try to resolve from deployment file
if (!constructorArgs || constructorArgs.length == 0) {
constructorArgs = resolveConstructorArgs(contract, chainId)
}
const encodedConstructorArgs = encodeConstructorArgs(
contract,
constructorArgs
)
let newDeploy: Deploy = { deployedArgs: encodedConstructorArgs } as Deploy
const contractJson = JSON.parse(
fs.readFileSync(`out/${contract}.sol/${contract}.json`, 'utf-8')
)
const deploymentBytecode = ethers.solidityPacked(
['bytes', 'bytes'],
[contractJson.bytecode.object, encodedConstructorArgs]
)
newDeploy.version = await getUndeployedContractVersion(
deploymentBytecode,
rpcUrl
)
newDeploy.bytecodeHash = crypto
.createHash('sha256')
.update(JSON.stringify(contractJson.bytecode.object))
.digest('hex')
newDeploy.abiHash = crypto
.createHash('sha256')
.update(JSON.stringify(contractJson.abi))
.digest('hex')
newDeploy.commitHash = getLatestCommitHash()
validateDeploy(contract, newDeploy, chainId)
console.log('Deploying contract...')
const getDeterministicAddressCall = `cast call ${CROSS_CHAIN_CREATE2_FACTORY} "findCreate2Address(bytes32,bytes)" ${salt} ${deploymentBytecode} --rpc-url ${rpcUrl}`
const deterministicCreateCall = `cast send ${CROSS_CHAIN_CREATE2_FACTORY} "safeCreate2(bytes32,bytes)" ${salt} ${deploymentBytecode} --rpc-url ${rpcUrl} --private-key ${privateKey}`
const getAddrResult = (await execSync(getDeterministicAddressCall))
.toString()
.trim()
const addr = ethers.AbiCoder.defaultAbiCoder().decode(
['address'],
getAddrResult
)[0]
if (addr == ethers.ZeroAddress) {
throw new Error(
`Contract ${contract} already deployed using salt ${salt} with version ${newDeploy.version}`
)
}
newDeploy.address = addr
await execSync(deterministicCreateCall)
console.log(
`Contract ${contract} deployed to ${newDeploy.address} with version ${newDeploy.version} (commit ${newDeploy.commitHash})`
)
if (storeAbi) {
// Store ABI file and generate diff
const abiDir = `deployments/abi/${contract}`
if (!fs.existsSync(abiDir)) {
fs.mkdirSync(abiDir, { recursive: true })
}
const newAbiPath = `${abiDir}/v${newDeploy.version.replace(/\./g, '_')}.json`
if (!fs.existsSync(newAbiPath)) {
fs.writeFileSync(newAbiPath, JSON.stringify(contractJson.abi, null, 2))
const abiFiles = fs.readdirSync(abiDir)
const versions = sortVersions(
abiFiles
.map((file) => file.match(/\d+\_\d+\_\d+/)?.[0] || '')
.filter(Boolean)
)
// Check if there's a previous version
if (versions.length > 1) {
const previousAbiPath = `${abiDir}/v${versions[1].replace(/\./g, '_')}.json`
const newAbi = JSON.parse(fs.readFileSync(newAbiPath, 'utf-8'))
const previousAbi = JSON.parse(
fs.readFileSync(previousAbiPath, 'utf-8')
)
// Check if the ABI has changed
if (JSON.stringify(newAbi) !== JSON.stringify(previousAbi)) {
if (webhookUrl && githubToken) {
const previousVersion = versions[1]
.split('.')[0]
.replace(/\_/g, '.')
// Send notification for the ABI changes
await notifyAbiChanges(
contract,
previousVersion,
newDeploy.version,
previousAbi,
newAbi,
chainId,
newDeploy.address,
webhookUrl,
githubToken
)
} else {
console.log(
'Skipping ABI change notification: GitHub token or webhook URL not provided.'
)
}
} else {
// Send notification for new deployment (ABI unchanged)
if (webhookUrl) {
await notifyNewDeploy(
contract,
newDeploy.version,
newDeploy.address,
chainId,
webhookUrl
)
}
}
} else {
console.log(
`First version of ABI for ${contract}. Skipping diff generation and webhook notification.`
)
}
} else {
console.log(
`ABI file already exists for ${contract} v${newDeploy.version}. Skipping writing and notification.`
)
}
}
if (!!explorerApiKey) {
await verifyContract(rpcUrl, explorerApiKey, newDeploy, contract)
}
writeDeploy(contract, newDeploy, chainId)
}
/**
* Verifies the contract on the given networks explorer. Uses forge verify command.
* @param rpcUrl
* @param explorerApiKey
* @param newDeploy
* @param contract
*/
async function verifyContract(
rpcUrl: string,
explorerApiKey: string,
newDeploy: Deploy,
contract: string
): Promise<void> {
const verifyCall = `forge v --rpc-url ${rpcUrl} --etherscan-api-key ${explorerApiKey!} ${
newDeploy.deployedArgs != ''
? `--constructor-args ${newDeploy.deployedArgs}`
: ''
} ${newDeploy.address} ${contract}`
console.log(`Verifying ${contract}`)
const res = await execSync(verifyCall)
console.log(res.toString())
}
/**
* Resolves the constructor arguments for a contract. Must be other contracts in the repo or constants in the deployment file.
* @param contractName Contract to resolve args for
* @param chainId Chain to deploy to
*/
function resolveConstructorArgs(
contractName: string,
chainId: string
): string[] {
if (!fs.existsSync(`deployments/${chainId}.json`)) {
throw new Error(
`Deployment file for network ${getNetworkName(chainId)} does not exist`
)
}
const deploymentFile: DeploymentFile = JSON.parse(
fs.readFileSync(`deployments/${chainId}.json`, 'utf-8')
)
if (!(contractName in deploymentFile.contracts)) {
throw new Error(`Contract ${contractName} does not exist in project`)
}
const args = deploymentFile.contracts[contractName].constructorArgs
let resolvedArgs: string[] = new Array<string>(args.length)
for (let i = 0; i < args.length; i++) {
if (args[i] in deploymentFile.contracts) {
const contractObj = deploymentFile.contracts[args[i]]
if (contractObj.deploys.length == 0)
throw new Error(`Contract ${args[i]} doesn't have any deploy`)
resolvedArgs[i] = contractObj.deploys.at(-1)!.address
} else {
// Must be in constants or revert
if (args[i] in deploymentFile.constants) {
resolvedArgs[i] = deploymentFile.constants[args[i]]
} else {
throw new Error(
`Argument ${args[i]} not found in deployment file or constants`
)
}
}
}
return resolvedArgs
}
/**
* Validates a deploy. Should be called prior to writing anything to chain.
* @param contract Name of the contract to be deployed
* @param deploy Deployments specifications to be used
* @param chainId Chain to deploy to
*/
function validateDeploy(contract: string, deploy: Deploy, chainId: string) {
// First check if deployment file exists
if (!fs.existsSync(`deployments/${chainId}.json`)) {
initProject(chainId)
}
const existingDeployments = JSON.parse(
fs.readFileSync(`deployments/${chainId}.json`, 'utf-8')
)
if (
!!existingDeployments.contracts[contract].deploys.find(
(d: Deploy) =>
d.version == deploy.version && d.deployedArgs == deploy.deployedArgs
)
) {
throw new Error(
`Contract ${contract} with version ${deploy.version} and deployed args ${
deploy.deployedArgs || '<empty>'
} already deployed`
)
}
// Validate deploy version
if (existingDeployments.contracts[contract].deploys.length != 0) {
const latestDeploy: Deploy =
existingDeployments.contracts[contract].deploys.at(-1)
if (
latestDeploy.version.split('.')[0] == '0' &&
deploy.version == '1.0.0'
) {
// Allow upgrade to alpha version
return
}
if (latestDeploy.abiHash != deploy.abiHash) {
let expectedVersion = `${Number(latestDeploy.version.split('.')[0]) + 1}.0.0`
if (latestDeploy.version.split('.')[0] == '0') {
// If in beta, we consider an abi update a minor change
expectedVersion = `0.${Number(latestDeploy.version.split('.')[1]) + 1}.0`
}
if (expectedVersion != deploy.version) {
throw new Error(
`Contract ${contract} version ${deploy.version} must increment major version due to ABI change. Expected version is ${expectedVersion}.`
)
}
} else if (latestDeploy.bytecodeHash != deploy.bytecodeHash) {
let expectedVersion = `${latestDeploy.version.split('.')[0]}.${Number(latestDeploy.version.split('.')[1]) + 1}.0`
if (expectedVersion.split('.')[0] == '0') {
// If in beta, we will consider bytecode changes a patch update
expectedVersion = `0.${latestDeploy.version.split('.')[1]}.${Number(latestDeploy.version.split('.')[2]) + 1}`
}
if (expectedVersion != deploy.version) {
throw new Error(
`Contract ${contract} version ${deploy.version} must increment minor version due to bytecode change. Expected version is ${expectedVersion}.`
)
}
}
}
}
/**
* Writes a new deploy to the deployment file
* @param contract Name of the contract deployed
* @param deploy Deployments specifications
* @param chainId The chain deployed to
*/
function writeDeploy(contract: string, deploy: Deploy, chainId: string) {
// First check if deployment file exists
if (!fs.existsSync(`deployments/${chainId}.json`)) {
initProject(chainId)
}
const existingDeployments = JSON.parse(
fs.readFileSync(`deployments/${chainId}.json`, 'utf-8')
)
existingDeployments.contracts[contract].deploys.push(deploy)
fs.writeFileSync(
`deployments/${chainId}.json`,
JSON.stringify(existingDeployments, null, 2)
)
}
/**
* Launches a local anvil instance using the `mnemonic-seed` 123
* @param rpcUrl RPC to use as a fork for the local anvil instance
* @returns Returns the child process. Must be killed.
*/
async function launchAnvil(
rpcUrl: string
): Promise<ChildProcessWithoutNullStreams> {
var anvil = spawn('anvil', [
'--mnemonic-seed-unsafe',
'123',
'--fork-url',
rpcUrl,
])
return new Promise((resolve) => {
anvil.stdout.on('data', function (data) {
if (data.includes('Listening')) {
resolve(anvil)
}
})
anvil.stderr.on('data', function (err) {
throw new Error(err.toString())
})
})
}
/**
* Gets the version of an undeployed contract via deploying to a local network.
* @param deploymentBytecode Bytecode to use for deploying the contract. Includes constructor args.
* @param rpcUrl The RPC url to fork the local node off of
* @returns version
*/
async function getUndeployedContractVersion(
deploymentBytecode: string,
rpcUrl: string
): Promise<string> {
const anvil = await launchAnvil(rpcUrl)
// Private key generated from mnemonic 123
const createCommand = `cast send --private-key 0x78427d179c2c0f8467881bc37f9453a99854977507ca53ff65e1c875208a4a03 --rpc-url "127.0.0.1:8545" --create ${deploymentBytecode}`
let addr = '0xC1e3efbd87a483129360a2196c09188D73fA1c6C' // Address of contract will alway be this
await execSync(createCommand)
const res = await getContractVersion(addr, 'http://127.0.0.1:8545')
anvil.kill()
return res
}
/**
* Fetches the version of the given contract by calling `VERSION`
* @param contractAddress Address the contract is deployed to
* @param rpcUrl RPC to connect to the network where the contract is deployed
* @returns
*/
async function getContractVersion(
contractAddress: string,
rpcUrl: string
): Promise<string> {
const provider = new ethers.JsonRpcProvider(rpcUrl)
try {
const versionRes = await provider.call({
to: contractAddress,
data: '0xffa1ad74' /* Version function */,
})
return ethers.AbiCoder.defaultAbiCoder().decode(['string'], versionRes)[0]
} catch (err) {
throw new Error(
'Contract does not implement version function. Please implement `VERSION` in your contract'
)
}
}
function encodeConstructorArgs(
contractName: string,
args: (string | number)[] | undefined
): string {
if (!!args) {
const contractABI = JSON.parse(
fs.readFileSync(`out/${contractName}.sol/${contractName}.json`, 'utf-8')
).abi
const contractInterface = new ethers.Interface(contractABI)
let encodedArgs = ''
try {
encodedArgs = contractInterface.encodeDeploy(args)
} catch (e) {
throw new Error(
`Error encoding constructor arguments for contract ${contractName}. ${e}`
)
}
return encodedArgs
}
return ''
}
type Deploy = {
version: string
address: string
deployedArgs: string
abiHash: string
commitHash: string
bytecodeHash: string
}
type Contract = {
deploys: Deploy[]
constructorArgs: string[]
}
type DeploymentFile = {
contracts: { [key: string]: Contract }
constants: { [key: string]: string }
}
/**
* Initialize the deployment file for a given network
* @param chainId
*/
function initProject(chainId: string) {
console.log(`Initializing project for network ${chainId}...`)
if (fs.existsSync(`deployments/${chainId}.json`)) {
throw new Error(
`Deployment file for network ${getNetworkName(chainId)} already exists`
)
}
let fileToStore: DeploymentFile = {
contracts: {},
constants: {},
}
const contracts = getProjectContracts()
contracts.map((contract) => {
fileToStore.contracts[contract] = {
deploys: [],
constructorArgs: [],
}
})
if (!fs.existsSync('deployments')) {
fs.mkdirSync('deployments')
}
fs.writeFileSync(
`deployments/${chainId}.json`,
JSON.stringify(fileToStore, null, 2)
)
}
/**
* Gets all the deployable contracts in the project
* @returns An array of contract names not including the path or extension
*/
function getProjectContracts(): string[] {
console.log('Building project...')
execSync('forge build')
const buildCache = JSON.parse(
fs.readFileSync('cache/solidity-files-cache.json', 'utf-8')
)
// Get files in src directory
const filesOfInterest = Object.keys(buildCache.files).filter((file: string) =>
file.startsWith('src/')
)
// Get contracts that have bytecode
let deployableContracts: string[] = []
for (const file of filesOfInterest) {
const fileName = file.split('/').pop()!
const buildOutput = JSON.parse(
fs.readFileSync(`out/${fileName}/${fileName.split('.')[0]}.json`, 'utf-8')
)
// Only consider contracts that are deployable
if (buildOutput.bytecode.object !== '0x') {
deployableContracts.push(fileName.split('.')[0])
}
}
return deployableContracts
}
/**
* Gets the latest commit hash
* @returns Commit hash
*/
function getLatestCommitHash(): string {
try {
return execSync('git rev-parse HEAD').toString().trim()
} catch (error) {
console.warn('Unable to get git commit hash. Is this a git repository?')
return 'unknown'
}
}
/**
* Notifies the team of ABI changes via webhook
* @param contract Name of the contract
* @param previousVersion Previous version of the contract
* @param newVersion New version of the contract
* @param previousAbi Previous ABI in JSON of the contract
* @param newAbi New ABI in JSON of the contract
* @param chainId Chain ID of the network
* @param contractAddress Address of the contract
*/
async function notifyAbiChanges(
contract: string,
previousVersion: string,
newVersion: string,
previousAbi: string,
newAbi: string,
chainId: string,
contractAddress: string,
webhookUrl: string,
githubToken: string
) {
const differences = diff.diffJson(previousAbi, newAbi)
let detailedDiff = ''
differences.forEach((part) => {
const prefix = part.added ? '+' : part.removed ? '-' : ' '
const lines = part.value
.split('\n')
.map((line) => `${prefix} ${line}`)
.join('\n')
detailedDiff += lines + '\n'
})
// Upload to GitHub Gist and send webhook message
try {
const description = `The ABI changes for ${contract}.sol between ${previousVersion} and ${newVersion}.`
const gistUrl = await uploadToGist(
detailedDiff,
`${contract}_ABI_${previousVersion}_to_${newVersion}.diff`,
description,
githubToken
)
console.log(`ABI diff for ${contract} uploaded to: ${gistUrl}`)
const message = {
embeds: [
{
title: `ABI Changes: ${contract} ${previousVersion} → ${newVersion}`,
description: `A new version of \`${contract}.sol\` with ABI changes has been deployed.`,
color: 3447003,
fields: [
{
name: 'Version',
value: `${previousVersion} → ${newVersion}`,
},
{
name: 'Chain',
value: `${getNetworkName(chainId)}`,
},
{
name: 'Address',
value: `${contractAddress}`,
},
{
name: 'ABI Changes',
value: `[View diff on GitHub](${gistUrl})`,
},
],
},
],
}
await sendWebhookMessage('ABI Changes', webhookUrl, message)
} catch (error) {
console.error('Error in notifying ABI changes:', error)
}
}
async function notifyNewDeploy(
contract: string,
version: string,
chainId: string,
address: string,
webhookUrl: string
) {
const networkName = getNetworkName(chainId)
const explorerUrl = getExplorerUrl(chainId)
try {
const message = {
embeds: [
{
title: `New Deployment: ${contract} ${version}`,
description: `A new \`${contract}.sol\` \`${version}\` has been deployed on ${networkName}.`,
color: 3447003,
fields: [
{
name: 'Version',
value: version,
inline: true,
},
{
name: 'Chain',
value: networkName,
inline: true,
},
{
name: 'Address',
value: explorerUrl
? `[${address}](${explorerUrl}/address/${address})`
: address,
},
],
},
],
}
await sendWebhookMessage('New Deployment', webhookUrl, message)
} catch (error) {
console.error('Error sending new address notification:', error)
}
}
async function uploadToGist(
content: string,
filename: string,
description: string,
githubToken: string
): Promise<string> {
try {
const response = await axios.post(
'https://api.github.com/gists',
{
files: {
[filename]: {
content: content,
},
},
description,
public: false,
},
{
headers: {
Authorization: `token ${githubToken}`,
Accept: 'application/vnd.github.v3+json',
},
}
)
return response.data.html_url
} catch (error) {
console.error('Error uploading to GitHub Gist:', error)
throw error
}
}
async function sendWebhookMessage(
purpose: string,
webhookUrl: string,
message: any
) {
try {
const response = await axios.post(webhookUrl, message)
console.log(`Webhook message sent for ${purpose}.`)
return response.data
} catch (error) {
console.error(
`Error sending webhook message for ${purpose}:`,
axios.isAxiosError(error) && error.response
? `${error.response.status} ${error.response.statusText}\nResponse data: ${JSON.stringify(error.response.data)}`
: error
)
}
}
function getNetworkName(chainId: string): string {
switch (chainId) {
case '1':
return 'Mainnet'
case '11155111':
return 'Sepolia'
case '8453':
return 'Base'
case '84532':
return 'Base Sepolia'
case '7777777':
return 'Zora'
case '1337':
return 'Localhost'
default:
return chainId.toString()
}
}
function getExplorerUrl(chainId: string): string {
switch (chainId) {
case '1':
return 'https://etherscan.io/'
case '11155111':
return 'https://sepolia.etherscan.io/'
case '8453':
return 'https://basescan.org/'
case '84532':
return 'https://sepolia.basescan.org/'
case '7777777':
return 'https://explorer.zora.energy/'
default:
return ''
}
}
function sortVersions(versions: string[]): string[] {
return versions.sort((a, b) => {
const versionA = a.replace(/^v/, '').replace(/\_/g, '.')
const versionB = b.replace(/^v/, '').replace(/\_/g, '.')
return semver.compare(versionB, versionA) // Descending order
})
}