/
deploy.go
714 lines (613 loc) · 23.4 KB
/
deploy.go
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
package deploy
import (
"context"
"errors"
"fmt"
"time"
"github.com/spf13/cobra"
"github.com/umbracle/ethgo"
"github.com/umbracle/ethgo/jsonrpc"
"golang.org/x/sync/errgroup"
"github.com/esportzvio/frietorchain/chain"
"github.com/esportzvio/frietorchain/command"
cmdHelper "github.com/esportzvio/frietorchain/command/helper"
"github.com/esportzvio/frietorchain/command/rootchain/helper"
"github.com/esportzvio/frietorchain/consensus/polybft"
"github.com/esportzvio/frietorchain/consensus/polybft/contractsapi"
"github.com/esportzvio/frietorchain/consensus/polybft/contractsapi/artifact"
bls "github.com/esportzvio/frietorchain/consensus/polybft/signer"
"github.com/esportzvio/frietorchain/consensus/polybft/validator"
"github.com/esportzvio/frietorchain/contracts"
"github.com/esportzvio/frietorchain/txrelayer"
"github.com/esportzvio/frietorchain/types"
)
const (
contractsDeploymentTitle = "[ROOTCHAIN - CONTRACTS DEPLOYMENT]"
stateSenderName = "StateSender"
checkpointManagerName = "CheckpointManager"
blsName = "BLS"
bn256G2Name = "BN256G2"
exitHelperName = "ExitHelper"
rootERC20PredicateName = "RootERC20Predicate"
childERC20MintablePredicateName = "ChildERC20MintablePredicate"
rootERC20Name = "RootERC20"
erc20TemplateName = "ERC20Template"
rootERC721PredicateName = "RootERC721Predicate"
childERC721MintablePredicateName = "ChildERC721MintablePredicate"
erc721TemplateName = "ERC721Template"
rootERC1155PredicateName = "RootERC1155Predicate"
childERC1155MintablePredicateName = "ChildERC1155MintablePredicate"
erc1155TemplateName = "ERC1155Template"
customSupernetManagerName = "CustomSupernetManager"
)
var (
// params are the parameters of CLI command
params deployParams
// consensusCfg contains consensus protocol configuration parameters
consensusCfg polybft.PolyBFTConfig
// metadataPopulatorMap maps rootchain contract names to callback
// which populates appropriate field in the RootchainMetadata
metadataPopulatorMap = map[string]func(*polybft.RootchainConfig, types.Address){
stateSenderName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.StateSenderAddress = addr
},
checkpointManagerName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.CheckpointManagerAddress = addr
},
blsName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.BLSAddress = addr
},
bn256G2Name: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.BN256G2Address = addr
},
exitHelperName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.ExitHelperAddress = addr
},
rootERC20PredicateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.RootERC20PredicateAddress = addr
},
childERC20MintablePredicateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.ChildMintableERC20PredicateAddress = addr
},
rootERC20Name: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.RootNativeERC20Address = addr
},
erc20TemplateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.ChildERC20Address = addr
},
rootERC721PredicateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.RootERC721PredicateAddress = addr
},
childERC721MintablePredicateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.ChildMintableERC721PredicateAddress = addr
},
erc721TemplateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.ChildERC721Address = addr
},
rootERC1155PredicateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.RootERC1155PredicateAddress = addr
},
childERC1155MintablePredicateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.ChildMintableERC1155PredicateAddress = addr
},
erc1155TemplateName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.ChildERC1155Address = addr
},
customSupernetManagerName: func(rootchainConfig *polybft.RootchainConfig, addr types.Address) {
rootchainConfig.CustomSupernetManagerAddress = addr
},
}
// initializersMap maps rootchain contract names to initializer function callbacks
initializersMap = map[string]func(command.OutputFormatter, txrelayer.TxRelayer,
*polybft.RootchainConfig, ethgo.Key) error{
customSupernetManagerName: func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
initParams := &contractsapi.InitializeCustomSupernetManagerFn{
NewStakeManager: config.StakeManagerAddress,
NewBls: config.BLSAddress,
NewStateSender: config.StateSenderAddress,
NewMatic: types.StringToAddress(params.stakeTokenAddr),
NewChildValidatorSet: contracts.ValidatorSetContract,
NewExitHelper: config.ExitHelperAddress,
NewDomain: bls.DomainValidatorSetString,
}
return initContract(fmt, relayer, initParams,
config.CustomSupernetManagerAddress, customSupernetManagerName, key)
},
exitHelperName: func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
inputParams := &contractsapi.InitializeExitHelperFn{
NewCheckpointManager: config.CheckpointManagerAddress,
}
return initContract(fmt, relayer, inputParams, config.ExitHelperAddress, exitHelperName, key)
},
rootERC20PredicateName: func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
// map root native token on rootchain only if it is non-mintable on a childchain
nativeTokenRootAddr := types.ZeroAddress
if !consensusCfg.NativeTokenConfig.IsMintable {
nativeTokenRootAddr = config.RootNativeERC20Address
}
inputParams := &contractsapi.InitializeRootERC20PredicateFn{
NewStateSender: config.StateSenderAddress,
NewExitHelper: config.ExitHelperAddress,
NewChildERC20Predicate: contracts.ChildERC20PredicateContract,
NewChildTokenTemplate: contracts.ChildERC20Contract,
NativeTokenRootAddress: nativeTokenRootAddr,
}
return initContract(fmt, relayer, inputParams,
config.RootERC20PredicateAddress, rootERC20PredicateName, key)
},
childERC20MintablePredicateName: func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
initParams := &contractsapi.InitializeChildMintableERC20PredicateFn{
NewStateSender: config.StateSenderAddress,
NewExitHelper: config.ExitHelperAddress,
NewRootERC20Predicate: contracts.RootMintableERC20PredicateContract,
NewChildTokenTemplate: config.ChildERC20Address,
}
return initContract(fmt, relayer, initParams,
config.ChildMintableERC20PredicateAddress, childERC20MintablePredicateName, key)
},
rootERC721PredicateName: func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
initParams := &contractsapi.InitializeRootERC721PredicateFn{
NewStateSender: config.StateSenderAddress,
NewExitHelper: config.ExitHelperAddress,
NewChildERC721Predicate: contracts.ChildERC721PredicateContract,
NewChildTokenTemplate: contracts.ChildERC721Contract,
}
return initContract(fmt, relayer, initParams,
config.RootERC721PredicateAddress, rootERC721PredicateName, key)
},
childERC721MintablePredicateName: func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
initParams := &contractsapi.InitializeChildMintableERC721PredicateFn{
NewStateSender: config.StateSenderAddress,
NewExitHelper: config.ExitHelperAddress,
NewRootERC721Predicate: contracts.RootMintableERC721PredicateContract,
NewChildTokenTemplate: config.ChildERC721Address,
}
return initContract(fmt, relayer, initParams,
config.ChildMintableERC721PredicateAddress, childERC721MintablePredicateName, key)
},
rootERC1155PredicateName: func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
initParams := &contractsapi.InitializeRootERC1155PredicateFn{
NewStateSender: config.StateSenderAddress,
NewExitHelper: config.ExitHelperAddress,
NewChildERC1155Predicate: contracts.ChildERC1155PredicateContract,
NewChildTokenTemplate: contracts.ChildERC1155Contract,
}
return initContract(fmt, relayer, initParams,
config.RootERC1155PredicateAddress, rootERC1155PredicateName, key)
},
childERC1155MintablePredicateName: func(fmt command.OutputFormatter,
relayer txrelayer.TxRelayer,
config *polybft.RootchainConfig,
key ethgo.Key) error {
initParams := &contractsapi.InitializeChildMintableERC1155PredicateFn{
NewStateSender: config.StateSenderAddress,
NewExitHelper: config.ExitHelperAddress,
NewRootERC1155Predicate: contracts.RootMintableERC1155PredicateContract,
NewChildTokenTemplate: config.ChildERC1155Address,
}
return initContract(fmt, relayer, initParams,
config.ChildMintableERC1155PredicateAddress, childERC1155MintablePredicateName, key)
},
}
)
type deploymentResultInfo struct {
RootchainCfg *polybft.RootchainConfig
SupernetID int64
CommandResults []command.CommandResult
}
// GetCommand returns the rootchain deploy command
func GetCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "deploy",
Short: "Deploys and initializes required smart contracts on the rootchain",
PreRunE: preRunCommand,
Run: runCommand,
}
cmd.Flags().StringVar(
¶ms.genesisPath,
helper.GenesisPathFlag,
helper.DefaultGenesisPath,
helper.GenesisPathFlagDesc,
)
cmd.Flags().StringVar(
¶ms.deployerKey,
deployerKeyFlag,
"",
"hex-encoded private key of the account which deploys rootchain contracts",
)
cmd.Flags().StringVar(
¶ms.jsonRPCAddress,
jsonRPCFlag,
txrelayer.DefaultRPCAddress,
"the JSON RPC rootchain IP address",
)
cmd.Flags().StringVar(
¶ms.rootERC20TokenAddr,
erc20AddrFlag,
"",
"existing root chain root native token address",
)
cmd.Flags().BoolVar(
¶ms.isTestMode,
helper.TestModeFlag,
false,
"test indicates whether rootchain contracts deployer is hardcoded test account"+
" (otherwise provided secrets are used to resolve deployer account)",
)
cmd.Flags().StringVar(
¶ms.stakeTokenAddr,
helper.StakeTokenFlag,
"",
helper.StakeTokenFlagDesc,
)
cmd.Flags().StringVar(
¶ms.stakeManagerAddr,
helper.StakeManagerFlag,
"",
helper.StakeManagerFlagDesc,
)
cmd.MarkFlagsMutuallyExclusive(helper.TestModeFlag, deployerKeyFlag)
_ = cmd.MarkFlagRequired(helper.StakeManagerFlag)
_ = cmd.MarkFlagRequired(helper.StakeTokenFlag)
return cmd
}
func preRunCommand(_ *cobra.Command, _ []string) error {
return params.validateFlags()
}
func runCommand(cmd *cobra.Command, _ []string) {
outputter := command.InitializeOutputter(cmd)
defer outputter.WriteOutput()
outputter.WriteCommandResult(&helper.MessageResult{
Message: fmt.Sprintf("%s started... Rootchain JSON RPC address %s.", contractsDeploymentTitle, params.jsonRPCAddress),
})
chainConfig, err := chain.ImportFromFile(params.genesisPath)
if err != nil {
outputter.SetError(fmt.Errorf("failed to read chain configuration: %w", err))
return
}
client, err := jsonrpc.NewClient(params.jsonRPCAddress)
if err != nil {
outputter.SetError(fmt.Errorf("failed to initialize JSON RPC client for provided IP address: %s: %w",
params.jsonRPCAddress, err))
return
}
if consensusCfg.Bridge != nil {
code, err := client.Eth().GetCode(ethgo.Address(consensusCfg.Bridge.StateSenderAddr), ethgo.Latest)
if err != nil {
outputter.SetError(fmt.Errorf("failed to check if rootchain contracts are deployed: %w", err))
return
} else if code != "0x" {
outputter.SetCommandResult(&helper.MessageResult{
Message: fmt.Sprintf("%s contracts are already deployed. Aborting.", contractsDeploymentTitle),
})
return
}
}
deploymentResultInfo, err := deployContracts(outputter, client,
chainConfig.Params.ChainID, consensusCfg.InitialValidatorSet, cmd.Context())
if err != nil {
outputter.SetError(fmt.Errorf("failed to deploy rootchain contracts: %w", err))
outputter.SetCommandResult(command.Results(deploymentResultInfo.CommandResults))
return
}
// populate bridge configuration
bridgeConfig := deploymentResultInfo.RootchainCfg.ToBridgeConfig()
if consensusCfg.Bridge != nil {
// only true if stake-manager-deploy command was executed
// users can still deploy stake manager manually
// only used for e2e tests
bridgeConfig.StakeTokenAddr = consensusCfg.Bridge.StakeTokenAddr
}
consensusCfg.Bridge = bridgeConfig
// set event tracker start blocks for rootchain contract(s) of interest
blockNum, err := client.Eth().BlockNumber()
if err != nil {
outputter.SetError(fmt.Errorf("failed to query rootchain latest block number: %w", err))
return
}
consensusCfg.Bridge.EventTrackerStartBlocks = map[types.Address]uint64{
deploymentResultInfo.RootchainCfg.StateSenderAddress: blockNum,
}
consensusCfg.SupernetID = deploymentResultInfo.SupernetID
// write updated consensus configuration
chainConfig.Params.Engine[polybft.ConsensusName] = consensusCfg
if err := cmdHelper.WriteGenesisConfigToDisk(chainConfig, params.genesisPath); err != nil {
outputter.SetError(fmt.Errorf("failed to save chain configuration bridge data: %w", err))
return
}
deploymentResultInfo.CommandResults = append(deploymentResultInfo.CommandResults, &helper.MessageResult{
Message: fmt.Sprintf("%s finished. All contracts are successfully deployed and initialized.",
contractsDeploymentTitle),
})
outputter.SetCommandResult(command.Results(deploymentResultInfo.CommandResults))
}
// deployContracts deploys and initializes rootchain smart contracts
func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client, chainID int64,
initialValidators []*validator.GenesisValidator, cmdCtx context.Context) (deploymentResultInfo, error) {
txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(client), txrelayer.WithWriter(outputter))
if err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil},
fmt.Errorf("failed to initialize tx relayer: %w", err)
}
deployerKey, err := helper.DecodePrivateKey(params.deployerKey)
if err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil},
fmt.Errorf("failed to initialize deployer key: %w", err)
}
if params.isTestMode {
deployerAddr := deployerKey.Address()
txn := ðgo.Transaction{To: &deployerAddr, Value: ethgo.Ether(1)}
if _, err = txRelayer.SendTransactionLocal(txn); err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
}
}
type contractInfo struct {
name string
artifact *artifact.Artifact
}
rootchainConfig := &polybft.RootchainConfig{
JSONRPCAddr: params.jsonRPCAddress,
// update stake manager address in genesis in case if stake manager was deployed manually
StakeManagerAddress: types.StringToAddress(params.stakeManagerAddr),
}
tokenContracts := []*contractInfo{}
// deploy root ERC20 token only if non-mintable native token flavor is used on a child chain
if !consensusCfg.NativeTokenConfig.IsMintable {
if params.rootERC20TokenAddr != "" {
// use existing root chain ERC20 token
if err := populateExistingTokenAddr(client.Eth(),
params.rootERC20TokenAddr, rootERC20Name, rootchainConfig); err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
}
} else {
// deploy MockERC20 as a root chain root native token
tokenContracts = append(tokenContracts,
&contractInfo{name: rootERC20Name, artifact: contractsapi.RootERC20})
}
}
allContracts := []*contractInfo{
{
name: stateSenderName,
artifact: contractsapi.StateSender,
},
{
name: checkpointManagerName,
artifact: contractsapi.CheckpointManager,
},
{
name: blsName,
artifact: contractsapi.BLS,
},
{
name: bn256G2Name,
artifact: contractsapi.BLS256,
},
{
name: exitHelperName,
artifact: contractsapi.ExitHelper,
},
{
name: rootERC20PredicateName,
artifact: contractsapi.RootERC20Predicate,
},
{
name: childERC20MintablePredicateName,
artifact: contractsapi.ChildMintableERC20Predicate,
},
{
name: erc20TemplateName,
artifact: contractsapi.ChildERC20,
},
{
name: rootERC721PredicateName,
artifact: contractsapi.RootERC721Predicate,
},
{
name: childERC721MintablePredicateName,
artifact: contractsapi.ChildMintableERC721Predicate,
},
{
name: erc721TemplateName,
artifact: contractsapi.ChildERC721,
},
{
name: rootERC1155PredicateName,
artifact: contractsapi.RootERC1155Predicate,
},
{
name: childERC1155MintablePredicateName,
artifact: contractsapi.ChildMintableERC1155Predicate,
},
{
name: erc1155TemplateName,
artifact: contractsapi.ChildERC1155,
},
{
name: customSupernetManagerName,
artifact: contractsapi.CustomSupernetManager,
},
}
allContracts = append(tokenContracts, allContracts...)
fmt.Println("All contracts: ", allContracts)
g, ctx := errgroup.WithContext(cmdCtx)
results := make([]*deployContractResult, len(allContracts))
commandResults := make([]command.CommandResult, len(allContracts))
for i, contract := range allContracts {
i := i
contract := contract
time.Sleep(10 * time.Second)
fmt.Println("Deploying contract: ", contract.name)
g.Go(func() error {
select {
case <-ctx.Done():
return ctx.Err()
default:
txn := ðgo.Transaction{
To: nil, // contract deployment
Input: contract.artifact.Bytecode,
}
txn.Gas = 10000000
receipt, err := txRelayer.SendTransaction(txn, deployerKey)
if err != nil {
return fmt.Errorf("failed sending %s contract deploy transaction: %w", contract.name, err)
}
if receipt == nil || receipt.Status != uint64(types.ReceiptSuccess) {
return fmt.Errorf("deployment of %s contract failed", contract.name)
}
results[i] = newDeployContractsResult(contract.name,
types.Address(receipt.ContractAddress),
receipt.TransactionHash,
receipt.GasUsed)
return nil
}
})
}
if err := g.Wait(); err != nil {
messageResult := helper.MessageResult{
Message: "[ROOTCHAIN - DEPLOY] Successfully deployed the following contracts\n"}
for i, result := range results {
if result != nil {
// In case an error happened, some of the indices may not be populated.
// Filter those out.
commandResults[i] = result
}
}
commandResults = append([]command.CommandResult{messageResult}, commandResults...)
return deploymentResultInfo{
RootchainCfg: nil,
SupernetID: 0,
CommandResults: commandResults}, err
}
for i, result := range results {
populatorFn, ok := metadataPopulatorMap[result.Name]
if !ok {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil},
fmt.Errorf("rootchain metadata populator not registered for contract '%s'", result.Name)
}
populatorFn(rootchainConfig, result.Address)
commandResults[i] = result
}
g, ctx = errgroup.WithContext(cmdCtx)
for _, contract := range allContracts {
contract := contract
initializer, exists := initializersMap[contract.name]
if !exists {
continue
}
g.Go(func() error {
select {
case <-cmdCtx.Done():
return cmdCtx.Err()
default:
return initializer(outputter, txRelayer, rootchainConfig, deployerKey)
}
})
}
if err := g.Wait(); err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
}
// register supernets manager on stake manager
supernetID, err := registerChainOnStakeManager(txRelayer, rootchainConfig, deployerKey)
if err != nil {
return deploymentResultInfo{RootchainCfg: nil, SupernetID: 0, CommandResults: nil}, err
}
return deploymentResultInfo{
RootchainCfg: rootchainConfig,
SupernetID: supernetID,
CommandResults: commandResults}, nil
}
// populateExistingTokenAddr checks whether given token is deployed on the provided address.
// If it is, then its address is set to the rootchain config, otherwise an error is returned
func populateExistingTokenAddr(eth *jsonrpc.Eth, tokenAddr, tokenName string,
rootchainCfg *polybft.RootchainConfig) error {
addr := types.StringToAddress(tokenAddr)
code, err := eth.GetCode(ethgo.Address(addr), ethgo.Latest)
if err != nil {
return fmt.Errorf("failed to check is %s token deployed: %w", tokenName, err)
} else if code == "0x" {
return fmt.Errorf("%s token is not deployed on provided address %s", tokenName, tokenAddr)
}
populatorFn, ok := metadataPopulatorMap[tokenName]
if !ok {
return fmt.Errorf("root chain metadata populator not registered for contract '%s'", tokenName)
}
populatorFn(rootchainCfg, addr)
return nil
}
// registerChainOnStakeManager registers child chain and its supernet manager on rootchain
func registerChainOnStakeManager(txRelayer txrelayer.TxRelayer,
rootchainCfg *polybft.RootchainConfig, deployerKey ethgo.Key) (int64, error) {
registerChainFn := &contractsapi.RegisterChildChainStakeManagerFn{
Manager: rootchainCfg.CustomSupernetManagerAddress,
}
encoded, err := registerChainFn.EncodeAbi()
if err != nil {
return 0, fmt.Errorf("failed to encode parameters for registering child chain on supernets. error: %w", err)
}
receipt, err := helper.SendTransaction(txRelayer, ethgo.Address(rootchainCfg.StakeManagerAddress),
encoded, checkpointManagerName, deployerKey)
if err != nil {
return 0, err
}
var (
childChainRegisteredEvent contractsapi.ChildManagerRegisteredEvent
found bool
supernetID int64
)
for _, log := range receipt.Logs {
doesMatch, err := childChainRegisteredEvent.ParseLog(log)
if err != nil {
return 0, err
}
if !doesMatch {
continue
}
supernetID = childChainRegisteredEvent.ID.Int64()
found = true
break
}
if !found {
return 0, errors.New("could not find a log that child chain was registered on stake manager")
}
return supernetID, nil
}
// initContract initializes arbitrary contract with given parameters deployed on a given address
func initContract(cmdOutput command.OutputFormatter, txRelayer txrelayer.TxRelayer,
initInputFn contractsapi.StateTransactionInput, contractAddr types.Address,
contractName string, deployerKey ethgo.Key) error {
input, err := initInputFn.EncodeAbi()
if err != nil {
return fmt.Errorf("failed to encode initialization params for %s.initialize. error: %w",
contractName, err)
}
if _, err := helper.SendTransaction(txRelayer, ethgo.Address(contractAddr),
input, contractName, deployerKey); err != nil {
return err
}
cmdOutput.WriteCommandResult(
&helper.MessageResult{
Message: fmt.Sprintf("%s %s contract is initialized", contractsDeploymentTitle, contractName),
})
return nil
}