Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: EVM event and deposit handlers refactor #243

Merged
merged 12 commits into from
Jan 18, 2024
3 changes: 1 addition & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@ genmocks:
mockgen --package mock_tss -destination=./tss/mock/storer.go -source=./tss/resharing/resharing.go
mockgen -source=./tss/coordinator.go -destination=./tss/mock/coordinator.go
mockgen -source=./comm/communication.go -destination=./comm/mock/communication.go
mockgen -source=./chains/evm/listener/event-handler.go -destination=./chains/evm/listener/mock/listener.go
mockgen -source=./chains/evm/listener/eventHandlers/event-handler.go -destination=./chains/evm/listener/eventHandlers/mock/listener.go
mockgen -source=./chains/evm/calls/events/listener.go -destination=./chains/evm/calls/events/mock/listener.go
mockgen -source=./chains/substrate/listener/listener.go -destination=./chains/substrate/listener/mock/listener.go
mockgen -source=./chains/substrate/listener/event-handlers.go -destination=./chains/substrate/listener/mock/handlers.go
mockgen -destination=chains/evm/listener/mock/core/listener.go github.com/ChainSafe/chainbridge-core/chains/evm/listener EventListener,DepositHandler
mockgen -source=./topology/topology.go -destination=./topology/mock/topology.go


Expand Down
61 changes: 39 additions & 22 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,7 @@
"syscall"
"time"

coreEvents "github.com/ChainSafe/chainbridge-core/chains/evm/calls/events"
"github.com/ChainSafe/chainbridge-core/chains/evm/calls/evmclient"
"github.com/ChainSafe/chainbridge-core/chains/evm/calls/evmgaspricer"
"github.com/ChainSafe/chainbridge-core/chains/evm/calls/evmtransaction"
"github.com/ChainSafe/chainbridge-core/chains/evm/calls/transactor/monitored"
coreListener "github.com/ChainSafe/chainbridge-core/chains/evm/listener"
"github.com/ChainSafe/chainbridge-core/crypto/secp256k1"
"github.com/ChainSafe/chainbridge-core/flags"
"github.com/ChainSafe/chainbridge-core/logger"
Expand All @@ -32,15 +27,21 @@
"github.com/ChainSafe/sygma-relayer/chains/evm/calls/contracts/bridge"
"github.com/ChainSafe/sygma-relayer/chains/evm/calls/events"
"github.com/ChainSafe/sygma-relayer/chains/evm/executor"
"github.com/ChainSafe/sygma-relayer/chains/evm/listener"
"github.com/ChainSafe/sygma-relayer/chains/evm/listener/depositHandlers"
hubEventHandlers "github.com/ChainSafe/sygma-relayer/chains/evm/listener/eventHandlers"
"github.com/ChainSafe/sygma-relayer/chains/substrate"
"github.com/ChainSafe/sygma-relayer/chains/substrate/client"
"github.com/ChainSafe/sygma-relayer/chains/substrate/connection"
substrateExecutor "github.com/ChainSafe/sygma-relayer/chains/substrate/executor"

Check failure on line 35 in app/app.go

View workflow job for this annotation

GitHub Actions / linter-check

could not import github.com/ChainSafe/sygma-relayer/chains/substrate/executor (-: # github.com/ChainSafe/sygma-relayer/chains/substrate/executor
substrate_listener "github.com/ChainSafe/sygma-relayer/chains/substrate/listener"
substrate_pallet "github.com/ChainSafe/sygma-relayer/chains/substrate/pallet"

Check failure on line 37 in app/app.go

View workflow job for this annotation

GitHub Actions / linter-check

could not import github.com/ChainSafe/sygma-relayer/chains/substrate/pallet (-: # github.com/ChainSafe/sygma-relayer/chains/substrate/pallet
"github.com/ChainSafe/sygma-relayer/metrics"
"github.com/centrifuge/go-substrate-rpc-client/v4/signature"
coreEvm "github.com/sygmaprotocol/sygma-core/chains/evm"
coreClient "github.com/sygmaprotocol/sygma-core/chains/evm/client"
"github.com/sygmaprotocol/sygma-core/chains/evm/listener"
"github.com/sygmaprotocol/sygma-core/chains/evm/transactor/monitored"
"github.com/sygmaprotocol/sygma-core/chains/evm/transactor/transaction"

"github.com/ChainSafe/sygma-relayer/comm/elector"
"github.com/ChainSafe/sygma-relayer/comm/p2p"
Expand Down Expand Up @@ -161,7 +162,7 @@
kp, err := secp256k1.NewKeypairFromString(config.GeneralChainConfig.Key)
panicOnError(err)

client, err := evmclient.NewEVMClient(config.GeneralChainConfig.Endpoint, kp)
client, err := coreClient.NewEVMClient(config.GeneralChainConfig.Endpoint, kp)
panicOnError(err)

log.Info().Str("domain", config.String()).Msgf("Registering EVM domain")
Expand All @@ -171,33 +172,49 @@
UpperLimitFeePerGas: config.MaxGasPrice,
GasPriceFactor: config.GasMultiplier,
})
t := monitored.NewMonitoredTransactor(evmtransaction.NewTransaction, gasPricer, client, config.MaxGasPrice, config.GasIncreasePercentage)
t := monitored.NewMonitoredTransactor(transaction.NewTransaction, gasPricer, client, config.MaxGasPrice, config.GasIncreasePercentage)
go t.Monitor(ctx, time.Minute*3, time.Minute*10, time.Minute)
bridgeContract := bridge.NewBridgeContract(client, bridgeAddress, t)

depositHandler := coreListener.NewETHDepositHandler(bridgeContract)
depositHandler := depositHandlers.NewETHDepositHandler(bridgeContract)
mh := coreMessage.NewMessageHandler()
for _, handler := range config.Handlers {
depositHandler.RegisterDepositHandler(handler.Address, listener.PermissionlessGenericDepositHandler)
mh.RegisterMessageHandler("transfer", &executor.TransferMessageHandler{})

mh.RegisterMessageHandler("Transfer", &executor.TransferMessageHandler{})

switch handler.Type {
case "erc20":
{
depositHandler.RegisterDepositHandler(handler.Address, &depositHandlers.Erc20DepositHandler{})
}
case "permissionedGeneric":
{
depositHandler.RegisterDepositHandler(handler.Address, &depositHandlers.GenericDepositHandler{})
}
case "permissionlessGeneric":
{
depositHandler.RegisterDepositHandler(handler.Address, &depositHandlers.PermissionlessGenericDepositHandler{})
}
case "erc721":
{
depositHandler.RegisterDepositHandler(handler.Address, &depositHandlers.Erc721DepositHandler{})
}
}
}
depositListener := coreEvents.NewListener(client)
depositListener := events.NewListener(client)
tssListener := events.NewListener(client)
eventHandlers := make([]coreListener.EventHandler, 0)
eventHandlers := make([]listener.EventHandler, 0)
l := log.With().Str("chain", fmt.Sprintf("%v", config.GeneralChainConfig.Name)).Uint8("domainID", *config.GeneralChainConfig.Id)
eventHandlers = append(eventHandlers, coreListener.NewDepositEventHandler(depositListener, depositHandler, bridgeAddress, *config.GeneralChainConfig.Id))
eventHandlers = append(eventHandlers, listener.NewKeygenEventHandler(l, tssListener, coordinator, host, communication, keyshareStore, bridgeAddress, networkTopology.Threshold))
eventHandlers = append(eventHandlers, listener.NewRefreshEventHandler(l, topologyProvider, topologyStore, tssListener, coordinator, host, communication, connectionGate, keyshareStore, bridgeAddress))
eventHandlers = append(eventHandlers, listener.NewRetryEventHandler(l, tssListener, depositHandler, bridgeAddress, *config.GeneralChainConfig.Id, config.BlockConfirmations))
evmListener := coreListener.NewEVMListener(client, eventHandlers, blockstore, sygmaMetrics, *config.GeneralChainConfig.Id, config.BlockRetryInterval, config.BlockConfirmations, config.BlockInterval)
eventHandlers = append(eventHandlers, hubEventHandlers.NewDepositEventHandler(depositListener, depositHandler, bridgeAddress, *config.GeneralChainConfig.Id, make(chan []*coreMessage.Message, 1)))
eventHandlers = append(eventHandlers, hubEventHandlers.NewKeygenEventHandler(l, tssListener, coordinator, host, communication, keyshareStore, bridgeAddress, networkTopology.Threshold))
eventHandlers = append(eventHandlers, hubEventHandlers.NewRefreshEventHandler(l, topologyProvider, topologyStore, tssListener, coordinator, host, communication, connectionGate, keyshareStore, bridgeAddress))
eventHandlers = append(eventHandlers, hubEventHandlers.NewRetryEventHandler(l, tssListener, depositHandler, bridgeAddress, *config.GeneralChainConfig.Id, config.BlockConfirmations, make(chan []*coreMessage.Message, 1)))
evmListener := listener.NewEVMListener(client, eventHandlers, blockstore, sygmaMetrics, *config.GeneralChainConfig.Id, config.BlockRetryInterval, config.BlockConfirmations, config.BlockInterval)
executor := executor.NewExecutor(host, communication, coordinator, bridgeContract, keyshareStore, exitLock, config.GasLimit.Uint64())

chain := evm.NewEVMChain(
client, evmListener, executor, blockstore, *config.GeneralChainConfig.Id, config.StartBlock,
config.BlockInterval, config.GeneralChainConfig.FreshStart, config.GeneralChainConfig.LatestBlock,
)
chain := coreEvm.NewEVMChain(evmListener, mh, executor, *config.GeneralChainConfig.Id, config.StartBlock)

chains = append(chains, chain)

Check failure on line 217 in app/app.go

View workflow job for this annotation

GitHub Actions / linter-check

cannot use chain (variable of type *"github.com/sygmaprotocol/sygma-core/chains/evm".EVMChain) as "github.com/ChainSafe/chainbridge-core/relayer".RelayedChain value in argument to append: *"github.com/sygmaprotocol/sygma-core/chains/evm".EVMChain does not implement "github.com/ChainSafe/chainbridge-core/relayer".RelayedChain (wrong type for method PollEvents)
}
case "substrate":
{
Expand Down
176 changes: 25 additions & 151 deletions chains/evm/calls/contracts/bridge/bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,16 @@ import (
"strconv"
"strings"

"github.com/ChainSafe/chainbridge-core/chains/evm/calls"
"github.com/ChainSafe/chainbridge-core/chains/evm/calls/contracts"
"github.com/ChainSafe/chainbridge-core/chains/evm/calls/contracts/deposit"
"github.com/ChainSafe/chainbridge-core/chains/evm/calls/transactor"
"github.com/ChainSafe/chainbridge-core/types"
"github.com/ChainSafe/sygma-relayer/chains"
"github.com/ChainSafe/sygma-relayer/chains/evm/calls/consts"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/rs/zerolog/log"

"github.com/sygmaprotocol/sygma-core/chains/evm/client"
"github.com/sygmaprotocol/sygma-core/chains/evm/contracts"
"github.com/sygmaprotocol/sygma-core/chains/evm/transactor"
)

const bridgeVersion = "3.1.0"
Expand All @@ -32,7 +31,7 @@ type BridgeProposal struct {
}

type ChainClient interface {
calls.ContractCallerDispatcher
client.Client
ChainID(ctx context.Context) (*big.Int, error)
}

Expand All @@ -53,162 +52,36 @@ func NewBridgeContract(
}
}

func (c *BridgeContract) deposit(
resourceID types.ResourceID,
destDomainID uint8,
data []byte,
feeData []byte,
opts transactor.TransactOptions,
) (*common.Hash, error) {
return c.ExecuteTransaction(
"deposit",
opts,
destDomainID, resourceID, data, feeData,
)
}

func (c *BridgeContract) Erc20Deposit(
recipient []byte,
amount *big.Int,
resourceID types.ResourceID,
destDomainID uint8,
feeData []byte,
opts transactor.TransactOptions,
) (*common.Hash, error) {
log.Debug().
Str("recipient", hexutil.Encode(recipient)).
Str("resourceID", hexutil.Encode(resourceID[:])).
Str("amount", amount.String()).
Uint8("destDomainID", destDomainID).
Hex("feeData", feeData).
Msgf("ERC20 deposit")
var data []byte
if opts.Priority == 0 {
data = deposit.ConstructErc20DepositData(recipient, amount)
} else {
data = deposit.ConstructErc20DepositDataWithPriority(recipient, amount, opts.Priority)
}

txHash, err := c.deposit(resourceID, destDomainID, data, feeData, opts)
if err != nil {
log.Error().Err(err)
return nil, err
}
return txHash, err
}

func (c *BridgeContract) Erc721Deposit(
tokenId *big.Int,
metadata string,
recipient common.Address,
resourceID types.ResourceID,
destDomainID uint8,
feeData []byte,
opts transactor.TransactOptions,
) (*common.Hash, error) {
log.Debug().
Str("recipient", recipient.String()).
Str("resourceID", hexutil.Encode(resourceID[:])).
Str("tokenID", tokenId.String()).
Uint8("destDomainID", destDomainID).
Hex("feeData", feeData).
Msgf("ERC721 deposit")
var data []byte
if opts.Priority == 0 {
data = deposit.ConstructErc721DepositData(recipient.Bytes(), tokenId, []byte(metadata))
} else {
data = deposit.ConstructErc721DepositDataWithPriority(recipient.Bytes(), tokenId, []byte(metadata), opts.Priority)
}

txHash, err := c.deposit(resourceID, destDomainID, data, feeData, opts)
if err != nil {
log.Error().Err(err)
return nil, err
}
return txHash, err
}

func (c *BridgeContract) GenericDeposit(
metadata []byte,
resourceID types.ResourceID,
destDomainID uint8,
feeData []byte,
opts transactor.TransactOptions,
) (*common.Hash, error) {
log.Debug().
Str("resourceID", hexutil.Encode(resourceID[:])).
Uint8("destDomainID", destDomainID).
Hex("feeData", feeData).
Msgf("Generic deposit")
data := deposit.ConstructGenericDepositData(metadata)

txHash, err := c.deposit(resourceID, destDomainID, data, feeData, opts)
if err != nil {
log.Error().Err(err)
return nil, err
}
return txHash, err
}

func (c *BridgeContract) PermissionlessGenericDeposit(
metadata []byte,
executeFunctionSig string,
executeContractAddress *common.Address,
depositor *common.Address,
maxFee *big.Int,
resourceID types.ResourceID,
destDomainID uint8,
feeData []byte,
opts transactor.TransactOptions,
) (*common.Hash, error) {
log.Debug().
Str("resourceID", hexutil.Encode(resourceID[:])).
Uint8("destDomainID", destDomainID).
Hex("feeData", feeData).
Msgf("Permissionless Generic deposit")
data := ConstructPermissionlessGenericDepositData(metadata, []byte(executeFunctionSig), executeContractAddress.Bytes(), depositor.Bytes(), maxFee)
txHash, err := c.deposit(
resourceID,
destDomainID,
data,
feeData,
opts,
)
if err != nil {
log.Error().Err(err)
return nil, err
}
return txHash, err
}

func (c *BridgeContract) ExecuteProposal(
proposal *chains.Proposal,
proposal *chains.TransferProposal,
signature []byte,
opts transactor.TransactOptions,
) (*common.Hash, error) {
log.Debug().
Str("depositNonce", strconv.FormatUint(proposal.DepositNonce, 10)).
Str("resourceID", hexutil.Encode(proposal.ResourceID[:])).
Str("depositNonce", strconv.FormatUint(proposal.Data.DepositNonce, 10)).
Str("resourceID", hexutil.Encode(proposal.Data.ResourceId[:])).
Msgf("Execute proposal")
return c.ExecuteTransaction(
"executeProposal",
opts,
proposal.OriginDomainID, proposal.DepositNonce, proposal.Data, proposal.ResourceID, signature,
proposal.Source, proposal.Data.DepositNonce, proposal.Data, proposal.Data.ResourceId, signature,
)
}

func (c *BridgeContract) ExecuteProposals(
proposals []*chains.Proposal,
proposals []*chains.TransferProposal,
signature []byte,
opts transactor.TransactOptions,
) (*common.Hash, error) {
bridgeProposals := make([]chains.Proposal, 0)
bridgeProposals := make([]chains.TransferProposal, 0)
for _, prop := range proposals {
bridgeProposals = append(bridgeProposals, chains.Proposal{
OriginDomainID: prop.OriginDomainID,
DepositNonce: prop.DepositNonce,
ResourceID: prop.ResourceID,
Data: prop.Data,
bridgeProposals = append(bridgeProposals, chains.TransferProposal{
Source: prop.Source,
Data: chains.TransferProposalData{
DepositNonce: prop.Data.DepositNonce,
ResourceId: prop.Data.ResourceId,
Data: prop.Data.Data,
},
})
}

Expand All @@ -220,20 +93,21 @@ func (c *BridgeContract) ExecuteProposals(
)
}

func (c *BridgeContract) ProposalsHash(proposals []*chains.Proposal) ([]byte, error) {
func (c *BridgeContract) ProposalsHash(proposals []*chains.TransferProposal) ([]byte, error) {
chainID, err := c.client.ChainID(context.Background())
if err != nil {
return []byte{}, err
}
return chains.ProposalsHash(proposals, chainID.Int64(), c.ContractAddress().Hex(), bridgeVersion)
}

func (c *BridgeContract) IsProposalExecuted(p *chains.Proposal) (bool, error) {
func (c *BridgeContract) IsProposalExecuted(p *chains.TransferProposal) (bool, error) {

log.Debug().
Str("depositNonce", strconv.FormatUint(p.DepositNonce, 10)).
Str("resourceID", hexutil.Encode(p.ResourceID[:])).
Str("depositNonce", strconv.FormatUint(p.Data.DepositNonce, 10)).
Str("resourceID", hexutil.Encode(p.Data.ResourceId[:])).
Msg("Getting is proposal executed")
res, err := c.CallContract("isProposalExecuted", p.OriginDomainID, big.NewInt(int64(p.DepositNonce)))
res, err := c.CallContract("isProposalExecuted", p.Source, big.NewInt(int64(p.Data.DepositNonce)))
if err != nil {
return false, err
}
Expand All @@ -242,7 +116,7 @@ func (c *BridgeContract) IsProposalExecuted(p *chains.Proposal) (bool, error) {
}

func (c *BridgeContract) GetHandlerAddressForResourceID(
resourceID types.ResourceID,
resourceID [32]byte,
) (common.Address, error) {
log.Debug().Msgf("Getting handler address for resource %s", hexutil.Encode(resourceID[:]))
res, err := c.CallContract("_resourceIDToHandlerAddress", resourceID)
Expand Down
23 changes: 0 additions & 23 deletions chains/evm/calls/contracts/bridge/deposit.go

This file was deleted.

Loading
Loading